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     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5816       int ClauseKindCnt = -1;
5817       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5818         ++ClauseKindCnt;
5819         if (ImplicitMap.empty())
5820           continue;
5821         CXXScopeSpec MapperIdScopeSpec;
5822         DeclarationNameInfo MapperId;
5823         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5824         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5825                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5826                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5827                 SourceLocation(), SourceLocation(), ImplicitMap,
5828                 OMPVarListLocTy())) {
5829           ClausesWithImplicit.emplace_back(Implicit);
5830           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5831                         ImplicitMap.size();
5832         } else {
5833           ErrorFound = true;
5834         }
5835       }
5836     }
5837     // Build expressions for implicit maps of data members with 'default'
5838     // mappers.
5839     if (LangOpts.OpenMP >= 50)
5840       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5841                                             ClausesWithImplicit);
5842   }
5843 
5844   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5845   switch (Kind) {
5846   case OMPD_parallel:
5847     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5848                                        EndLoc);
5849     AllowedNameModifiers.push_back(OMPD_parallel);
5850     break;
5851   case OMPD_simd:
5852     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5853                                    VarsWithInheritedDSA);
5854     if (LangOpts.OpenMP >= 50)
5855       AllowedNameModifiers.push_back(OMPD_simd);
5856     break;
5857   case OMPD_tile:
5858     Res =
5859         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5860     break;
5861   case OMPD_unroll:
5862     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
5863                                      EndLoc);
5864     break;
5865   case OMPD_for:
5866     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5867                                   VarsWithInheritedDSA);
5868     break;
5869   case OMPD_for_simd:
5870     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5871                                       EndLoc, VarsWithInheritedDSA);
5872     if (LangOpts.OpenMP >= 50)
5873       AllowedNameModifiers.push_back(OMPD_simd);
5874     break;
5875   case OMPD_sections:
5876     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5877                                        EndLoc);
5878     break;
5879   case OMPD_section:
5880     assert(ClausesWithImplicit.empty() &&
5881            "No clauses are allowed for 'omp section' directive");
5882     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5883     break;
5884   case OMPD_single:
5885     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5886                                      EndLoc);
5887     break;
5888   case OMPD_master:
5889     assert(ClausesWithImplicit.empty() &&
5890            "No clauses are allowed for 'omp master' directive");
5891     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5892     break;
5893   case OMPD_masked:
5894     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
5895                                      EndLoc);
5896     break;
5897   case OMPD_critical:
5898     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5899                                        StartLoc, EndLoc);
5900     break;
5901   case OMPD_parallel_for:
5902     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5903                                           EndLoc, VarsWithInheritedDSA);
5904     AllowedNameModifiers.push_back(OMPD_parallel);
5905     break;
5906   case OMPD_parallel_for_simd:
5907     Res = ActOnOpenMPParallelForSimdDirective(
5908         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5909     AllowedNameModifiers.push_back(OMPD_parallel);
5910     if (LangOpts.OpenMP >= 50)
5911       AllowedNameModifiers.push_back(OMPD_simd);
5912     break;
5913   case OMPD_parallel_master:
5914     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5915                                                StartLoc, EndLoc);
5916     AllowedNameModifiers.push_back(OMPD_parallel);
5917     break;
5918   case OMPD_parallel_sections:
5919     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5920                                                StartLoc, EndLoc);
5921     AllowedNameModifiers.push_back(OMPD_parallel);
5922     break;
5923   case OMPD_task:
5924     Res =
5925         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5926     AllowedNameModifiers.push_back(OMPD_task);
5927     break;
5928   case OMPD_taskyield:
5929     assert(ClausesWithImplicit.empty() &&
5930            "No clauses are allowed for 'omp taskyield' directive");
5931     assert(AStmt == nullptr &&
5932            "No associated statement allowed for 'omp taskyield' directive");
5933     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5934     break;
5935   case OMPD_barrier:
5936     assert(ClausesWithImplicit.empty() &&
5937            "No clauses are allowed for 'omp barrier' directive");
5938     assert(AStmt == nullptr &&
5939            "No associated statement allowed for 'omp barrier' directive");
5940     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5941     break;
5942   case OMPD_taskwait:
5943     assert(ClausesWithImplicit.empty() &&
5944            "No clauses are allowed for 'omp taskwait' directive");
5945     assert(AStmt == nullptr &&
5946            "No associated statement allowed for 'omp taskwait' directive");
5947     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5948     break;
5949   case OMPD_taskgroup:
5950     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5951                                         EndLoc);
5952     break;
5953   case OMPD_flush:
5954     assert(AStmt == nullptr &&
5955            "No associated statement allowed for 'omp flush' directive");
5956     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5957     break;
5958   case OMPD_depobj:
5959     assert(AStmt == nullptr &&
5960            "No associated statement allowed for 'omp depobj' directive");
5961     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5962     break;
5963   case OMPD_scan:
5964     assert(AStmt == nullptr &&
5965            "No associated statement allowed for 'omp scan' directive");
5966     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5967     break;
5968   case OMPD_ordered:
5969     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5970                                       EndLoc);
5971     break;
5972   case OMPD_atomic:
5973     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5974                                      EndLoc);
5975     break;
5976   case OMPD_teams:
5977     Res =
5978         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5979     break;
5980   case OMPD_target:
5981     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5982                                      EndLoc);
5983     AllowedNameModifiers.push_back(OMPD_target);
5984     break;
5985   case OMPD_target_parallel:
5986     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5987                                              StartLoc, EndLoc);
5988     AllowedNameModifiers.push_back(OMPD_target);
5989     AllowedNameModifiers.push_back(OMPD_parallel);
5990     break;
5991   case OMPD_target_parallel_for:
5992     Res = ActOnOpenMPTargetParallelForDirective(
5993         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5994     AllowedNameModifiers.push_back(OMPD_target);
5995     AllowedNameModifiers.push_back(OMPD_parallel);
5996     break;
5997   case OMPD_cancellation_point:
5998     assert(ClausesWithImplicit.empty() &&
5999            "No clauses are allowed for 'omp cancellation point' directive");
6000     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6001                                "cancellation point' directive");
6002     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6003     break;
6004   case OMPD_cancel:
6005     assert(AStmt == nullptr &&
6006            "No associated statement allowed for 'omp cancel' directive");
6007     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6008                                      CancelRegion);
6009     AllowedNameModifiers.push_back(OMPD_cancel);
6010     break;
6011   case OMPD_target_data:
6012     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6013                                          EndLoc);
6014     AllowedNameModifiers.push_back(OMPD_target_data);
6015     break;
6016   case OMPD_target_enter_data:
6017     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6018                                               EndLoc, AStmt);
6019     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6020     break;
6021   case OMPD_target_exit_data:
6022     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6023                                              EndLoc, AStmt);
6024     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6025     break;
6026   case OMPD_taskloop:
6027     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6028                                        EndLoc, VarsWithInheritedDSA);
6029     AllowedNameModifiers.push_back(OMPD_taskloop);
6030     break;
6031   case OMPD_taskloop_simd:
6032     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6033                                            EndLoc, VarsWithInheritedDSA);
6034     AllowedNameModifiers.push_back(OMPD_taskloop);
6035     if (LangOpts.OpenMP >= 50)
6036       AllowedNameModifiers.push_back(OMPD_simd);
6037     break;
6038   case OMPD_master_taskloop:
6039     Res = ActOnOpenMPMasterTaskLoopDirective(
6040         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6041     AllowedNameModifiers.push_back(OMPD_taskloop);
6042     break;
6043   case OMPD_master_taskloop_simd:
6044     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6045         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6046     AllowedNameModifiers.push_back(OMPD_taskloop);
6047     if (LangOpts.OpenMP >= 50)
6048       AllowedNameModifiers.push_back(OMPD_simd);
6049     break;
6050   case OMPD_parallel_master_taskloop:
6051     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6052         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6053     AllowedNameModifiers.push_back(OMPD_taskloop);
6054     AllowedNameModifiers.push_back(OMPD_parallel);
6055     break;
6056   case OMPD_parallel_master_taskloop_simd:
6057     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6058         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6059     AllowedNameModifiers.push_back(OMPD_taskloop);
6060     AllowedNameModifiers.push_back(OMPD_parallel);
6061     if (LangOpts.OpenMP >= 50)
6062       AllowedNameModifiers.push_back(OMPD_simd);
6063     break;
6064   case OMPD_distribute:
6065     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6066                                          EndLoc, VarsWithInheritedDSA);
6067     break;
6068   case OMPD_target_update:
6069     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6070                                            EndLoc, AStmt);
6071     AllowedNameModifiers.push_back(OMPD_target_update);
6072     break;
6073   case OMPD_distribute_parallel_for:
6074     Res = ActOnOpenMPDistributeParallelForDirective(
6075         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6076     AllowedNameModifiers.push_back(OMPD_parallel);
6077     break;
6078   case OMPD_distribute_parallel_for_simd:
6079     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6080         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6081     AllowedNameModifiers.push_back(OMPD_parallel);
6082     if (LangOpts.OpenMP >= 50)
6083       AllowedNameModifiers.push_back(OMPD_simd);
6084     break;
6085   case OMPD_distribute_simd:
6086     Res = ActOnOpenMPDistributeSimdDirective(
6087         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6088     if (LangOpts.OpenMP >= 50)
6089       AllowedNameModifiers.push_back(OMPD_simd);
6090     break;
6091   case OMPD_target_parallel_for_simd:
6092     Res = ActOnOpenMPTargetParallelForSimdDirective(
6093         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6094     AllowedNameModifiers.push_back(OMPD_target);
6095     AllowedNameModifiers.push_back(OMPD_parallel);
6096     if (LangOpts.OpenMP >= 50)
6097       AllowedNameModifiers.push_back(OMPD_simd);
6098     break;
6099   case OMPD_target_simd:
6100     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6101                                          EndLoc, VarsWithInheritedDSA);
6102     AllowedNameModifiers.push_back(OMPD_target);
6103     if (LangOpts.OpenMP >= 50)
6104       AllowedNameModifiers.push_back(OMPD_simd);
6105     break;
6106   case OMPD_teams_distribute:
6107     Res = ActOnOpenMPTeamsDistributeDirective(
6108         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6109     break;
6110   case OMPD_teams_distribute_simd:
6111     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6112         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6113     if (LangOpts.OpenMP >= 50)
6114       AllowedNameModifiers.push_back(OMPD_simd);
6115     break;
6116   case OMPD_teams_distribute_parallel_for_simd:
6117     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6118         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6119     AllowedNameModifiers.push_back(OMPD_parallel);
6120     if (LangOpts.OpenMP >= 50)
6121       AllowedNameModifiers.push_back(OMPD_simd);
6122     break;
6123   case OMPD_teams_distribute_parallel_for:
6124     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6125         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6126     AllowedNameModifiers.push_back(OMPD_parallel);
6127     break;
6128   case OMPD_target_teams:
6129     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6130                                           EndLoc);
6131     AllowedNameModifiers.push_back(OMPD_target);
6132     break;
6133   case OMPD_target_teams_distribute:
6134     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6135         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6136     AllowedNameModifiers.push_back(OMPD_target);
6137     break;
6138   case OMPD_target_teams_distribute_parallel_for:
6139     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6140         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6141     AllowedNameModifiers.push_back(OMPD_target);
6142     AllowedNameModifiers.push_back(OMPD_parallel);
6143     break;
6144   case OMPD_target_teams_distribute_parallel_for_simd:
6145     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6146         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6147     AllowedNameModifiers.push_back(OMPD_target);
6148     AllowedNameModifiers.push_back(OMPD_parallel);
6149     if (LangOpts.OpenMP >= 50)
6150       AllowedNameModifiers.push_back(OMPD_simd);
6151     break;
6152   case OMPD_target_teams_distribute_simd:
6153     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6154         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6155     AllowedNameModifiers.push_back(OMPD_target);
6156     if (LangOpts.OpenMP >= 50)
6157       AllowedNameModifiers.push_back(OMPD_simd);
6158     break;
6159   case OMPD_interop:
6160     assert(AStmt == nullptr &&
6161            "No associated statement allowed for 'omp interop' directive");
6162     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6163     break;
6164   case OMPD_dispatch:
6165     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6166                                        EndLoc);
6167     break;
6168   case OMPD_declare_target:
6169   case OMPD_end_declare_target:
6170   case OMPD_threadprivate:
6171   case OMPD_allocate:
6172   case OMPD_declare_reduction:
6173   case OMPD_declare_mapper:
6174   case OMPD_declare_simd:
6175   case OMPD_requires:
6176   case OMPD_declare_variant:
6177   case OMPD_begin_declare_variant:
6178   case OMPD_end_declare_variant:
6179     llvm_unreachable("OpenMP Directive is not allowed");
6180   case OMPD_unknown:
6181   default:
6182     llvm_unreachable("Unknown OpenMP directive");
6183   }
6184 
6185   ErrorFound = Res.isInvalid() || ErrorFound;
6186 
6187   // Check variables in the clauses if default(none) or
6188   // default(firstprivate) was specified.
6189   if (DSAStack->getDefaultDSA() == DSA_none ||
6190       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6191     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6192     for (OMPClause *C : Clauses) {
6193       switch (C->getClauseKind()) {
6194       case OMPC_num_threads:
6195       case OMPC_dist_schedule:
6196         // Do not analyse if no parent teams directive.
6197         if (isOpenMPTeamsDirective(Kind))
6198           break;
6199         continue;
6200       case OMPC_if:
6201         if (isOpenMPTeamsDirective(Kind) &&
6202             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6203           break;
6204         if (isOpenMPParallelDirective(Kind) &&
6205             isOpenMPTaskLoopDirective(Kind) &&
6206             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6207           break;
6208         continue;
6209       case OMPC_schedule:
6210       case OMPC_detach:
6211         break;
6212       case OMPC_grainsize:
6213       case OMPC_num_tasks:
6214       case OMPC_final:
6215       case OMPC_priority:
6216       case OMPC_novariants:
6217       case OMPC_nocontext:
6218         // Do not analyze if no parent parallel directive.
6219         if (isOpenMPParallelDirective(Kind))
6220           break;
6221         continue;
6222       case OMPC_ordered:
6223       case OMPC_device:
6224       case OMPC_num_teams:
6225       case OMPC_thread_limit:
6226       case OMPC_hint:
6227       case OMPC_collapse:
6228       case OMPC_safelen:
6229       case OMPC_simdlen:
6230       case OMPC_sizes:
6231       case OMPC_default:
6232       case OMPC_proc_bind:
6233       case OMPC_private:
6234       case OMPC_firstprivate:
6235       case OMPC_lastprivate:
6236       case OMPC_shared:
6237       case OMPC_reduction:
6238       case OMPC_task_reduction:
6239       case OMPC_in_reduction:
6240       case OMPC_linear:
6241       case OMPC_aligned:
6242       case OMPC_copyin:
6243       case OMPC_copyprivate:
6244       case OMPC_nowait:
6245       case OMPC_untied:
6246       case OMPC_mergeable:
6247       case OMPC_allocate:
6248       case OMPC_read:
6249       case OMPC_write:
6250       case OMPC_update:
6251       case OMPC_capture:
6252       case OMPC_seq_cst:
6253       case OMPC_acq_rel:
6254       case OMPC_acquire:
6255       case OMPC_release:
6256       case OMPC_relaxed:
6257       case OMPC_depend:
6258       case OMPC_threads:
6259       case OMPC_simd:
6260       case OMPC_map:
6261       case OMPC_nogroup:
6262       case OMPC_defaultmap:
6263       case OMPC_to:
6264       case OMPC_from:
6265       case OMPC_use_device_ptr:
6266       case OMPC_use_device_addr:
6267       case OMPC_is_device_ptr:
6268       case OMPC_nontemporal:
6269       case OMPC_order:
6270       case OMPC_destroy:
6271       case OMPC_inclusive:
6272       case OMPC_exclusive:
6273       case OMPC_uses_allocators:
6274       case OMPC_affinity:
6275         continue;
6276       case OMPC_allocator:
6277       case OMPC_flush:
6278       case OMPC_depobj:
6279       case OMPC_threadprivate:
6280       case OMPC_uniform:
6281       case OMPC_unknown:
6282       case OMPC_unified_address:
6283       case OMPC_unified_shared_memory:
6284       case OMPC_reverse_offload:
6285       case OMPC_dynamic_allocators:
6286       case OMPC_atomic_default_mem_order:
6287       case OMPC_device_type:
6288       case OMPC_match:
6289       default:
6290         llvm_unreachable("Unexpected clause");
6291       }
6292       for (Stmt *CC : C->children()) {
6293         if (CC)
6294           DSAChecker.Visit(CC);
6295       }
6296     }
6297     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6298       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6299   }
6300   for (const auto &P : VarsWithInheritedDSA) {
6301     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6302       continue;
6303     ErrorFound = true;
6304     if (DSAStack->getDefaultDSA() == DSA_none ||
6305         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6306       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6307           << P.first << P.second->getSourceRange();
6308       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6309     } else if (getLangOpts().OpenMP >= 50) {
6310       Diag(P.second->getExprLoc(),
6311            diag::err_omp_defaultmap_no_attr_for_variable)
6312           << P.first << P.second->getSourceRange();
6313       Diag(DSAStack->getDefaultDSALocation(),
6314            diag::note_omp_defaultmap_attr_none);
6315     }
6316   }
6317 
6318   if (!AllowedNameModifiers.empty())
6319     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6320                  ErrorFound;
6321 
6322   if (ErrorFound)
6323     return StmtError();
6324 
6325   if (!CurContext->isDependentContext() &&
6326       isOpenMPTargetExecutionDirective(Kind) &&
6327       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6328         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6329         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6330         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6331     // Register target to DSA Stack.
6332     DSAStack->addTargetDirLocation(StartLoc);
6333   }
6334 
6335   return Res;
6336 }
6337 
6338 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6339     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6340     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6341     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6342     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6343   assert(Aligneds.size() == Alignments.size());
6344   assert(Linears.size() == LinModifiers.size());
6345   assert(Linears.size() == Steps.size());
6346   if (!DG || DG.get().isNull())
6347     return DeclGroupPtrTy();
6348 
6349   const int SimdId = 0;
6350   if (!DG.get().isSingleDecl()) {
6351     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6352         << SimdId;
6353     return DG;
6354   }
6355   Decl *ADecl = DG.get().getSingleDecl();
6356   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6357     ADecl = FTD->getTemplatedDecl();
6358 
6359   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6360   if (!FD) {
6361     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6362     return DeclGroupPtrTy();
6363   }
6364 
6365   // OpenMP [2.8.2, declare simd construct, Description]
6366   // The parameter of the simdlen clause must be a constant positive integer
6367   // expression.
6368   ExprResult SL;
6369   if (Simdlen)
6370     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6371   // OpenMP [2.8.2, declare simd construct, Description]
6372   // The special this pointer can be used as if was one of the arguments to the
6373   // function in any of the linear, aligned, or uniform clauses.
6374   // The uniform clause declares one or more arguments to have an invariant
6375   // value for all concurrent invocations of the function in the execution of a
6376   // single SIMD loop.
6377   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6378   const Expr *UniformedLinearThis = nullptr;
6379   for (const Expr *E : Uniforms) {
6380     E = E->IgnoreParenImpCasts();
6381     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6382       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6383         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6384             FD->getParamDecl(PVD->getFunctionScopeIndex())
6385                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6386           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6387           continue;
6388         }
6389     if (isa<CXXThisExpr>(E)) {
6390       UniformedLinearThis = E;
6391       continue;
6392     }
6393     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6394         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6395   }
6396   // OpenMP [2.8.2, declare simd construct, Description]
6397   // The aligned clause declares that the object to which each list item points
6398   // is aligned to the number of bytes expressed in the optional parameter of
6399   // the aligned clause.
6400   // The special this pointer can be used as if was one of the arguments to the
6401   // function in any of the linear, aligned, or uniform clauses.
6402   // The type of list items appearing in the aligned clause must be array,
6403   // pointer, reference to array, or reference to pointer.
6404   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6405   const Expr *AlignedThis = nullptr;
6406   for (const Expr *E : Aligneds) {
6407     E = E->IgnoreParenImpCasts();
6408     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6409       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6410         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6411         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6412             FD->getParamDecl(PVD->getFunctionScopeIndex())
6413                     ->getCanonicalDecl() == CanonPVD) {
6414           // OpenMP  [2.8.1, simd construct, Restrictions]
6415           // A list-item cannot appear in more than one aligned clause.
6416           if (AlignedArgs.count(CanonPVD) > 0) {
6417             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6418                 << 1 << getOpenMPClauseName(OMPC_aligned)
6419                 << E->getSourceRange();
6420             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6421                  diag::note_omp_explicit_dsa)
6422                 << getOpenMPClauseName(OMPC_aligned);
6423             continue;
6424           }
6425           AlignedArgs[CanonPVD] = E;
6426           QualType QTy = PVD->getType()
6427                              .getNonReferenceType()
6428                              .getUnqualifiedType()
6429                              .getCanonicalType();
6430           const Type *Ty = QTy.getTypePtrOrNull();
6431           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6432             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6433                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6434             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6435           }
6436           continue;
6437         }
6438       }
6439     if (isa<CXXThisExpr>(E)) {
6440       if (AlignedThis) {
6441         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6442             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6443         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6444             << getOpenMPClauseName(OMPC_aligned);
6445       }
6446       AlignedThis = E;
6447       continue;
6448     }
6449     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6450         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6451   }
6452   // The optional parameter of the aligned clause, alignment, must be a constant
6453   // positive integer expression. If no optional parameter is specified,
6454   // implementation-defined default alignments for SIMD instructions on the
6455   // target platforms are assumed.
6456   SmallVector<const Expr *, 4> NewAligns;
6457   for (Expr *E : Alignments) {
6458     ExprResult Align;
6459     if (E)
6460       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6461     NewAligns.push_back(Align.get());
6462   }
6463   // OpenMP [2.8.2, declare simd construct, Description]
6464   // The linear clause declares one or more list items to be private to a SIMD
6465   // lane and to have a linear relationship with respect to the iteration space
6466   // of a loop.
6467   // The special this pointer can be used as if was one of the arguments to the
6468   // function in any of the linear, aligned, or uniform clauses.
6469   // When a linear-step expression is specified in a linear clause it must be
6470   // either a constant integer expression or an integer-typed parameter that is
6471   // specified in a uniform clause on the directive.
6472   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6473   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6474   auto MI = LinModifiers.begin();
6475   for (const Expr *E : Linears) {
6476     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6477     ++MI;
6478     E = E->IgnoreParenImpCasts();
6479     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6480       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6481         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6482         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6483             FD->getParamDecl(PVD->getFunctionScopeIndex())
6484                     ->getCanonicalDecl() == CanonPVD) {
6485           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6486           // A list-item cannot appear in more than one linear clause.
6487           if (LinearArgs.count(CanonPVD) > 0) {
6488             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6489                 << getOpenMPClauseName(OMPC_linear)
6490                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6491             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6492                  diag::note_omp_explicit_dsa)
6493                 << getOpenMPClauseName(OMPC_linear);
6494             continue;
6495           }
6496           // Each argument can appear in at most one uniform or linear clause.
6497           if (UniformedArgs.count(CanonPVD) > 0) {
6498             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6499                 << getOpenMPClauseName(OMPC_linear)
6500                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6501             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6502                  diag::note_omp_explicit_dsa)
6503                 << getOpenMPClauseName(OMPC_uniform);
6504             continue;
6505           }
6506           LinearArgs[CanonPVD] = E;
6507           if (E->isValueDependent() || E->isTypeDependent() ||
6508               E->isInstantiationDependent() ||
6509               E->containsUnexpandedParameterPack())
6510             continue;
6511           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6512                                       PVD->getOriginalType(),
6513                                       /*IsDeclareSimd=*/true);
6514           continue;
6515         }
6516       }
6517     if (isa<CXXThisExpr>(E)) {
6518       if (UniformedLinearThis) {
6519         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6520             << getOpenMPClauseName(OMPC_linear)
6521             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6522             << E->getSourceRange();
6523         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6524             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6525                                                    : OMPC_linear);
6526         continue;
6527       }
6528       UniformedLinearThis = E;
6529       if (E->isValueDependent() || E->isTypeDependent() ||
6530           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6531         continue;
6532       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6533                                   E->getType(), /*IsDeclareSimd=*/true);
6534       continue;
6535     }
6536     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6537         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6538   }
6539   Expr *Step = nullptr;
6540   Expr *NewStep = nullptr;
6541   SmallVector<Expr *, 4> NewSteps;
6542   for (Expr *E : Steps) {
6543     // Skip the same step expression, it was checked already.
6544     if (Step == E || !E) {
6545       NewSteps.push_back(E ? NewStep : nullptr);
6546       continue;
6547     }
6548     Step = E;
6549     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6550       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6551         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6552         if (UniformedArgs.count(CanonPVD) == 0) {
6553           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6554               << Step->getSourceRange();
6555         } else if (E->isValueDependent() || E->isTypeDependent() ||
6556                    E->isInstantiationDependent() ||
6557                    E->containsUnexpandedParameterPack() ||
6558                    CanonPVD->getType()->hasIntegerRepresentation()) {
6559           NewSteps.push_back(Step);
6560         } else {
6561           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6562               << Step->getSourceRange();
6563         }
6564         continue;
6565       }
6566     NewStep = Step;
6567     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6568         !Step->isInstantiationDependent() &&
6569         !Step->containsUnexpandedParameterPack()) {
6570       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6571                     .get();
6572       if (NewStep)
6573         NewStep =
6574             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6575     }
6576     NewSteps.push_back(NewStep);
6577   }
6578   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6579       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6580       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6581       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6582       const_cast<Expr **>(Linears.data()), Linears.size(),
6583       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6584       NewSteps.data(), NewSteps.size(), SR);
6585   ADecl->addAttr(NewAttr);
6586   return DG;
6587 }
6588 
6589 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6590                          QualType NewType) {
6591   assert(NewType->isFunctionProtoType() &&
6592          "Expected function type with prototype.");
6593   assert(FD->getType()->isFunctionNoProtoType() &&
6594          "Expected function with type with no prototype.");
6595   assert(FDWithProto->getType()->isFunctionProtoType() &&
6596          "Expected function with prototype.");
6597   // Synthesize parameters with the same types.
6598   FD->setType(NewType);
6599   SmallVector<ParmVarDecl *, 16> Params;
6600   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6601     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6602                                       SourceLocation(), nullptr, P->getType(),
6603                                       /*TInfo=*/nullptr, SC_None, nullptr);
6604     Param->setScopeInfo(0, Params.size());
6605     Param->setImplicit();
6606     Params.push_back(Param);
6607   }
6608 
6609   FD->setParams(Params);
6610 }
6611 
6612 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6613   if (D->isInvalidDecl())
6614     return;
6615   FunctionDecl *FD = nullptr;
6616   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6617     FD = UTemplDecl->getTemplatedDecl();
6618   else
6619     FD = cast<FunctionDecl>(D);
6620   assert(FD && "Expected a function declaration!");
6621 
6622   // If we are intantiating templates we do *not* apply scoped assumptions but
6623   // only global ones. We apply scoped assumption to the template definition
6624   // though.
6625   if (!inTemplateInstantiation()) {
6626     for (AssumptionAttr *AA : OMPAssumeScoped)
6627       FD->addAttr(AA);
6628   }
6629   for (AssumptionAttr *AA : OMPAssumeGlobal)
6630     FD->addAttr(AA);
6631 }
6632 
6633 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6634     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6635 
6636 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6637     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6638     SmallVectorImpl<FunctionDecl *> &Bases) {
6639   if (!D.getIdentifier())
6640     return;
6641 
6642   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6643 
6644   // Template specialization is an extension, check if we do it.
6645   bool IsTemplated = !TemplateParamLists.empty();
6646   if (IsTemplated &
6647       !DVScope.TI->isExtensionActive(
6648           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6649     return;
6650 
6651   IdentifierInfo *BaseII = D.getIdentifier();
6652   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6653                       LookupOrdinaryName);
6654   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6655 
6656   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6657   QualType FType = TInfo->getType();
6658 
6659   bool IsConstexpr =
6660       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6661   bool IsConsteval =
6662       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6663 
6664   for (auto *Candidate : Lookup) {
6665     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6666     FunctionDecl *UDecl = nullptr;
6667     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl))
6668       UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl();
6669     else if (!IsTemplated)
6670       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6671     if (!UDecl)
6672       continue;
6673 
6674     // Don't specialize constexpr/consteval functions with
6675     // non-constexpr/consteval functions.
6676     if (UDecl->isConstexpr() && !IsConstexpr)
6677       continue;
6678     if (UDecl->isConsteval() && !IsConsteval)
6679       continue;
6680 
6681     QualType UDeclTy = UDecl->getType();
6682     if (!UDeclTy->isDependentType()) {
6683       QualType NewType = Context.mergeFunctionTypes(
6684           FType, UDeclTy, /* OfBlockPointer */ false,
6685           /* Unqualified */ false, /* AllowCXX */ true);
6686       if (NewType.isNull())
6687         continue;
6688     }
6689 
6690     // Found a base!
6691     Bases.push_back(UDecl);
6692   }
6693 
6694   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6695       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6696   // If no base was found we create a declaration that we use as base.
6697   if (Bases.empty() && UseImplicitBase) {
6698     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6699     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6700     BaseD->setImplicit(true);
6701     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6702       Bases.push_back(BaseTemplD->getTemplatedDecl());
6703     else
6704       Bases.push_back(cast<FunctionDecl>(BaseD));
6705   }
6706 
6707   std::string MangledName;
6708   MangledName += D.getIdentifier()->getName();
6709   MangledName += getOpenMPVariantManglingSeparatorStr();
6710   MangledName += DVScope.NameSuffix;
6711   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6712 
6713   VariantII.setMangledOpenMPVariantName(true);
6714   D.SetIdentifier(&VariantII, D.getBeginLoc());
6715 }
6716 
6717 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6718     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6719   // Do not mark function as is used to prevent its emission if this is the
6720   // only place where it is used.
6721   EnterExpressionEvaluationContext Unevaluated(
6722       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6723 
6724   FunctionDecl *FD = nullptr;
6725   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6726     FD = UTemplDecl->getTemplatedDecl();
6727   else
6728     FD = cast<FunctionDecl>(D);
6729   auto *VariantFuncRef = DeclRefExpr::Create(
6730       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6731       /* RefersToEnclosingVariableOrCapture */ false,
6732       /* NameLoc */ FD->getLocation(), FD->getType(),
6733       ExprValueKind::VK_PRValue);
6734 
6735   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6736   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6737       Context, VariantFuncRef, DVScope.TI);
6738   for (FunctionDecl *BaseFD : Bases)
6739     BaseFD->addAttr(OMPDeclareVariantA);
6740 }
6741 
6742 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6743                                  SourceLocation LParenLoc,
6744                                  MultiExprArg ArgExprs,
6745                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6746   // The common case is a regular call we do not want to specialize at all. Try
6747   // to make that case fast by bailing early.
6748   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6749   if (!CE)
6750     return Call;
6751 
6752   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6753   if (!CalleeFnDecl)
6754     return Call;
6755 
6756   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6757     return Call;
6758 
6759   ASTContext &Context = getASTContext();
6760   std::function<void(StringRef)> DiagUnknownTrait = [this,
6761                                                      CE](StringRef ISATrait) {
6762     // TODO Track the selector locations in a way that is accessible here to
6763     // improve the diagnostic location.
6764     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6765         << ISATrait;
6766   };
6767   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6768                           getCurFunctionDecl());
6769 
6770   QualType CalleeFnType = CalleeFnDecl->getType();
6771 
6772   SmallVector<Expr *, 4> Exprs;
6773   SmallVector<VariantMatchInfo, 4> VMIs;
6774   while (CalleeFnDecl) {
6775     for (OMPDeclareVariantAttr *A :
6776          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6777       Expr *VariantRef = A->getVariantFuncRef();
6778 
6779       VariantMatchInfo VMI;
6780       OMPTraitInfo &TI = A->getTraitInfo();
6781       TI.getAsVariantMatchInfo(Context, VMI);
6782       if (!isVariantApplicableInContext(VMI, OMPCtx,
6783                                         /* DeviceSetOnly */ false))
6784         continue;
6785 
6786       VMIs.push_back(VMI);
6787       Exprs.push_back(VariantRef);
6788     }
6789 
6790     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6791   }
6792 
6793   ExprResult NewCall;
6794   do {
6795     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6796     if (BestIdx < 0)
6797       return Call;
6798     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6799     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6800 
6801     {
6802       // Try to build a (member) call expression for the current best applicable
6803       // variant expression. We allow this to fail in which case we continue
6804       // with the next best variant expression. The fail case is part of the
6805       // implementation defined behavior in the OpenMP standard when it talks
6806       // about what differences in the function prototypes: "Any differences
6807       // that the specific OpenMP context requires in the prototype of the
6808       // variant from the base function prototype are implementation defined."
6809       // This wording is there to allow the specialized variant to have a
6810       // different type than the base function. This is intended and OK but if
6811       // we cannot create a call the difference is not in the "implementation
6812       // defined range" we allow.
6813       Sema::TentativeAnalysisScope Trap(*this);
6814 
6815       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6816         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6817         BestExpr = MemberExpr::CreateImplicit(
6818             Context, MemberCall->getImplicitObjectArgument(),
6819             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6820             MemberCall->getValueKind(), MemberCall->getObjectKind());
6821       }
6822       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6823                               ExecConfig);
6824       if (NewCall.isUsable()) {
6825         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6826           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6827           QualType NewType = Context.mergeFunctionTypes(
6828               CalleeFnType, NewCalleeFnDecl->getType(),
6829               /* OfBlockPointer */ false,
6830               /* Unqualified */ false, /* AllowCXX */ true);
6831           if (!NewType.isNull())
6832             break;
6833           // Don't use the call if the function type was not compatible.
6834           NewCall = nullptr;
6835         }
6836       }
6837     }
6838 
6839     VMIs.erase(VMIs.begin() + BestIdx);
6840     Exprs.erase(Exprs.begin() + BestIdx);
6841   } while (!VMIs.empty());
6842 
6843   if (!NewCall.isUsable())
6844     return Call;
6845   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6846 }
6847 
6848 Optional<std::pair<FunctionDecl *, Expr *>>
6849 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6850                                         Expr *VariantRef, OMPTraitInfo &TI,
6851                                         SourceRange SR) {
6852   if (!DG || DG.get().isNull())
6853     return None;
6854 
6855   const int VariantId = 1;
6856   // Must be applied only to single decl.
6857   if (!DG.get().isSingleDecl()) {
6858     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6859         << VariantId << SR;
6860     return None;
6861   }
6862   Decl *ADecl = DG.get().getSingleDecl();
6863   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6864     ADecl = FTD->getTemplatedDecl();
6865 
6866   // Decl must be a function.
6867   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6868   if (!FD) {
6869     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6870         << VariantId << SR;
6871     return None;
6872   }
6873 
6874   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6875     return FD->hasAttrs() &&
6876            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6877             FD->hasAttr<TargetAttr>());
6878   };
6879   // OpenMP is not compatible with CPU-specific attributes.
6880   if (HasMultiVersionAttributes(FD)) {
6881     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6882         << SR;
6883     return None;
6884   }
6885 
6886   // Allow #pragma omp declare variant only if the function is not used.
6887   if (FD->isUsed(false))
6888     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
6889         << FD->getLocation();
6890 
6891   // Check if the function was emitted already.
6892   const FunctionDecl *Definition;
6893   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
6894       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
6895     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
6896         << FD->getLocation();
6897 
6898   // The VariantRef must point to function.
6899   if (!VariantRef) {
6900     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
6901     return None;
6902   }
6903 
6904   auto ShouldDelayChecks = [](Expr *&E, bool) {
6905     return E && (E->isTypeDependent() || E->isValueDependent() ||
6906                  E->containsUnexpandedParameterPack() ||
6907                  E->isInstantiationDependent());
6908   };
6909   // Do not check templates, wait until instantiation.
6910   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
6911       TI.anyScoreOrCondition(ShouldDelayChecks))
6912     return std::make_pair(FD, VariantRef);
6913 
6914   // Deal with non-constant score and user condition expressions.
6915   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
6916                                                      bool IsScore) -> bool {
6917     if (!E || E->isIntegerConstantExpr(Context))
6918       return false;
6919 
6920     if (IsScore) {
6921       // We warn on non-constant scores and pretend they were not present.
6922       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
6923           << E;
6924       E = nullptr;
6925     } else {
6926       // We could replace a non-constant user condition with "false" but we
6927       // will soon need to handle these anyway for the dynamic version of
6928       // OpenMP context selectors.
6929       Diag(E->getExprLoc(),
6930            diag::err_omp_declare_variant_user_condition_not_constant)
6931           << E;
6932     }
6933     return true;
6934   };
6935   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6936     return None;
6937 
6938   // Convert VariantRef expression to the type of the original function to
6939   // resolve possible conflicts.
6940   ExprResult VariantRefCast = VariantRef;
6941   if (LangOpts.CPlusPlus) {
6942     QualType FnPtrType;
6943     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6944     if (Method && !Method->isStatic()) {
6945       const Type *ClassType =
6946           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6947       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6948       ExprResult ER;
6949       {
6950         // Build adrr_of unary op to correctly handle type checks for member
6951         // functions.
6952         Sema::TentativeAnalysisScope Trap(*this);
6953         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6954                                   VariantRef);
6955       }
6956       if (!ER.isUsable()) {
6957         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6958             << VariantId << VariantRef->getSourceRange();
6959         return None;
6960       }
6961       VariantRef = ER.get();
6962     } else {
6963       FnPtrType = Context.getPointerType(FD->getType());
6964     }
6965     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
6966     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
6967       ImplicitConversionSequence ICS = TryImplicitConversion(
6968           VariantRef, FnPtrType.getUnqualifiedType(),
6969           /*SuppressUserConversions=*/false, AllowedExplicit::None,
6970           /*InOverloadResolution=*/false,
6971           /*CStyle=*/false,
6972           /*AllowObjCWritebackConversion=*/false);
6973       if (ICS.isFailure()) {
6974         Diag(VariantRef->getExprLoc(),
6975              diag::err_omp_declare_variant_incompat_types)
6976             << VariantRef->getType()
6977             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6978             << VariantRef->getSourceRange();
6979         return None;
6980       }
6981       VariantRefCast = PerformImplicitConversion(
6982           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6983       if (!VariantRefCast.isUsable())
6984         return None;
6985     }
6986     // Drop previously built artificial addr_of unary op for member functions.
6987     if (Method && !Method->isStatic()) {
6988       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6989       if (auto *UO = dyn_cast<UnaryOperator>(
6990               PossibleAddrOfVariantRef->IgnoreImplicit()))
6991         VariantRefCast = UO->getSubExpr();
6992     }
6993   }
6994 
6995   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6996   if (!ER.isUsable() ||
6997       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6998     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6999         << VariantId << VariantRef->getSourceRange();
7000     return None;
7001   }
7002 
7003   // The VariantRef must point to function.
7004   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7005   if (!DRE) {
7006     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7007         << VariantId << VariantRef->getSourceRange();
7008     return None;
7009   }
7010   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7011   if (!NewFD) {
7012     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7013         << VariantId << VariantRef->getSourceRange();
7014     return None;
7015   }
7016 
7017   // Check if function types are compatible in C.
7018   if (!LangOpts.CPlusPlus) {
7019     QualType NewType =
7020         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
7021     if (NewType.isNull()) {
7022       Diag(VariantRef->getExprLoc(),
7023            diag::err_omp_declare_variant_incompat_types)
7024           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
7025       return None;
7026     }
7027     if (NewType->isFunctionProtoType()) {
7028       if (FD->getType()->isFunctionNoProtoType())
7029         setPrototype(*this, FD, NewFD, NewType);
7030       else if (NewFD->getType()->isFunctionNoProtoType())
7031         setPrototype(*this, NewFD, FD, NewType);
7032     }
7033   }
7034 
7035   // Check if variant function is not marked with declare variant directive.
7036   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7037     Diag(VariantRef->getExprLoc(),
7038          diag::warn_omp_declare_variant_marked_as_declare_variant)
7039         << VariantRef->getSourceRange();
7040     SourceRange SR =
7041         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7042     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7043     return None;
7044   }
7045 
7046   enum DoesntSupport {
7047     VirtFuncs = 1,
7048     Constructors = 3,
7049     Destructors = 4,
7050     DeletedFuncs = 5,
7051     DefaultedFuncs = 6,
7052     ConstexprFuncs = 7,
7053     ConstevalFuncs = 8,
7054   };
7055   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7056     if (CXXFD->isVirtual()) {
7057       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7058           << VirtFuncs;
7059       return None;
7060     }
7061 
7062     if (isa<CXXConstructorDecl>(FD)) {
7063       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7064           << Constructors;
7065       return None;
7066     }
7067 
7068     if (isa<CXXDestructorDecl>(FD)) {
7069       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7070           << Destructors;
7071       return None;
7072     }
7073   }
7074 
7075   if (FD->isDeleted()) {
7076     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7077         << DeletedFuncs;
7078     return None;
7079   }
7080 
7081   if (FD->isDefaulted()) {
7082     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7083         << DefaultedFuncs;
7084     return None;
7085   }
7086 
7087   if (FD->isConstexpr()) {
7088     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7089         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7090     return None;
7091   }
7092 
7093   // Check general compatibility.
7094   if (areMultiversionVariantFunctionsCompatible(
7095           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7096           PartialDiagnosticAt(SourceLocation(),
7097                               PartialDiagnostic::NullDiagnostic()),
7098           PartialDiagnosticAt(
7099               VariantRef->getExprLoc(),
7100               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7101           PartialDiagnosticAt(VariantRef->getExprLoc(),
7102                               PDiag(diag::err_omp_declare_variant_diff)
7103                                   << FD->getLocation()),
7104           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7105           /*CLinkageMayDiffer=*/true))
7106     return None;
7107   return std::make_pair(FD, cast<Expr>(DRE));
7108 }
7109 
7110 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
7111                                               Expr *VariantRef,
7112                                               OMPTraitInfo &TI,
7113                                               SourceRange SR) {
7114   auto *NewAttr =
7115       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
7116   FD->addAttr(NewAttr);
7117 }
7118 
7119 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7120                                               Stmt *AStmt,
7121                                               SourceLocation StartLoc,
7122                                               SourceLocation EndLoc) {
7123   if (!AStmt)
7124     return StmtError();
7125 
7126   auto *CS = cast<CapturedStmt>(AStmt);
7127   // 1.2.2 OpenMP Language Terminology
7128   // Structured block - An executable statement with a single entry at the
7129   // top and a single exit at the bottom.
7130   // The point of exit cannot be a branch out of the structured block.
7131   // longjmp() and throw() must not violate the entry/exit criteria.
7132   CS->getCapturedDecl()->setNothrow();
7133 
7134   setFunctionHasBranchProtectedScope();
7135 
7136   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7137                                       DSAStack->getTaskgroupReductionRef(),
7138                                       DSAStack->isCancelRegion());
7139 }
7140 
7141 namespace {
7142 /// Iteration space of a single for loop.
7143 struct LoopIterationSpace final {
7144   /// True if the condition operator is the strict compare operator (<, > or
7145   /// !=).
7146   bool IsStrictCompare = false;
7147   /// Condition of the loop.
7148   Expr *PreCond = nullptr;
7149   /// This expression calculates the number of iterations in the loop.
7150   /// It is always possible to calculate it before starting the loop.
7151   Expr *NumIterations = nullptr;
7152   /// The loop counter variable.
7153   Expr *CounterVar = nullptr;
7154   /// Private loop counter variable.
7155   Expr *PrivateCounterVar = nullptr;
7156   /// This is initializer for the initial value of #CounterVar.
7157   Expr *CounterInit = nullptr;
7158   /// This is step for the #CounterVar used to generate its update:
7159   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7160   Expr *CounterStep = nullptr;
7161   /// Should step be subtracted?
7162   bool Subtract = false;
7163   /// Source range of the loop init.
7164   SourceRange InitSrcRange;
7165   /// Source range of the loop condition.
7166   SourceRange CondSrcRange;
7167   /// Source range of the loop increment.
7168   SourceRange IncSrcRange;
7169   /// Minimum value that can have the loop control variable. Used to support
7170   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7171   /// since only such variables can be used in non-loop invariant expressions.
7172   Expr *MinValue = nullptr;
7173   /// Maximum value that can have the loop control variable. Used to support
7174   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7175   /// since only such variables can be used in non-loop invariant expressions.
7176   Expr *MaxValue = nullptr;
7177   /// true, if the lower bound depends on the outer loop control var.
7178   bool IsNonRectangularLB = false;
7179   /// true, if the upper bound depends on the outer loop control var.
7180   bool IsNonRectangularUB = false;
7181   /// Index of the loop this loop depends on and forms non-rectangular loop
7182   /// nest.
7183   unsigned LoopDependentIdx = 0;
7184   /// Final condition for the non-rectangular loop nest support. It is used to
7185   /// check that the number of iterations for this particular counter must be
7186   /// finished.
7187   Expr *FinalCondition = nullptr;
7188 };
7189 
7190 /// Helper class for checking canonical form of the OpenMP loops and
7191 /// extracting iteration space of each loop in the loop nest, that will be used
7192 /// for IR generation.
7193 class OpenMPIterationSpaceChecker {
7194   /// Reference to Sema.
7195   Sema &SemaRef;
7196   /// Does the loop associated directive support non-rectangular loops?
7197   bool SupportsNonRectangular;
7198   /// Data-sharing stack.
7199   DSAStackTy &Stack;
7200   /// A location for diagnostics (when there is no some better location).
7201   SourceLocation DefaultLoc;
7202   /// A location for diagnostics (when increment is not compatible).
7203   SourceLocation ConditionLoc;
7204   /// A source location for referring to loop init later.
7205   SourceRange InitSrcRange;
7206   /// A source location for referring to condition later.
7207   SourceRange ConditionSrcRange;
7208   /// A source location for referring to increment later.
7209   SourceRange IncrementSrcRange;
7210   /// Loop variable.
7211   ValueDecl *LCDecl = nullptr;
7212   /// Reference to loop variable.
7213   Expr *LCRef = nullptr;
7214   /// Lower bound (initializer for the var).
7215   Expr *LB = nullptr;
7216   /// Upper bound.
7217   Expr *UB = nullptr;
7218   /// Loop step (increment).
7219   Expr *Step = nullptr;
7220   /// This flag is true when condition is one of:
7221   ///   Var <  UB
7222   ///   Var <= UB
7223   ///   UB  >  Var
7224   ///   UB  >= Var
7225   /// This will have no value when the condition is !=
7226   llvm::Optional<bool> TestIsLessOp;
7227   /// This flag is true when condition is strict ( < or > ).
7228   bool TestIsStrictOp = false;
7229   /// This flag is true when step is subtracted on each iteration.
7230   bool SubtractStep = false;
7231   /// The outer loop counter this loop depends on (if any).
7232   const ValueDecl *DepDecl = nullptr;
7233   /// Contains number of loop (starts from 1) on which loop counter init
7234   /// expression of this loop depends on.
7235   Optional<unsigned> InitDependOnLC;
7236   /// Contains number of loop (starts from 1) on which loop counter condition
7237   /// expression of this loop depends on.
7238   Optional<unsigned> CondDependOnLC;
7239   /// Checks if the provide statement depends on the loop counter.
7240   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7241   /// Original condition required for checking of the exit condition for
7242   /// non-rectangular loop.
7243   Expr *Condition = nullptr;
7244 
7245 public:
7246   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7247                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7248       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7249         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7250   /// Check init-expr for canonical loop form and save loop counter
7251   /// variable - #Var and its initialization value - #LB.
7252   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7253   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7254   /// for less/greater and for strict/non-strict comparison.
7255   bool checkAndSetCond(Expr *S);
7256   /// Check incr-expr for canonical loop form and return true if it
7257   /// does not conform, otherwise save loop step (#Step).
7258   bool checkAndSetInc(Expr *S);
7259   /// Return the loop counter variable.
7260   ValueDecl *getLoopDecl() const { return LCDecl; }
7261   /// Return the reference expression to loop counter variable.
7262   Expr *getLoopDeclRefExpr() const { return LCRef; }
7263   /// Source range of the loop init.
7264   SourceRange getInitSrcRange() const { return InitSrcRange; }
7265   /// Source range of the loop condition.
7266   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7267   /// Source range of the loop increment.
7268   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7269   /// True if the step should be subtracted.
7270   bool shouldSubtractStep() const { return SubtractStep; }
7271   /// True, if the compare operator is strict (<, > or !=).
7272   bool isStrictTestOp() const { return TestIsStrictOp; }
7273   /// Build the expression to calculate the number of iterations.
7274   Expr *buildNumIterations(
7275       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7276       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7277   /// Build the precondition expression for the loops.
7278   Expr *
7279   buildPreCond(Scope *S, Expr *Cond,
7280                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7281   /// Build reference expression to the counter be used for codegen.
7282   DeclRefExpr *
7283   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7284                   DSAStackTy &DSA) const;
7285   /// Build reference expression to the private counter be used for
7286   /// codegen.
7287   Expr *buildPrivateCounterVar() const;
7288   /// Build initialization of the counter be used for codegen.
7289   Expr *buildCounterInit() const;
7290   /// Build step of the counter be used for codegen.
7291   Expr *buildCounterStep() const;
7292   /// Build loop data with counter value for depend clauses in ordered
7293   /// directives.
7294   Expr *
7295   buildOrderedLoopData(Scope *S, Expr *Counter,
7296                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7297                        SourceLocation Loc, Expr *Inc = nullptr,
7298                        OverloadedOperatorKind OOK = OO_Amp);
7299   /// Builds the minimum value for the loop counter.
7300   std::pair<Expr *, Expr *> buildMinMaxValues(
7301       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7302   /// Builds final condition for the non-rectangular loops.
7303   Expr *buildFinalCondition(Scope *S) const;
7304   /// Return true if any expression is dependent.
7305   bool dependent() const;
7306   /// Returns true if the initializer forms non-rectangular loop.
7307   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7308   /// Returns true if the condition forms non-rectangular loop.
7309   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7310   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7311   unsigned getLoopDependentIdx() const {
7312     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7313   }
7314 
7315 private:
7316   /// Check the right-hand side of an assignment in the increment
7317   /// expression.
7318   bool checkAndSetIncRHS(Expr *RHS);
7319   /// Helper to set loop counter variable and its initializer.
7320   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7321                       bool EmitDiags);
7322   /// Helper to set upper bound.
7323   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7324              SourceRange SR, SourceLocation SL);
7325   /// Helper to set loop increment.
7326   bool setStep(Expr *NewStep, bool Subtract);
7327 };
7328 
7329 bool OpenMPIterationSpaceChecker::dependent() const {
7330   if (!LCDecl) {
7331     assert(!LB && !UB && !Step);
7332     return false;
7333   }
7334   return LCDecl->getType()->isDependentType() ||
7335          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7336          (Step && Step->isValueDependent());
7337 }
7338 
7339 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7340                                                  Expr *NewLCRefExpr,
7341                                                  Expr *NewLB, bool EmitDiags) {
7342   // State consistency checking to ensure correct usage.
7343   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7344          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7345   if (!NewLCDecl || !NewLB)
7346     return true;
7347   LCDecl = getCanonicalDecl(NewLCDecl);
7348   LCRef = NewLCRefExpr;
7349   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7350     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7351       if ((Ctor->isCopyOrMoveConstructor() ||
7352            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7353           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7354         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7355   LB = NewLB;
7356   if (EmitDiags)
7357     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7358   return false;
7359 }
7360 
7361 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7362                                         llvm::Optional<bool> LessOp,
7363                                         bool StrictOp, SourceRange SR,
7364                                         SourceLocation SL) {
7365   // State consistency checking to ensure correct usage.
7366   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7367          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7368   if (!NewUB)
7369     return true;
7370   UB = NewUB;
7371   if (LessOp)
7372     TestIsLessOp = LessOp;
7373   TestIsStrictOp = StrictOp;
7374   ConditionSrcRange = SR;
7375   ConditionLoc = SL;
7376   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7377   return false;
7378 }
7379 
7380 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7381   // State consistency checking to ensure correct usage.
7382   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7383   if (!NewStep)
7384     return true;
7385   if (!NewStep->isValueDependent()) {
7386     // Check that the step is integer expression.
7387     SourceLocation StepLoc = NewStep->getBeginLoc();
7388     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7389         StepLoc, getExprAsWritten(NewStep));
7390     if (Val.isInvalid())
7391       return true;
7392     NewStep = Val.get();
7393 
7394     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7395     //  If test-expr is of form var relational-op b and relational-op is < or
7396     //  <= then incr-expr must cause var to increase on each iteration of the
7397     //  loop. If test-expr is of form var relational-op b and relational-op is
7398     //  > or >= then incr-expr must cause var to decrease on each iteration of
7399     //  the loop.
7400     //  If test-expr is of form b relational-op var and relational-op is < or
7401     //  <= then incr-expr must cause var to decrease on each iteration of the
7402     //  loop. If test-expr is of form b relational-op var and relational-op is
7403     //  > or >= then incr-expr must cause var to increase on each iteration of
7404     //  the loop.
7405     Optional<llvm::APSInt> Result =
7406         NewStep->getIntegerConstantExpr(SemaRef.Context);
7407     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7408     bool IsConstNeg =
7409         Result && Result->isSigned() && (Subtract != Result->isNegative());
7410     bool IsConstPos =
7411         Result && Result->isSigned() && (Subtract == Result->isNegative());
7412     bool IsConstZero = Result && !Result->getBoolValue();
7413 
7414     // != with increment is treated as <; != with decrement is treated as >
7415     if (!TestIsLessOp.hasValue())
7416       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7417     if (UB && (IsConstZero ||
7418                (TestIsLessOp.getValue() ?
7419                   (IsConstNeg || (IsUnsigned && Subtract)) :
7420                   (IsConstPos || (IsUnsigned && !Subtract))))) {
7421       SemaRef.Diag(NewStep->getExprLoc(),
7422                    diag::err_omp_loop_incr_not_compatible)
7423           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7424       SemaRef.Diag(ConditionLoc,
7425                    diag::note_omp_loop_cond_requres_compatible_incr)
7426           << TestIsLessOp.getValue() << ConditionSrcRange;
7427       return true;
7428     }
7429     if (TestIsLessOp.getValue() == Subtract) {
7430       NewStep =
7431           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7432               .get();
7433       Subtract = !Subtract;
7434     }
7435   }
7436 
7437   Step = NewStep;
7438   SubtractStep = Subtract;
7439   return false;
7440 }
7441 
7442 namespace {
7443 /// Checker for the non-rectangular loops. Checks if the initializer or
7444 /// condition expression references loop counter variable.
7445 class LoopCounterRefChecker final
7446     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7447   Sema &SemaRef;
7448   DSAStackTy &Stack;
7449   const ValueDecl *CurLCDecl = nullptr;
7450   const ValueDecl *DepDecl = nullptr;
7451   const ValueDecl *PrevDepDecl = nullptr;
7452   bool IsInitializer = true;
7453   bool SupportsNonRectangular;
7454   unsigned BaseLoopId = 0;
7455   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7456     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7457       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7458           << (IsInitializer ? 0 : 1);
7459       return false;
7460     }
7461     const auto &&Data = Stack.isLoopControlVariable(VD);
7462     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7463     // The type of the loop iterator on which we depend may not have a random
7464     // access iterator type.
7465     if (Data.first && VD->getType()->isRecordType()) {
7466       SmallString<128> Name;
7467       llvm::raw_svector_ostream OS(Name);
7468       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7469                                /*Qualified=*/true);
7470       SemaRef.Diag(E->getExprLoc(),
7471                    diag::err_omp_wrong_dependency_iterator_type)
7472           << OS.str();
7473       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7474       return false;
7475     }
7476     if (Data.first && !SupportsNonRectangular) {
7477       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7478       return false;
7479     }
7480     if (Data.first &&
7481         (DepDecl || (PrevDepDecl &&
7482                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7483       if (!DepDecl && PrevDepDecl)
7484         DepDecl = PrevDepDecl;
7485       SmallString<128> Name;
7486       llvm::raw_svector_ostream OS(Name);
7487       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7488                                     /*Qualified=*/true);
7489       SemaRef.Diag(E->getExprLoc(),
7490                    diag::err_omp_invariant_or_linear_dependency)
7491           << OS.str();
7492       return false;
7493     }
7494     if (Data.first) {
7495       DepDecl = VD;
7496       BaseLoopId = Data.first;
7497     }
7498     return Data.first;
7499   }
7500 
7501 public:
7502   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7503     const ValueDecl *VD = E->getDecl();
7504     if (isa<VarDecl>(VD))
7505       return checkDecl(E, VD);
7506     return false;
7507   }
7508   bool VisitMemberExpr(const MemberExpr *E) {
7509     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7510       const ValueDecl *VD = E->getMemberDecl();
7511       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7512         return checkDecl(E, VD);
7513     }
7514     return false;
7515   }
7516   bool VisitStmt(const Stmt *S) {
7517     bool Res = false;
7518     for (const Stmt *Child : S->children())
7519       Res = (Child && Visit(Child)) || Res;
7520     return Res;
7521   }
7522   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7523                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7524                                  const ValueDecl *PrevDepDecl = nullptr,
7525                                  bool SupportsNonRectangular = true)
7526       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7527         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7528         SupportsNonRectangular(SupportsNonRectangular) {}
7529   unsigned getBaseLoopId() const {
7530     assert(CurLCDecl && "Expected loop dependency.");
7531     return BaseLoopId;
7532   }
7533   const ValueDecl *getDepDecl() const {
7534     assert(CurLCDecl && "Expected loop dependency.");
7535     return DepDecl;
7536   }
7537 };
7538 } // namespace
7539 
7540 Optional<unsigned>
7541 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7542                                                      bool IsInitializer) {
7543   // Check for the non-rectangular loops.
7544   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7545                                         DepDecl, SupportsNonRectangular);
7546   if (LoopStmtChecker.Visit(S)) {
7547     DepDecl = LoopStmtChecker.getDepDecl();
7548     return LoopStmtChecker.getBaseLoopId();
7549   }
7550   return llvm::None;
7551 }
7552 
7553 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7554   // Check init-expr for canonical loop form and save loop counter
7555   // variable - #Var and its initialization value - #LB.
7556   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7557   //   var = lb
7558   //   integer-type var = lb
7559   //   random-access-iterator-type var = lb
7560   //   pointer-type var = lb
7561   //
7562   if (!S) {
7563     if (EmitDiags) {
7564       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7565     }
7566     return true;
7567   }
7568   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7569     if (!ExprTemp->cleanupsHaveSideEffects())
7570       S = ExprTemp->getSubExpr();
7571 
7572   InitSrcRange = S->getSourceRange();
7573   if (Expr *E = dyn_cast<Expr>(S))
7574     S = E->IgnoreParens();
7575   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7576     if (BO->getOpcode() == BO_Assign) {
7577       Expr *LHS = BO->getLHS()->IgnoreParens();
7578       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7579         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7580           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7581             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7582                                   EmitDiags);
7583         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7584       }
7585       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7586         if (ME->isArrow() &&
7587             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7588           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7589                                 EmitDiags);
7590       }
7591     }
7592   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7593     if (DS->isSingleDecl()) {
7594       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7595         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7596           // Accept non-canonical init form here but emit ext. warning.
7597           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7598             SemaRef.Diag(S->getBeginLoc(),
7599                          diag::ext_omp_loop_not_canonical_init)
7600                 << S->getSourceRange();
7601           return setLCDeclAndLB(
7602               Var,
7603               buildDeclRefExpr(SemaRef, Var,
7604                                Var->getType().getNonReferenceType(),
7605                                DS->getBeginLoc()),
7606               Var->getInit(), EmitDiags);
7607         }
7608       }
7609     }
7610   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7611     if (CE->getOperator() == OO_Equal) {
7612       Expr *LHS = CE->getArg(0);
7613       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7614         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7615           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7616             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7617                                   EmitDiags);
7618         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7619       }
7620       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7621         if (ME->isArrow() &&
7622             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7623           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7624                                 EmitDiags);
7625       }
7626     }
7627   }
7628 
7629   if (dependent() || SemaRef.CurContext->isDependentContext())
7630     return false;
7631   if (EmitDiags) {
7632     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7633         << S->getSourceRange();
7634   }
7635   return true;
7636 }
7637 
7638 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7639 /// variable (which may be the loop variable) if possible.
7640 static const ValueDecl *getInitLCDecl(const Expr *E) {
7641   if (!E)
7642     return nullptr;
7643   E = getExprAsWritten(E);
7644   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7645     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7646       if ((Ctor->isCopyOrMoveConstructor() ||
7647            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7648           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7649         E = CE->getArg(0)->IgnoreParenImpCasts();
7650   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7651     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7652       return getCanonicalDecl(VD);
7653   }
7654   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7655     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7656       return getCanonicalDecl(ME->getMemberDecl());
7657   return nullptr;
7658 }
7659 
7660 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7661   // Check test-expr for canonical form, save upper-bound UB, flags for
7662   // less/greater and for strict/non-strict comparison.
7663   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7664   //   var relational-op b
7665   //   b relational-op var
7666   //
7667   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7668   if (!S) {
7669     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7670         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7671     return true;
7672   }
7673   Condition = S;
7674   S = getExprAsWritten(S);
7675   SourceLocation CondLoc = S->getBeginLoc();
7676   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7677                                BinaryOperatorKind Opcode, const Expr *LHS,
7678                                const Expr *RHS, SourceRange SR,
7679                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7680     if (BinaryOperator::isRelationalOp(Opcode)) {
7681       if (getInitLCDecl(LHS) == LCDecl)
7682         return setUB(const_cast<Expr *>(RHS),
7683                      (Opcode == BO_LT || Opcode == BO_LE),
7684                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7685       if (getInitLCDecl(RHS) == LCDecl)
7686         return setUB(const_cast<Expr *>(LHS),
7687                      (Opcode == BO_GT || Opcode == BO_GE),
7688                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7689     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7690       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7691                    /*LessOp=*/llvm::None,
7692                    /*StrictOp=*/true, SR, OpLoc);
7693     }
7694     return llvm::None;
7695   };
7696   llvm::Optional<bool> Res;
7697   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7698     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7699     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7700                           RBO->getOperatorLoc());
7701   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7702     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7703                           BO->getSourceRange(), BO->getOperatorLoc());
7704   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7705     if (CE->getNumArgs() == 2) {
7706       Res = CheckAndSetCond(
7707           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7708           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7709     }
7710   }
7711   if (Res.hasValue())
7712     return *Res;
7713   if (dependent() || SemaRef.CurContext->isDependentContext())
7714     return false;
7715   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7716       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7717   return true;
7718 }
7719 
7720 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7721   // RHS of canonical loop form increment can be:
7722   //   var + incr
7723   //   incr + var
7724   //   var - incr
7725   //
7726   RHS = RHS->IgnoreParenImpCasts();
7727   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7728     if (BO->isAdditiveOp()) {
7729       bool IsAdd = BO->getOpcode() == BO_Add;
7730       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7731         return setStep(BO->getRHS(), !IsAdd);
7732       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7733         return setStep(BO->getLHS(), /*Subtract=*/false);
7734     }
7735   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7736     bool IsAdd = CE->getOperator() == OO_Plus;
7737     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7738       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7739         return setStep(CE->getArg(1), !IsAdd);
7740       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7741         return setStep(CE->getArg(0), /*Subtract=*/false);
7742     }
7743   }
7744   if (dependent() || SemaRef.CurContext->isDependentContext())
7745     return false;
7746   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7747       << RHS->getSourceRange() << LCDecl;
7748   return true;
7749 }
7750 
7751 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7752   // Check incr-expr for canonical loop form and return true if it
7753   // does not conform.
7754   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7755   //   ++var
7756   //   var++
7757   //   --var
7758   //   var--
7759   //   var += incr
7760   //   var -= incr
7761   //   var = var + incr
7762   //   var = incr + var
7763   //   var = var - incr
7764   //
7765   if (!S) {
7766     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7767     return true;
7768   }
7769   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7770     if (!ExprTemp->cleanupsHaveSideEffects())
7771       S = ExprTemp->getSubExpr();
7772 
7773   IncrementSrcRange = S->getSourceRange();
7774   S = S->IgnoreParens();
7775   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7776     if (UO->isIncrementDecrementOp() &&
7777         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7778       return setStep(SemaRef
7779                          .ActOnIntegerConstant(UO->getBeginLoc(),
7780                                                (UO->isDecrementOp() ? -1 : 1))
7781                          .get(),
7782                      /*Subtract=*/false);
7783   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7784     switch (BO->getOpcode()) {
7785     case BO_AddAssign:
7786     case BO_SubAssign:
7787       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7788         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7789       break;
7790     case BO_Assign:
7791       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7792         return checkAndSetIncRHS(BO->getRHS());
7793       break;
7794     default:
7795       break;
7796     }
7797   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7798     switch (CE->getOperator()) {
7799     case OO_PlusPlus:
7800     case OO_MinusMinus:
7801       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7802         return setStep(SemaRef
7803                            .ActOnIntegerConstant(
7804                                CE->getBeginLoc(),
7805                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
7806                            .get(),
7807                        /*Subtract=*/false);
7808       break;
7809     case OO_PlusEqual:
7810     case OO_MinusEqual:
7811       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7812         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
7813       break;
7814     case OO_Equal:
7815       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7816         return checkAndSetIncRHS(CE->getArg(1));
7817       break;
7818     default:
7819       break;
7820     }
7821   }
7822   if (dependent() || SemaRef.CurContext->isDependentContext())
7823     return false;
7824   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7825       << S->getSourceRange() << LCDecl;
7826   return true;
7827 }
7828 
7829 static ExprResult
7830 tryBuildCapture(Sema &SemaRef, Expr *Capture,
7831                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7832   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
7833     return Capture;
7834   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
7835     return SemaRef.PerformImplicitConversion(
7836         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
7837         /*AllowExplicit=*/true);
7838   auto I = Captures.find(Capture);
7839   if (I != Captures.end())
7840     return buildCapture(SemaRef, Capture, I->second);
7841   DeclRefExpr *Ref = nullptr;
7842   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
7843   Captures[Capture] = Ref;
7844   return Res;
7845 }
7846 
7847 /// Calculate number of iterations, transforming to unsigned, if number of
7848 /// iterations may be larger than the original type.
7849 static Expr *
7850 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
7851                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
7852                   bool TestIsStrictOp, bool RoundToStep,
7853                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7854   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7855   if (!NewStep.isUsable())
7856     return nullptr;
7857   llvm::APSInt LRes, SRes;
7858   bool IsLowerConst = false, IsStepConst = false;
7859   if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) {
7860     LRes = *Res;
7861     IsLowerConst = true;
7862   }
7863   if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) {
7864     SRes = *Res;
7865     IsStepConst = true;
7866   }
7867   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
7868                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
7869                           (TestIsStrictOp && LRes.isStrictlyPositive()));
7870   bool NeedToReorganize = false;
7871   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
7872   if (!NoNeedToConvert && IsLowerConst &&
7873       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
7874     NoNeedToConvert = true;
7875     if (RoundToStep) {
7876       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
7877                         ? LRes.getBitWidth()
7878                         : SRes.getBitWidth();
7879       LRes = LRes.extend(BW + 1);
7880       LRes.setIsSigned(true);
7881       SRes = SRes.extend(BW + 1);
7882       SRes.setIsSigned(true);
7883       LRes -= SRes;
7884       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
7885       LRes = LRes.trunc(BW);
7886     }
7887     if (TestIsStrictOp) {
7888       unsigned BW = LRes.getBitWidth();
7889       LRes = LRes.extend(BW + 1);
7890       LRes.setIsSigned(true);
7891       ++LRes;
7892       NoNeedToConvert =
7893           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
7894       // truncate to the original bitwidth.
7895       LRes = LRes.trunc(BW);
7896     }
7897     NeedToReorganize = NoNeedToConvert;
7898   }
7899   llvm::APSInt URes;
7900   bool IsUpperConst = false;
7901   if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) {
7902     URes = *Res;
7903     IsUpperConst = true;
7904   }
7905   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
7906       (!RoundToStep || IsStepConst)) {
7907     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
7908                                                           : URes.getBitWidth();
7909     LRes = LRes.extend(BW + 1);
7910     LRes.setIsSigned(true);
7911     URes = URes.extend(BW + 1);
7912     URes.setIsSigned(true);
7913     URes -= LRes;
7914     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
7915     NeedToReorganize = NoNeedToConvert;
7916   }
7917   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
7918   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
7919   // unsigned.
7920   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
7921       !LCTy->isDependentType() && LCTy->isIntegerType()) {
7922     QualType LowerTy = Lower->getType();
7923     QualType UpperTy = Upper->getType();
7924     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
7925     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
7926     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
7927         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
7928       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
7929           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
7930       Upper =
7931           SemaRef
7932               .PerformImplicitConversion(
7933                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7934                   CastType, Sema::AA_Converting)
7935               .get();
7936       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7937       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7938     }
7939   }
7940   if (!Lower || !Upper || NewStep.isInvalid())
7941     return nullptr;
7942 
7943   ExprResult Diff;
7944   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7945   // 1]).
7946   if (NeedToReorganize) {
7947     Diff = Lower;
7948 
7949     if (RoundToStep) {
7950       // Lower - Step
7951       Diff =
7952           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7953       if (!Diff.isUsable())
7954         return nullptr;
7955     }
7956 
7957     // Lower - Step [+ 1]
7958     if (TestIsStrictOp)
7959       Diff = SemaRef.BuildBinOp(
7960           S, DefaultLoc, BO_Add, Diff.get(),
7961           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7962     if (!Diff.isUsable())
7963       return nullptr;
7964 
7965     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7966     if (!Diff.isUsable())
7967       return nullptr;
7968 
7969     // Upper - (Lower - Step [+ 1]).
7970     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7971     if (!Diff.isUsable())
7972       return nullptr;
7973   } else {
7974     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7975 
7976     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7977       // BuildBinOp already emitted error, this one is to point user to upper
7978       // and lower bound, and to tell what is passed to 'operator-'.
7979       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7980           << Upper->getSourceRange() << Lower->getSourceRange();
7981       return nullptr;
7982     }
7983 
7984     if (!Diff.isUsable())
7985       return nullptr;
7986 
7987     // Upper - Lower [- 1]
7988     if (TestIsStrictOp)
7989       Diff = SemaRef.BuildBinOp(
7990           S, DefaultLoc, BO_Sub, Diff.get(),
7991           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7992     if (!Diff.isUsable())
7993       return nullptr;
7994 
7995     if (RoundToStep) {
7996       // Upper - Lower [- 1] + Step
7997       Diff =
7998           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7999       if (!Diff.isUsable())
8000         return nullptr;
8001     }
8002   }
8003 
8004   // Parentheses (for dumping/debugging purposes only).
8005   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8006   if (!Diff.isUsable())
8007     return nullptr;
8008 
8009   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8010   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8011   if (!Diff.isUsable())
8012     return nullptr;
8013 
8014   return Diff.get();
8015 }
8016 
8017 /// Build the expression to calculate the number of iterations.
8018 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8019     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8020     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8021   QualType VarType = LCDecl->getType().getNonReferenceType();
8022   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8023       !SemaRef.getLangOpts().CPlusPlus)
8024     return nullptr;
8025   Expr *LBVal = LB;
8026   Expr *UBVal = UB;
8027   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8028   // max(LB(MinVal), LB(MaxVal))
8029   if (InitDependOnLC) {
8030     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8031     if (!IS.MinValue || !IS.MaxValue)
8032       return nullptr;
8033     // OuterVar = Min
8034     ExprResult MinValue =
8035         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8036     if (!MinValue.isUsable())
8037       return nullptr;
8038 
8039     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8040                                              IS.CounterVar, MinValue.get());
8041     if (!LBMinVal.isUsable())
8042       return nullptr;
8043     // OuterVar = Min, LBVal
8044     LBMinVal =
8045         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8046     if (!LBMinVal.isUsable())
8047       return nullptr;
8048     // (OuterVar = Min, LBVal)
8049     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8050     if (!LBMinVal.isUsable())
8051       return nullptr;
8052 
8053     // OuterVar = Max
8054     ExprResult MaxValue =
8055         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8056     if (!MaxValue.isUsable())
8057       return nullptr;
8058 
8059     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8060                                              IS.CounterVar, MaxValue.get());
8061     if (!LBMaxVal.isUsable())
8062       return nullptr;
8063     // OuterVar = Max, LBVal
8064     LBMaxVal =
8065         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8066     if (!LBMaxVal.isUsable())
8067       return nullptr;
8068     // (OuterVar = Max, LBVal)
8069     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8070     if (!LBMaxVal.isUsable())
8071       return nullptr;
8072 
8073     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8074     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8075     if (!LBMin || !LBMax)
8076       return nullptr;
8077     // LB(MinVal) < LB(MaxVal)
8078     ExprResult MinLessMaxRes =
8079         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8080     if (!MinLessMaxRes.isUsable())
8081       return nullptr;
8082     Expr *MinLessMax =
8083         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8084     if (!MinLessMax)
8085       return nullptr;
8086     if (TestIsLessOp.getValue()) {
8087       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8088       // LB(MaxVal))
8089       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8090                                                     MinLessMax, LBMin, LBMax);
8091       if (!MinLB.isUsable())
8092         return nullptr;
8093       LBVal = MinLB.get();
8094     } else {
8095       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8096       // LB(MaxVal))
8097       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8098                                                     MinLessMax, LBMax, LBMin);
8099       if (!MaxLB.isUsable())
8100         return nullptr;
8101       LBVal = MaxLB.get();
8102     }
8103   }
8104   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8105   // min(UB(MinVal), UB(MaxVal))
8106   if (CondDependOnLC) {
8107     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8108     if (!IS.MinValue || !IS.MaxValue)
8109       return nullptr;
8110     // OuterVar = Min
8111     ExprResult MinValue =
8112         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8113     if (!MinValue.isUsable())
8114       return nullptr;
8115 
8116     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8117                                              IS.CounterVar, MinValue.get());
8118     if (!UBMinVal.isUsable())
8119       return nullptr;
8120     // OuterVar = Min, UBVal
8121     UBMinVal =
8122         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8123     if (!UBMinVal.isUsable())
8124       return nullptr;
8125     // (OuterVar = Min, UBVal)
8126     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8127     if (!UBMinVal.isUsable())
8128       return nullptr;
8129 
8130     // OuterVar = Max
8131     ExprResult MaxValue =
8132         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8133     if (!MaxValue.isUsable())
8134       return nullptr;
8135 
8136     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8137                                              IS.CounterVar, MaxValue.get());
8138     if (!UBMaxVal.isUsable())
8139       return nullptr;
8140     // OuterVar = Max, UBVal
8141     UBMaxVal =
8142         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8143     if (!UBMaxVal.isUsable())
8144       return nullptr;
8145     // (OuterVar = Max, UBVal)
8146     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8147     if (!UBMaxVal.isUsable())
8148       return nullptr;
8149 
8150     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8151     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8152     if (!UBMin || !UBMax)
8153       return nullptr;
8154     // UB(MinVal) > UB(MaxVal)
8155     ExprResult MinGreaterMaxRes =
8156         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8157     if (!MinGreaterMaxRes.isUsable())
8158       return nullptr;
8159     Expr *MinGreaterMax =
8160         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8161     if (!MinGreaterMax)
8162       return nullptr;
8163     if (TestIsLessOp.getValue()) {
8164       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8165       // UB(MaxVal))
8166       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8167           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8168       if (!MaxUB.isUsable())
8169         return nullptr;
8170       UBVal = MaxUB.get();
8171     } else {
8172       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8173       // UB(MaxVal))
8174       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8175           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8176       if (!MinUB.isUsable())
8177         return nullptr;
8178       UBVal = MinUB.get();
8179     }
8180   }
8181   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8182   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8183   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8184   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8185   if (!Upper || !Lower)
8186     return nullptr;
8187 
8188   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8189                                       Step, VarType, TestIsStrictOp,
8190                                       /*RoundToStep=*/true, Captures);
8191   if (!Diff.isUsable())
8192     return nullptr;
8193 
8194   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8195   QualType Type = Diff.get()->getType();
8196   ASTContext &C = SemaRef.Context;
8197   bool UseVarType = VarType->hasIntegerRepresentation() &&
8198                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8199   if (!Type->isIntegerType() || UseVarType) {
8200     unsigned NewSize =
8201         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8202     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8203                                : Type->hasSignedIntegerRepresentation();
8204     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8205     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8206       Diff = SemaRef.PerformImplicitConversion(
8207           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8208       if (!Diff.isUsable())
8209         return nullptr;
8210     }
8211   }
8212   if (LimitedType) {
8213     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8214     if (NewSize != C.getTypeSize(Type)) {
8215       if (NewSize < C.getTypeSize(Type)) {
8216         assert(NewSize == 64 && "incorrect loop var size");
8217         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8218             << InitSrcRange << ConditionSrcRange;
8219       }
8220       QualType NewType = C.getIntTypeForBitwidth(
8221           NewSize, Type->hasSignedIntegerRepresentation() ||
8222                        C.getTypeSize(Type) < NewSize);
8223       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8224         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8225                                                  Sema::AA_Converting, true);
8226         if (!Diff.isUsable())
8227           return nullptr;
8228       }
8229     }
8230   }
8231 
8232   return Diff.get();
8233 }
8234 
8235 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8236     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8237   // Do not build for iterators, they cannot be used in non-rectangular loop
8238   // nests.
8239   if (LCDecl->getType()->isRecordType())
8240     return std::make_pair(nullptr, nullptr);
8241   // If we subtract, the min is in the condition, otherwise the min is in the
8242   // init value.
8243   Expr *MinExpr = nullptr;
8244   Expr *MaxExpr = nullptr;
8245   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8246   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8247   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8248                                            : CondDependOnLC.hasValue();
8249   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8250                                            : InitDependOnLC.hasValue();
8251   Expr *Lower =
8252       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8253   Expr *Upper =
8254       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8255   if (!Upper || !Lower)
8256     return std::make_pair(nullptr, nullptr);
8257 
8258   if (TestIsLessOp.getValue())
8259     MinExpr = Lower;
8260   else
8261     MaxExpr = Upper;
8262 
8263   // Build minimum/maximum value based on number of iterations.
8264   QualType VarType = LCDecl->getType().getNonReferenceType();
8265 
8266   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8267                                       Step, VarType, TestIsStrictOp,
8268                                       /*RoundToStep=*/false, Captures);
8269   if (!Diff.isUsable())
8270     return std::make_pair(nullptr, nullptr);
8271 
8272   // ((Upper - Lower [- 1]) / Step) * Step
8273   // Parentheses (for dumping/debugging purposes only).
8274   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8275   if (!Diff.isUsable())
8276     return std::make_pair(nullptr, nullptr);
8277 
8278   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8279   if (!NewStep.isUsable())
8280     return std::make_pair(nullptr, nullptr);
8281   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8282   if (!Diff.isUsable())
8283     return std::make_pair(nullptr, nullptr);
8284 
8285   // Parentheses (for dumping/debugging purposes only).
8286   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8287   if (!Diff.isUsable())
8288     return std::make_pair(nullptr, nullptr);
8289 
8290   // Convert to the ptrdiff_t, if original type is pointer.
8291   if (VarType->isAnyPointerType() &&
8292       !SemaRef.Context.hasSameType(
8293           Diff.get()->getType(),
8294           SemaRef.Context.getUnsignedPointerDiffType())) {
8295     Diff = SemaRef.PerformImplicitConversion(
8296         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8297         Sema::AA_Converting, /*AllowExplicit=*/true);
8298   }
8299   if (!Diff.isUsable())
8300     return std::make_pair(nullptr, nullptr);
8301 
8302   if (TestIsLessOp.getValue()) {
8303     // MinExpr = Lower;
8304     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8305     Diff = SemaRef.BuildBinOp(
8306         S, DefaultLoc, BO_Add,
8307         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8308         Diff.get());
8309     if (!Diff.isUsable())
8310       return std::make_pair(nullptr, nullptr);
8311   } else {
8312     // MaxExpr = Upper;
8313     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8314     Diff = SemaRef.BuildBinOp(
8315         S, DefaultLoc, BO_Sub,
8316         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8317         Diff.get());
8318     if (!Diff.isUsable())
8319       return std::make_pair(nullptr, nullptr);
8320   }
8321 
8322   // Convert to the original type.
8323   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8324     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8325                                              Sema::AA_Converting,
8326                                              /*AllowExplicit=*/true);
8327   if (!Diff.isUsable())
8328     return std::make_pair(nullptr, nullptr);
8329 
8330   Sema::TentativeAnalysisScope Trap(SemaRef);
8331   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8332   if (!Diff.isUsable())
8333     return std::make_pair(nullptr, nullptr);
8334 
8335   if (TestIsLessOp.getValue())
8336     MaxExpr = Diff.get();
8337   else
8338     MinExpr = Diff.get();
8339 
8340   return std::make_pair(MinExpr, MaxExpr);
8341 }
8342 
8343 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8344   if (InitDependOnLC || CondDependOnLC)
8345     return Condition;
8346   return nullptr;
8347 }
8348 
8349 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8350     Scope *S, Expr *Cond,
8351     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8352   // Do not build a precondition when the condition/initialization is dependent
8353   // to prevent pessimistic early loop exit.
8354   // TODO: this can be improved by calculating min/max values but not sure that
8355   // it will be very effective.
8356   if (CondDependOnLC || InitDependOnLC)
8357     return SemaRef.PerformImplicitConversion(
8358         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8359         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8360         /*AllowExplicit=*/true).get();
8361 
8362   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8363   Sema::TentativeAnalysisScope Trap(SemaRef);
8364 
8365   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8366   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8367   if (!NewLB.isUsable() || !NewUB.isUsable())
8368     return nullptr;
8369 
8370   ExprResult CondExpr =
8371       SemaRef.BuildBinOp(S, DefaultLoc,
8372                          TestIsLessOp.getValue() ?
8373                            (TestIsStrictOp ? BO_LT : BO_LE) :
8374                            (TestIsStrictOp ? BO_GT : BO_GE),
8375                          NewLB.get(), NewUB.get());
8376   if (CondExpr.isUsable()) {
8377     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8378                                                 SemaRef.Context.BoolTy))
8379       CondExpr = SemaRef.PerformImplicitConversion(
8380           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8381           /*AllowExplicit=*/true);
8382   }
8383 
8384   // Otherwise use original loop condition and evaluate it in runtime.
8385   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8386 }
8387 
8388 /// Build reference expression to the counter be used for codegen.
8389 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8390     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8391     DSAStackTy &DSA) const {
8392   auto *VD = dyn_cast<VarDecl>(LCDecl);
8393   if (!VD) {
8394     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8395     DeclRefExpr *Ref = buildDeclRefExpr(
8396         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8397     const DSAStackTy::DSAVarData Data =
8398         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8399     // If the loop control decl is explicitly marked as private, do not mark it
8400     // as captured again.
8401     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8402       Captures.insert(std::make_pair(LCRef, Ref));
8403     return Ref;
8404   }
8405   return cast<DeclRefExpr>(LCRef);
8406 }
8407 
8408 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8409   if (LCDecl && !LCDecl->isInvalidDecl()) {
8410     QualType Type = LCDecl->getType().getNonReferenceType();
8411     VarDecl *PrivateVar = buildVarDecl(
8412         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8413         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8414         isa<VarDecl>(LCDecl)
8415             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8416             : nullptr);
8417     if (PrivateVar->isInvalidDecl())
8418       return nullptr;
8419     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8420   }
8421   return nullptr;
8422 }
8423 
8424 /// Build initialization of the counter to be used for codegen.
8425 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8426 
8427 /// Build step of the counter be used for codegen.
8428 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8429 
8430 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8431     Scope *S, Expr *Counter,
8432     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8433     Expr *Inc, OverloadedOperatorKind OOK) {
8434   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8435   if (!Cnt)
8436     return nullptr;
8437   if (Inc) {
8438     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8439            "Expected only + or - operations for depend clauses.");
8440     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8441     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8442     if (!Cnt)
8443       return nullptr;
8444   }
8445   QualType VarType = LCDecl->getType().getNonReferenceType();
8446   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8447       !SemaRef.getLangOpts().CPlusPlus)
8448     return nullptr;
8449   // Upper - Lower
8450   Expr *Upper = TestIsLessOp.getValue()
8451                     ? Cnt
8452                     : tryBuildCapture(SemaRef, LB, Captures).get();
8453   Expr *Lower = TestIsLessOp.getValue()
8454                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8455                     : Cnt;
8456   if (!Upper || !Lower)
8457     return nullptr;
8458 
8459   ExprResult Diff = calculateNumIters(
8460       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8461       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8462   if (!Diff.isUsable())
8463     return nullptr;
8464 
8465   return Diff.get();
8466 }
8467 } // namespace
8468 
8469 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8470   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8471   assert(Init && "Expected loop in canonical form.");
8472   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8473   if (AssociatedLoops > 0 &&
8474       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8475     DSAStack->loopStart();
8476     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8477                                     *DSAStack, ForLoc);
8478     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8479       if (ValueDecl *D = ISC.getLoopDecl()) {
8480         auto *VD = dyn_cast<VarDecl>(D);
8481         DeclRefExpr *PrivateRef = nullptr;
8482         if (!VD) {
8483           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8484             VD = Private;
8485           } else {
8486             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8487                                       /*WithInit=*/false);
8488             VD = cast<VarDecl>(PrivateRef->getDecl());
8489           }
8490         }
8491         DSAStack->addLoopControlVariable(D, VD);
8492         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8493         if (LD != D->getCanonicalDecl()) {
8494           DSAStack->resetPossibleLoopCounter();
8495           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8496             MarkDeclarationsReferencedInExpr(
8497                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8498                                  Var->getType().getNonLValueExprType(Context),
8499                                  ForLoc, /*RefersToCapture=*/true));
8500         }
8501         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8502         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8503         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8504         // associated for-loop of a simd construct with just one associated
8505         // for-loop may be listed in a linear clause with a constant-linear-step
8506         // that is the increment of the associated for-loop. The loop iteration
8507         // variable(s) in the associated for-loop(s) of a for or parallel for
8508         // construct may be listed in a private or lastprivate clause.
8509         DSAStackTy::DSAVarData DVar =
8510             DSAStack->getTopDSA(D, /*FromParent=*/false);
8511         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8512         // is declared in the loop and it is predetermined as a private.
8513         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8514         OpenMPClauseKind PredeterminedCKind =
8515             isOpenMPSimdDirective(DKind)
8516                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8517                 : OMPC_private;
8518         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8519               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8520               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8521                                          DVar.CKind != OMPC_private))) ||
8522              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8523                DKind == OMPD_master_taskloop ||
8524                DKind == OMPD_parallel_master_taskloop ||
8525                isOpenMPDistributeDirective(DKind)) &&
8526               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8527               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8528             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8529           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8530               << getOpenMPClauseName(DVar.CKind)
8531               << getOpenMPDirectiveName(DKind)
8532               << getOpenMPClauseName(PredeterminedCKind);
8533           if (DVar.RefExpr == nullptr)
8534             DVar.CKind = PredeterminedCKind;
8535           reportOriginalDsa(*this, DSAStack, D, DVar,
8536                             /*IsLoopIterVar=*/true);
8537         } else if (LoopDeclRefExpr) {
8538           // Make the loop iteration variable private (for worksharing
8539           // constructs), linear (for simd directives with the only one
8540           // associated loop) or lastprivate (for simd directives with several
8541           // collapsed or ordered loops).
8542           if (DVar.CKind == OMPC_unknown)
8543             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8544                              PrivateRef);
8545         }
8546       }
8547     }
8548     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8549   }
8550 }
8551 
8552 /// Called on a for stmt to check and extract its iteration space
8553 /// for further processing (such as collapsing).
8554 static bool checkOpenMPIterationSpace(
8555     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8556     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8557     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8558     Expr *OrderedLoopCountExpr,
8559     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8560     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8561     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8562   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8563   // OpenMP [2.9.1, Canonical Loop Form]
8564   //   for (init-expr; test-expr; incr-expr) structured-block
8565   //   for (range-decl: range-expr) structured-block
8566   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8567     S = CanonLoop->getLoopStmt();
8568   auto *For = dyn_cast_or_null<ForStmt>(S);
8569   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8570   // Ranged for is supported only in OpenMP 5.0.
8571   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8572     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8573         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8574         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8575         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8576     if (TotalNestedLoopCount > 1) {
8577       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8578         SemaRef.Diag(DSA.getConstructLoc(),
8579                      diag::note_omp_collapse_ordered_expr)
8580             << 2 << CollapseLoopCountExpr->getSourceRange()
8581             << OrderedLoopCountExpr->getSourceRange();
8582       else if (CollapseLoopCountExpr)
8583         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8584                      diag::note_omp_collapse_ordered_expr)
8585             << 0 << CollapseLoopCountExpr->getSourceRange();
8586       else
8587         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8588                      diag::note_omp_collapse_ordered_expr)
8589             << 1 << OrderedLoopCountExpr->getSourceRange();
8590     }
8591     return true;
8592   }
8593   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8594          "No loop body.");
8595 
8596   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8597                                   For ? For->getForLoc() : CXXFor->getForLoc());
8598 
8599   // Check init.
8600   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8601   if (ISC.checkAndSetInit(Init))
8602     return true;
8603 
8604   bool HasErrors = false;
8605 
8606   // Check loop variable's type.
8607   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8608     // OpenMP [2.6, Canonical Loop Form]
8609     // Var is one of the following:
8610     //   A variable of signed or unsigned integer type.
8611     //   For C++, a variable of a random access iterator type.
8612     //   For C, a variable of a pointer type.
8613     QualType VarType = LCDecl->getType().getNonReferenceType();
8614     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8615         !VarType->isPointerType() &&
8616         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8617       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8618           << SemaRef.getLangOpts().CPlusPlus;
8619       HasErrors = true;
8620     }
8621 
8622     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8623     // a Construct
8624     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8625     // parallel for construct is (are) private.
8626     // The loop iteration variable in the associated for-loop of a simd
8627     // construct with just one associated for-loop is linear with a
8628     // constant-linear-step that is the increment of the associated for-loop.
8629     // Exclude loop var from the list of variables with implicitly defined data
8630     // sharing attributes.
8631     VarsWithImplicitDSA.erase(LCDecl);
8632 
8633     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8634 
8635     // Check test-expr.
8636     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8637 
8638     // Check incr-expr.
8639     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8640   }
8641 
8642   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8643     return HasErrors;
8644 
8645   // Build the loop's iteration space representation.
8646   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8647       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8648   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8649       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8650                              (isOpenMPWorksharingDirective(DKind) ||
8651                               isOpenMPTaskLoopDirective(DKind) ||
8652                               isOpenMPDistributeDirective(DKind) ||
8653                               isOpenMPLoopTransformationDirective(DKind)),
8654                              Captures);
8655   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8656       ISC.buildCounterVar(Captures, DSA);
8657   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8658       ISC.buildPrivateCounterVar();
8659   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8660   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8661   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8662   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8663       ISC.getConditionSrcRange();
8664   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8665       ISC.getIncrementSrcRange();
8666   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8667   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8668       ISC.isStrictTestOp();
8669   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8670            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8671       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8672   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8673       ISC.buildFinalCondition(DSA.getCurScope());
8674   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8675       ISC.doesInitDependOnLC();
8676   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8677       ISC.doesCondDependOnLC();
8678   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8679       ISC.getLoopDependentIdx();
8680 
8681   HasErrors |=
8682       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8683        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8684        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8685        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8686        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8687        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8688   if (!HasErrors && DSA.isOrderedRegion()) {
8689     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8690       if (CurrentNestedLoopCount <
8691           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8692         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8693             CurrentNestedLoopCount,
8694             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8695         DSA.getOrderedRegionParam().second->setLoopCounter(
8696             CurrentNestedLoopCount,
8697             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8698       }
8699     }
8700     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8701       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8702         // Erroneous case - clause has some problems.
8703         continue;
8704       }
8705       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8706           Pair.second.size() <= CurrentNestedLoopCount) {
8707         // Erroneous case - clause has some problems.
8708         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8709         continue;
8710       }
8711       Expr *CntValue;
8712       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8713         CntValue = ISC.buildOrderedLoopData(
8714             DSA.getCurScope(),
8715             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8716             Pair.first->getDependencyLoc());
8717       else
8718         CntValue = ISC.buildOrderedLoopData(
8719             DSA.getCurScope(),
8720             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8721             Pair.first->getDependencyLoc(),
8722             Pair.second[CurrentNestedLoopCount].first,
8723             Pair.second[CurrentNestedLoopCount].second);
8724       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8725     }
8726   }
8727 
8728   return HasErrors;
8729 }
8730 
8731 /// Build 'VarRef = Start.
8732 static ExprResult
8733 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8734                  ExprResult Start, bool IsNonRectangularLB,
8735                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8736   // Build 'VarRef = Start.
8737   ExprResult NewStart = IsNonRectangularLB
8738                             ? Start.get()
8739                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8740   if (!NewStart.isUsable())
8741     return ExprError();
8742   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8743                                    VarRef.get()->getType())) {
8744     NewStart = SemaRef.PerformImplicitConversion(
8745         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8746         /*AllowExplicit=*/true);
8747     if (!NewStart.isUsable())
8748       return ExprError();
8749   }
8750 
8751   ExprResult Init =
8752       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8753   return Init;
8754 }
8755 
8756 /// Build 'VarRef = Start + Iter * Step'.
8757 static ExprResult buildCounterUpdate(
8758     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8759     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8760     bool IsNonRectangularLB,
8761     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8762   // Add parentheses (for debugging purposes only).
8763   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8764   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8765       !Step.isUsable())
8766     return ExprError();
8767 
8768   ExprResult NewStep = Step;
8769   if (Captures)
8770     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8771   if (NewStep.isInvalid())
8772     return ExprError();
8773   ExprResult Update =
8774       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8775   if (!Update.isUsable())
8776     return ExprError();
8777 
8778   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8779   // 'VarRef = Start (+|-) Iter * Step'.
8780   if (!Start.isUsable())
8781     return ExprError();
8782   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8783   if (!NewStart.isUsable())
8784     return ExprError();
8785   if (Captures && !IsNonRectangularLB)
8786     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
8787   if (NewStart.isInvalid())
8788     return ExprError();
8789 
8790   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
8791   ExprResult SavedUpdate = Update;
8792   ExprResult UpdateVal;
8793   if (VarRef.get()->getType()->isOverloadableType() ||
8794       NewStart.get()->getType()->isOverloadableType() ||
8795       Update.get()->getType()->isOverloadableType()) {
8796     Sema::TentativeAnalysisScope Trap(SemaRef);
8797 
8798     Update =
8799         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8800     if (Update.isUsable()) {
8801       UpdateVal =
8802           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
8803                              VarRef.get(), SavedUpdate.get());
8804       if (UpdateVal.isUsable()) {
8805         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
8806                                             UpdateVal.get());
8807       }
8808     }
8809   }
8810 
8811   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
8812   if (!Update.isUsable() || !UpdateVal.isUsable()) {
8813     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
8814                                 NewStart.get(), SavedUpdate.get());
8815     if (!Update.isUsable())
8816       return ExprError();
8817 
8818     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
8819                                      VarRef.get()->getType())) {
8820       Update = SemaRef.PerformImplicitConversion(
8821           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
8822       if (!Update.isUsable())
8823         return ExprError();
8824     }
8825 
8826     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
8827   }
8828   return Update;
8829 }
8830 
8831 /// Convert integer expression \a E to make it have at least \a Bits
8832 /// bits.
8833 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
8834   if (E == nullptr)
8835     return ExprError();
8836   ASTContext &C = SemaRef.Context;
8837   QualType OldType = E->getType();
8838   unsigned HasBits = C.getTypeSize(OldType);
8839   if (HasBits >= Bits)
8840     return ExprResult(E);
8841   // OK to convert to signed, because new type has more bits than old.
8842   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
8843   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
8844                                            true);
8845 }
8846 
8847 /// Check if the given expression \a E is a constant integer that fits
8848 /// into \a Bits bits.
8849 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
8850   if (E == nullptr)
8851     return false;
8852   if (Optional<llvm::APSInt> Result =
8853           E->getIntegerConstantExpr(SemaRef.Context))
8854     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
8855   return false;
8856 }
8857 
8858 /// Build preinits statement for the given declarations.
8859 static Stmt *buildPreInits(ASTContext &Context,
8860                            MutableArrayRef<Decl *> PreInits) {
8861   if (!PreInits.empty()) {
8862     return new (Context) DeclStmt(
8863         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
8864         SourceLocation(), SourceLocation());
8865   }
8866   return nullptr;
8867 }
8868 
8869 /// Build preinits statement for the given declarations.
8870 static Stmt *
8871 buildPreInits(ASTContext &Context,
8872               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8873   if (!Captures.empty()) {
8874     SmallVector<Decl *, 16> PreInits;
8875     for (const auto &Pair : Captures)
8876       PreInits.push_back(Pair.second->getDecl());
8877     return buildPreInits(Context, PreInits);
8878   }
8879   return nullptr;
8880 }
8881 
8882 /// Build postupdate expression for the given list of postupdates expressions.
8883 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
8884   Expr *PostUpdate = nullptr;
8885   if (!PostUpdates.empty()) {
8886     for (Expr *E : PostUpdates) {
8887       Expr *ConvE = S.BuildCStyleCastExpr(
8888                          E->getExprLoc(),
8889                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
8890                          E->getExprLoc(), E)
8891                         .get();
8892       PostUpdate = PostUpdate
8893                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
8894                                               PostUpdate, ConvE)
8895                              .get()
8896                        : ConvE;
8897     }
8898   }
8899   return PostUpdate;
8900 }
8901 
8902 /// Called on a for stmt to check itself and nested loops (if any).
8903 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
8904 /// number of collapsed loops otherwise.
8905 static unsigned
8906 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
8907                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
8908                 DSAStackTy &DSA,
8909                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8910                 OMPLoopBasedDirective::HelperExprs &Built) {
8911   unsigned NestedLoopCount = 1;
8912   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
8913                                     !isOpenMPLoopTransformationDirective(DKind);
8914 
8915   if (CollapseLoopCountExpr) {
8916     // Found 'collapse' clause - calculate collapse number.
8917     Expr::EvalResult Result;
8918     if (!CollapseLoopCountExpr->isValueDependent() &&
8919         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
8920       NestedLoopCount = Result.Val.getInt().getLimitedValue();
8921     } else {
8922       Built.clear(/*Size=*/1);
8923       return 1;
8924     }
8925   }
8926   unsigned OrderedLoopCount = 1;
8927   if (OrderedLoopCountExpr) {
8928     // Found 'ordered' clause - calculate collapse number.
8929     Expr::EvalResult EVResult;
8930     if (!OrderedLoopCountExpr->isValueDependent() &&
8931         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
8932                                             SemaRef.getASTContext())) {
8933       llvm::APSInt Result = EVResult.Val.getInt();
8934       if (Result.getLimitedValue() < NestedLoopCount) {
8935         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8936                      diag::err_omp_wrong_ordered_loop_count)
8937             << OrderedLoopCountExpr->getSourceRange();
8938         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8939                      diag::note_collapse_loop_count)
8940             << CollapseLoopCountExpr->getSourceRange();
8941       }
8942       OrderedLoopCount = Result.getLimitedValue();
8943     } else {
8944       Built.clear(/*Size=*/1);
8945       return 1;
8946     }
8947   }
8948   // This is helper routine for loop directives (e.g., 'for', 'simd',
8949   // 'for simd', etc.).
8950   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8951   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
8952   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
8953   if (!OMPLoopBasedDirective::doForAllLoops(
8954           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
8955           SupportsNonPerfectlyNested, NumLoops,
8956           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
8957            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
8958            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
8959             if (checkOpenMPIterationSpace(
8960                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8961                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
8962                     VarsWithImplicitDSA, IterSpaces, Captures))
8963               return true;
8964             if (Cnt > 0 && Cnt >= NestedLoopCount &&
8965                 IterSpaces[Cnt].CounterVar) {
8966               // Handle initialization of captured loop iterator variables.
8967               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8968               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8969                 Captures[DRE] = DRE;
8970               }
8971             }
8972             return false;
8973           },
8974           [&SemaRef, &Captures](OMPLoopBasedDirective *Transform) {
8975             Stmt *DependentPreInits;
8976             if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) {
8977               DependentPreInits = Dir->getPreInits();
8978             } else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) {
8979               DependentPreInits = Dir->getPreInits();
8980             } else {
8981               llvm_unreachable("Unexpected loop transformation");
8982             }
8983             if (!DependentPreInits)
8984               return;
8985             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
8986               auto *D = cast<VarDecl>(C);
8987               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
8988                                                   Transform->getBeginLoc());
8989               Captures[Ref] = Ref;
8990             }
8991           }))
8992     return 0;
8993 
8994   Built.clear(/* size */ NestedLoopCount);
8995 
8996   if (SemaRef.CurContext->isDependentContext())
8997     return NestedLoopCount;
8998 
8999   // An example of what is generated for the following code:
9000   //
9001   //   #pragma omp simd collapse(2) ordered(2)
9002   //   for (i = 0; i < NI; ++i)
9003   //     for (k = 0; k < NK; ++k)
9004   //       for (j = J0; j < NJ; j+=2) {
9005   //         <loop body>
9006   //       }
9007   //
9008   // We generate the code below.
9009   // Note: the loop body may be outlined in CodeGen.
9010   // Note: some counters may be C++ classes, operator- is used to find number of
9011   // iterations and operator+= to calculate counter value.
9012   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9013   // or i64 is currently supported).
9014   //
9015   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9016   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9017   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9018   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9019   //     // similar updates for vars in clauses (e.g. 'linear')
9020   //     <loop body (using local i and j)>
9021   //   }
9022   //   i = NI; // assign final values of counters
9023   //   j = NJ;
9024   //
9025 
9026   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9027   // the iteration counts of the collapsed for loops.
9028   // Precondition tests if there is at least one iteration (all conditions are
9029   // true).
9030   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9031   Expr *N0 = IterSpaces[0].NumIterations;
9032   ExprResult LastIteration32 =
9033       widenIterationCount(/*Bits=*/32,
9034                           SemaRef
9035                               .PerformImplicitConversion(
9036                                   N0->IgnoreImpCasts(), N0->getType(),
9037                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9038                               .get(),
9039                           SemaRef);
9040   ExprResult LastIteration64 = widenIterationCount(
9041       /*Bits=*/64,
9042       SemaRef
9043           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9044                                      Sema::AA_Converting,
9045                                      /*AllowExplicit=*/true)
9046           .get(),
9047       SemaRef);
9048 
9049   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9050     return NestedLoopCount;
9051 
9052   ASTContext &C = SemaRef.Context;
9053   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9054 
9055   Scope *CurScope = DSA.getCurScope();
9056   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9057     if (PreCond.isUsable()) {
9058       PreCond =
9059           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9060                              PreCond.get(), IterSpaces[Cnt].PreCond);
9061     }
9062     Expr *N = IterSpaces[Cnt].NumIterations;
9063     SourceLocation Loc = N->getExprLoc();
9064     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9065     if (LastIteration32.isUsable())
9066       LastIteration32 = SemaRef.BuildBinOp(
9067           CurScope, Loc, BO_Mul, LastIteration32.get(),
9068           SemaRef
9069               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9070                                          Sema::AA_Converting,
9071                                          /*AllowExplicit=*/true)
9072               .get());
9073     if (LastIteration64.isUsable())
9074       LastIteration64 = SemaRef.BuildBinOp(
9075           CurScope, Loc, BO_Mul, LastIteration64.get(),
9076           SemaRef
9077               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9078                                          Sema::AA_Converting,
9079                                          /*AllowExplicit=*/true)
9080               .get());
9081   }
9082 
9083   // Choose either the 32-bit or 64-bit version.
9084   ExprResult LastIteration = LastIteration64;
9085   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9086       (LastIteration32.isUsable() &&
9087        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9088        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9089         fitsInto(
9090             /*Bits=*/32,
9091             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9092             LastIteration64.get(), SemaRef))))
9093     LastIteration = LastIteration32;
9094   QualType VType = LastIteration.get()->getType();
9095   QualType RealVType = VType;
9096   QualType StrideVType = VType;
9097   if (isOpenMPTaskLoopDirective(DKind)) {
9098     VType =
9099         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9100     StrideVType =
9101         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9102   }
9103 
9104   if (!LastIteration.isUsable())
9105     return 0;
9106 
9107   // Save the number of iterations.
9108   ExprResult NumIterations = LastIteration;
9109   {
9110     LastIteration = SemaRef.BuildBinOp(
9111         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9112         LastIteration.get(),
9113         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9114     if (!LastIteration.isUsable())
9115       return 0;
9116   }
9117 
9118   // Calculate the last iteration number beforehand instead of doing this on
9119   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9120   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9121   ExprResult CalcLastIteration;
9122   if (!IsConstant) {
9123     ExprResult SaveRef =
9124         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9125     LastIteration = SaveRef;
9126 
9127     // Prepare SaveRef + 1.
9128     NumIterations = SemaRef.BuildBinOp(
9129         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9130         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9131     if (!NumIterations.isUsable())
9132       return 0;
9133   }
9134 
9135   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9136 
9137   // Build variables passed into runtime, necessary for worksharing directives.
9138   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9139   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9140       isOpenMPDistributeDirective(DKind) ||
9141       isOpenMPLoopTransformationDirective(DKind)) {
9142     // Lower bound variable, initialized with zero.
9143     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9144     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9145     SemaRef.AddInitializerToDecl(LBDecl,
9146                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9147                                  /*DirectInit*/ false);
9148 
9149     // Upper bound variable, initialized with last iteration number.
9150     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9151     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9152     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9153                                  /*DirectInit*/ false);
9154 
9155     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9156     // This will be used to implement clause 'lastprivate'.
9157     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9158     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9159     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9160     SemaRef.AddInitializerToDecl(ILDecl,
9161                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9162                                  /*DirectInit*/ false);
9163 
9164     // Stride variable returned by runtime (we initialize it to 1 by default).
9165     VarDecl *STDecl =
9166         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9167     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9168     SemaRef.AddInitializerToDecl(STDecl,
9169                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9170                                  /*DirectInit*/ false);
9171 
9172     // Build expression: UB = min(UB, LastIteration)
9173     // It is necessary for CodeGen of directives with static scheduling.
9174     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9175                                                 UB.get(), LastIteration.get());
9176     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9177         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9178         LastIteration.get(), UB.get());
9179     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9180                              CondOp.get());
9181     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9182 
9183     // If we have a combined directive that combines 'distribute', 'for' or
9184     // 'simd' we need to be able to access the bounds of the schedule of the
9185     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9186     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9187     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9188       // Lower bound variable, initialized with zero.
9189       VarDecl *CombLBDecl =
9190           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9191       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9192       SemaRef.AddInitializerToDecl(
9193           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9194           /*DirectInit*/ false);
9195 
9196       // Upper bound variable, initialized with last iteration number.
9197       VarDecl *CombUBDecl =
9198           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9199       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9200       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9201                                    /*DirectInit*/ false);
9202 
9203       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9204           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9205       ExprResult CombCondOp =
9206           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9207                                      LastIteration.get(), CombUB.get());
9208       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9209                                    CombCondOp.get());
9210       CombEUB =
9211           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9212 
9213       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9214       // We expect to have at least 2 more parameters than the 'parallel'
9215       // directive does - the lower and upper bounds of the previous schedule.
9216       assert(CD->getNumParams() >= 4 &&
9217              "Unexpected number of parameters in loop combined directive");
9218 
9219       // Set the proper type for the bounds given what we learned from the
9220       // enclosed loops.
9221       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9222       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9223 
9224       // Previous lower and upper bounds are obtained from the region
9225       // parameters.
9226       PrevLB =
9227           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9228       PrevUB =
9229           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9230     }
9231   }
9232 
9233   // Build the iteration variable and its initialization before loop.
9234   ExprResult IV;
9235   ExprResult Init, CombInit;
9236   {
9237     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9238     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9239     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9240                  isOpenMPTaskLoopDirective(DKind) ||
9241                  isOpenMPDistributeDirective(DKind) ||
9242                  isOpenMPLoopTransformationDirective(DKind))
9243                     ? LB.get()
9244                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9245     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9246     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9247 
9248     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9249       Expr *CombRHS =
9250           (isOpenMPWorksharingDirective(DKind) ||
9251            isOpenMPTaskLoopDirective(DKind) ||
9252            isOpenMPDistributeDirective(DKind))
9253               ? CombLB.get()
9254               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9255       CombInit =
9256           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9257       CombInit =
9258           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9259     }
9260   }
9261 
9262   bool UseStrictCompare =
9263       RealVType->hasUnsignedIntegerRepresentation() &&
9264       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9265         return LIS.IsStrictCompare;
9266       });
9267   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9268   // unsigned IV)) for worksharing loops.
9269   SourceLocation CondLoc = AStmt->getBeginLoc();
9270   Expr *BoundUB = UB.get();
9271   if (UseStrictCompare) {
9272     BoundUB =
9273         SemaRef
9274             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9275                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9276             .get();
9277     BoundUB =
9278         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9279   }
9280   ExprResult Cond =
9281       (isOpenMPWorksharingDirective(DKind) ||
9282        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9283        isOpenMPLoopTransformationDirective(DKind))
9284           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9285                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9286                                BoundUB)
9287           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9288                                NumIterations.get());
9289   ExprResult CombDistCond;
9290   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9291     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9292                                       NumIterations.get());
9293   }
9294 
9295   ExprResult CombCond;
9296   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9297     Expr *BoundCombUB = CombUB.get();
9298     if (UseStrictCompare) {
9299       BoundCombUB =
9300           SemaRef
9301               .BuildBinOp(
9302                   CurScope, CondLoc, BO_Add, BoundCombUB,
9303                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9304               .get();
9305       BoundCombUB =
9306           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9307               .get();
9308     }
9309     CombCond =
9310         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9311                            IV.get(), BoundCombUB);
9312   }
9313   // Loop increment (IV = IV + 1)
9314   SourceLocation IncLoc = AStmt->getBeginLoc();
9315   ExprResult Inc =
9316       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9317                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9318   if (!Inc.isUsable())
9319     return 0;
9320   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9321   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9322   if (!Inc.isUsable())
9323     return 0;
9324 
9325   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9326   // Used for directives with static scheduling.
9327   // In combined construct, add combined version that use CombLB and CombUB
9328   // base variables for the update
9329   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9330   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9331       isOpenMPDistributeDirective(DKind) ||
9332       isOpenMPLoopTransformationDirective(DKind)) {
9333     // LB + ST
9334     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9335     if (!NextLB.isUsable())
9336       return 0;
9337     // LB = LB + ST
9338     NextLB =
9339         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9340     NextLB =
9341         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9342     if (!NextLB.isUsable())
9343       return 0;
9344     // UB + ST
9345     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9346     if (!NextUB.isUsable())
9347       return 0;
9348     // UB = UB + ST
9349     NextUB =
9350         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9351     NextUB =
9352         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9353     if (!NextUB.isUsable())
9354       return 0;
9355     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9356       CombNextLB =
9357           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9358       if (!NextLB.isUsable())
9359         return 0;
9360       // LB = LB + ST
9361       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9362                                       CombNextLB.get());
9363       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9364                                                /*DiscardedValue*/ false);
9365       if (!CombNextLB.isUsable())
9366         return 0;
9367       // UB + ST
9368       CombNextUB =
9369           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9370       if (!CombNextUB.isUsable())
9371         return 0;
9372       // UB = UB + ST
9373       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9374                                       CombNextUB.get());
9375       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9376                                                /*DiscardedValue*/ false);
9377       if (!CombNextUB.isUsable())
9378         return 0;
9379     }
9380   }
9381 
9382   // Create increment expression for distribute loop when combined in a same
9383   // directive with for as IV = IV + ST; ensure upper bound expression based
9384   // on PrevUB instead of NumIterations - used to implement 'for' when found
9385   // in combination with 'distribute', like in 'distribute parallel for'
9386   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9387   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9388   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9389     DistCond = SemaRef.BuildBinOp(
9390         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9391     assert(DistCond.isUsable() && "distribute cond expr was not built");
9392 
9393     DistInc =
9394         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9395     assert(DistInc.isUsable() && "distribute inc expr was not built");
9396     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9397                                  DistInc.get());
9398     DistInc =
9399         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9400     assert(DistInc.isUsable() && "distribute inc expr was not built");
9401 
9402     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9403     // construct
9404     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9405     ExprResult IsUBGreater =
9406         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
9407     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9408         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
9409     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9410                                  CondOp.get());
9411     PrevEUB =
9412         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9413 
9414     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9415     // parallel for is in combination with a distribute directive with
9416     // schedule(static, 1)
9417     Expr *BoundPrevUB = PrevUB.get();
9418     if (UseStrictCompare) {
9419       BoundPrevUB =
9420           SemaRef
9421               .BuildBinOp(
9422                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9423                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9424               .get();
9425       BoundPrevUB =
9426           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9427               .get();
9428     }
9429     ParForInDistCond =
9430         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9431                            IV.get(), BoundPrevUB);
9432   }
9433 
9434   // Build updates and final values of the loop counters.
9435   bool HasErrors = false;
9436   Built.Counters.resize(NestedLoopCount);
9437   Built.Inits.resize(NestedLoopCount);
9438   Built.Updates.resize(NestedLoopCount);
9439   Built.Finals.resize(NestedLoopCount);
9440   Built.DependentCounters.resize(NestedLoopCount);
9441   Built.DependentInits.resize(NestedLoopCount);
9442   Built.FinalsConditions.resize(NestedLoopCount);
9443   {
9444     // We implement the following algorithm for obtaining the
9445     // original loop iteration variable values based on the
9446     // value of the collapsed loop iteration variable IV.
9447     //
9448     // Let n+1 be the number of collapsed loops in the nest.
9449     // Iteration variables (I0, I1, .... In)
9450     // Iteration counts (N0, N1, ... Nn)
9451     //
9452     // Acc = IV;
9453     //
9454     // To compute Ik for loop k, 0 <= k <= n, generate:
9455     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9456     //    Ik = Acc / Prod;
9457     //    Acc -= Ik * Prod;
9458     //
9459     ExprResult Acc = IV;
9460     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9461       LoopIterationSpace &IS = IterSpaces[Cnt];
9462       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9463       ExprResult Iter;
9464 
9465       // Compute prod
9466       ExprResult Prod =
9467           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9468       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
9469         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9470                                   IterSpaces[K].NumIterations);
9471 
9472       // Iter = Acc / Prod
9473       // If there is at least one more inner loop to avoid
9474       // multiplication by 1.
9475       if (Cnt + 1 < NestedLoopCount)
9476         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
9477                                   Acc.get(), Prod.get());
9478       else
9479         Iter = Acc;
9480       if (!Iter.isUsable()) {
9481         HasErrors = true;
9482         break;
9483       }
9484 
9485       // Update Acc:
9486       // Acc -= Iter * Prod
9487       // Check if there is at least one more inner loop to avoid
9488       // multiplication by 1.
9489       if (Cnt + 1 < NestedLoopCount)
9490         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
9491                                   Iter.get(), Prod.get());
9492       else
9493         Prod = Iter;
9494       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
9495                                Acc.get(), Prod.get());
9496 
9497       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9498       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9499       DeclRefExpr *CounterVar = buildDeclRefExpr(
9500           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9501           /*RefersToCapture=*/true);
9502       ExprResult Init =
9503           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9504                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9505       if (!Init.isUsable()) {
9506         HasErrors = true;
9507         break;
9508       }
9509       ExprResult Update = buildCounterUpdate(
9510           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9511           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9512       if (!Update.isUsable()) {
9513         HasErrors = true;
9514         break;
9515       }
9516 
9517       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9518       ExprResult Final =
9519           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9520                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9521                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9522       if (!Final.isUsable()) {
9523         HasErrors = true;
9524         break;
9525       }
9526 
9527       if (!Update.isUsable() || !Final.isUsable()) {
9528         HasErrors = true;
9529         break;
9530       }
9531       // Save results
9532       Built.Counters[Cnt] = IS.CounterVar;
9533       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9534       Built.Inits[Cnt] = Init.get();
9535       Built.Updates[Cnt] = Update.get();
9536       Built.Finals[Cnt] = Final.get();
9537       Built.DependentCounters[Cnt] = nullptr;
9538       Built.DependentInits[Cnt] = nullptr;
9539       Built.FinalsConditions[Cnt] = nullptr;
9540       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9541         Built.DependentCounters[Cnt] =
9542             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9543         Built.DependentInits[Cnt] =
9544             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9545         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9546       }
9547     }
9548   }
9549 
9550   if (HasErrors)
9551     return 0;
9552 
9553   // Save results
9554   Built.IterationVarRef = IV.get();
9555   Built.LastIteration = LastIteration.get();
9556   Built.NumIterations = NumIterations.get();
9557   Built.CalcLastIteration = SemaRef
9558                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9559                                                      /*DiscardedValue=*/false)
9560                                 .get();
9561   Built.PreCond = PreCond.get();
9562   Built.PreInits = buildPreInits(C, Captures);
9563   Built.Cond = Cond.get();
9564   Built.Init = Init.get();
9565   Built.Inc = Inc.get();
9566   Built.LB = LB.get();
9567   Built.UB = UB.get();
9568   Built.IL = IL.get();
9569   Built.ST = ST.get();
9570   Built.EUB = EUB.get();
9571   Built.NLB = NextLB.get();
9572   Built.NUB = NextUB.get();
9573   Built.PrevLB = PrevLB.get();
9574   Built.PrevUB = PrevUB.get();
9575   Built.DistInc = DistInc.get();
9576   Built.PrevEUB = PrevEUB.get();
9577   Built.DistCombinedFields.LB = CombLB.get();
9578   Built.DistCombinedFields.UB = CombUB.get();
9579   Built.DistCombinedFields.EUB = CombEUB.get();
9580   Built.DistCombinedFields.Init = CombInit.get();
9581   Built.DistCombinedFields.Cond = CombCond.get();
9582   Built.DistCombinedFields.NLB = CombNextLB.get();
9583   Built.DistCombinedFields.NUB = CombNextUB.get();
9584   Built.DistCombinedFields.DistCond = CombDistCond.get();
9585   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9586 
9587   return NestedLoopCount;
9588 }
9589 
9590 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9591   auto CollapseClauses =
9592       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9593   if (CollapseClauses.begin() != CollapseClauses.end())
9594     return (*CollapseClauses.begin())->getNumForLoops();
9595   return nullptr;
9596 }
9597 
9598 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9599   auto OrderedClauses =
9600       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9601   if (OrderedClauses.begin() != OrderedClauses.end())
9602     return (*OrderedClauses.begin())->getNumForLoops();
9603   return nullptr;
9604 }
9605 
9606 static bool checkSimdlenSafelenSpecified(Sema &S,
9607                                          const ArrayRef<OMPClause *> Clauses) {
9608   const OMPSafelenClause *Safelen = nullptr;
9609   const OMPSimdlenClause *Simdlen = nullptr;
9610 
9611   for (const OMPClause *Clause : Clauses) {
9612     if (Clause->getClauseKind() == OMPC_safelen)
9613       Safelen = cast<OMPSafelenClause>(Clause);
9614     else if (Clause->getClauseKind() == OMPC_simdlen)
9615       Simdlen = cast<OMPSimdlenClause>(Clause);
9616     if (Safelen && Simdlen)
9617       break;
9618   }
9619 
9620   if (Simdlen && Safelen) {
9621     const Expr *SimdlenLength = Simdlen->getSimdlen();
9622     const Expr *SafelenLength = Safelen->getSafelen();
9623     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9624         SimdlenLength->isInstantiationDependent() ||
9625         SimdlenLength->containsUnexpandedParameterPack())
9626       return false;
9627     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9628         SafelenLength->isInstantiationDependent() ||
9629         SafelenLength->containsUnexpandedParameterPack())
9630       return false;
9631     Expr::EvalResult SimdlenResult, SafelenResult;
9632     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9633     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9634     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9635     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9636     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9637     // If both simdlen and safelen clauses are specified, the value of the
9638     // simdlen parameter must be less than or equal to the value of the safelen
9639     // parameter.
9640     if (SimdlenRes > SafelenRes) {
9641       S.Diag(SimdlenLength->getExprLoc(),
9642              diag::err_omp_wrong_simdlen_safelen_values)
9643           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9644       return true;
9645     }
9646   }
9647   return false;
9648 }
9649 
9650 StmtResult
9651 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9652                                SourceLocation StartLoc, SourceLocation EndLoc,
9653                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9654   if (!AStmt)
9655     return StmtError();
9656 
9657   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9658   OMPLoopBasedDirective::HelperExprs B;
9659   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9660   // define the nested loops number.
9661   unsigned NestedLoopCount = checkOpenMPLoop(
9662       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9663       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9664   if (NestedLoopCount == 0)
9665     return StmtError();
9666 
9667   assert((CurContext->isDependentContext() || B.builtAll()) &&
9668          "omp simd loop exprs were not built");
9669 
9670   if (!CurContext->isDependentContext()) {
9671     // Finalize the clauses that need pre-built expressions for CodeGen.
9672     for (OMPClause *C : Clauses) {
9673       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9674         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9675                                      B.NumIterations, *this, CurScope,
9676                                      DSAStack))
9677           return StmtError();
9678     }
9679   }
9680 
9681   if (checkSimdlenSafelenSpecified(*this, Clauses))
9682     return StmtError();
9683 
9684   setFunctionHasBranchProtectedScope();
9685   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9686                                   Clauses, AStmt, B);
9687 }
9688 
9689 StmtResult
9690 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9691                               SourceLocation StartLoc, SourceLocation EndLoc,
9692                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9693   if (!AStmt)
9694     return StmtError();
9695 
9696   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9697   OMPLoopBasedDirective::HelperExprs B;
9698   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9699   // define the nested loops number.
9700   unsigned NestedLoopCount = checkOpenMPLoop(
9701       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9702       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9703   if (NestedLoopCount == 0)
9704     return StmtError();
9705 
9706   assert((CurContext->isDependentContext() || B.builtAll()) &&
9707          "omp for loop exprs were not built");
9708 
9709   if (!CurContext->isDependentContext()) {
9710     // Finalize the clauses that need pre-built expressions for CodeGen.
9711     for (OMPClause *C : Clauses) {
9712       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9713         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9714                                      B.NumIterations, *this, CurScope,
9715                                      DSAStack))
9716           return StmtError();
9717     }
9718   }
9719 
9720   setFunctionHasBranchProtectedScope();
9721   return OMPForDirective::Create(
9722       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9723       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9724 }
9725 
9726 StmtResult Sema::ActOnOpenMPForSimdDirective(
9727     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9728     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9729   if (!AStmt)
9730     return StmtError();
9731 
9732   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9733   OMPLoopBasedDirective::HelperExprs B;
9734   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9735   // define the nested loops number.
9736   unsigned NestedLoopCount =
9737       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9738                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9739                       VarsWithImplicitDSA, B);
9740   if (NestedLoopCount == 0)
9741     return StmtError();
9742 
9743   assert((CurContext->isDependentContext() || B.builtAll()) &&
9744          "omp for simd loop exprs were not built");
9745 
9746   if (!CurContext->isDependentContext()) {
9747     // Finalize the clauses that need pre-built expressions for CodeGen.
9748     for (OMPClause *C : Clauses) {
9749       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9750         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9751                                      B.NumIterations, *this, CurScope,
9752                                      DSAStack))
9753           return StmtError();
9754     }
9755   }
9756 
9757   if (checkSimdlenSafelenSpecified(*this, Clauses))
9758     return StmtError();
9759 
9760   setFunctionHasBranchProtectedScope();
9761   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9762                                      Clauses, AStmt, B);
9763 }
9764 
9765 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9766                                               Stmt *AStmt,
9767                                               SourceLocation StartLoc,
9768                                               SourceLocation EndLoc) {
9769   if (!AStmt)
9770     return StmtError();
9771 
9772   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9773   auto BaseStmt = AStmt;
9774   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9775     BaseStmt = CS->getCapturedStmt();
9776   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9777     auto S = C->children();
9778     if (S.begin() == S.end())
9779       return StmtError();
9780     // All associated statements must be '#pragma omp section' except for
9781     // the first one.
9782     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9783       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9784         if (SectionStmt)
9785           Diag(SectionStmt->getBeginLoc(),
9786                diag::err_omp_sections_substmt_not_section);
9787         return StmtError();
9788       }
9789       cast<OMPSectionDirective>(SectionStmt)
9790           ->setHasCancel(DSAStack->isCancelRegion());
9791     }
9792   } else {
9793     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
9794     return StmtError();
9795   }
9796 
9797   setFunctionHasBranchProtectedScope();
9798 
9799   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9800                                       DSAStack->getTaskgroupReductionRef(),
9801                                       DSAStack->isCancelRegion());
9802 }
9803 
9804 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
9805                                              SourceLocation StartLoc,
9806                                              SourceLocation EndLoc) {
9807   if (!AStmt)
9808     return StmtError();
9809 
9810   setFunctionHasBranchProtectedScope();
9811   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
9812 
9813   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
9814                                      DSAStack->isCancelRegion());
9815 }
9816 
9817 static Expr *getDirectCallExpr(Expr *E) {
9818   E = E->IgnoreParenCasts()->IgnoreImplicit();
9819   if (auto *CE = dyn_cast<CallExpr>(E))
9820     if (CE->getDirectCallee())
9821       return E;
9822   return nullptr;
9823 }
9824 
9825 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
9826                                               Stmt *AStmt,
9827                                               SourceLocation StartLoc,
9828                                               SourceLocation EndLoc) {
9829   if (!AStmt)
9830     return StmtError();
9831 
9832   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
9833 
9834   // 5.1 OpenMP
9835   // expression-stmt : an expression statement with one of the following forms:
9836   //   expression = target-call ( [expression-list] );
9837   //   target-call ( [expression-list] );
9838 
9839   SourceLocation TargetCallLoc;
9840 
9841   if (!CurContext->isDependentContext()) {
9842     Expr *TargetCall = nullptr;
9843 
9844     auto *E = dyn_cast<Expr>(S);
9845     if (!E) {
9846       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9847       return StmtError();
9848     }
9849 
9850     E = E->IgnoreParenCasts()->IgnoreImplicit();
9851 
9852     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
9853       if (BO->getOpcode() == BO_Assign)
9854         TargetCall = getDirectCallExpr(BO->getRHS());
9855     } else {
9856       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
9857         if (COCE->getOperator() == OO_Equal)
9858           TargetCall = getDirectCallExpr(COCE->getArg(1));
9859       if (!TargetCall)
9860         TargetCall = getDirectCallExpr(E);
9861     }
9862     if (!TargetCall) {
9863       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9864       return StmtError();
9865     }
9866     TargetCallLoc = TargetCall->getExprLoc();
9867   }
9868 
9869   setFunctionHasBranchProtectedScope();
9870 
9871   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9872                                       TargetCallLoc);
9873 }
9874 
9875 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9876                                             Stmt *AStmt,
9877                                             SourceLocation StartLoc,
9878                                             SourceLocation EndLoc) {
9879   if (!AStmt)
9880     return StmtError();
9881 
9882   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9883 
9884   setFunctionHasBranchProtectedScope();
9885 
9886   // OpenMP [2.7.3, single Construct, Restrictions]
9887   // The copyprivate clause must not be used with the nowait clause.
9888   const OMPClause *Nowait = nullptr;
9889   const OMPClause *Copyprivate = nullptr;
9890   for (const OMPClause *Clause : Clauses) {
9891     if (Clause->getClauseKind() == OMPC_nowait)
9892       Nowait = Clause;
9893     else if (Clause->getClauseKind() == OMPC_copyprivate)
9894       Copyprivate = Clause;
9895     if (Copyprivate && Nowait) {
9896       Diag(Copyprivate->getBeginLoc(),
9897            diag::err_omp_single_copyprivate_with_nowait);
9898       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
9899       return StmtError();
9900     }
9901   }
9902 
9903   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9904 }
9905 
9906 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
9907                                             SourceLocation StartLoc,
9908                                             SourceLocation EndLoc) {
9909   if (!AStmt)
9910     return StmtError();
9911 
9912   setFunctionHasBranchProtectedScope();
9913 
9914   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
9915 }
9916 
9917 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
9918                                             Stmt *AStmt,
9919                                             SourceLocation StartLoc,
9920                                             SourceLocation EndLoc) {
9921   if (!AStmt)
9922     return StmtError();
9923 
9924   setFunctionHasBranchProtectedScope();
9925 
9926   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9927 }
9928 
9929 StmtResult Sema::ActOnOpenMPCriticalDirective(
9930     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
9931     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
9932   if (!AStmt)
9933     return StmtError();
9934 
9935   bool ErrorFound = false;
9936   llvm::APSInt Hint;
9937   SourceLocation HintLoc;
9938   bool DependentHint = false;
9939   for (const OMPClause *C : Clauses) {
9940     if (C->getClauseKind() == OMPC_hint) {
9941       if (!DirName.getName()) {
9942         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
9943         ErrorFound = true;
9944       }
9945       Expr *E = cast<OMPHintClause>(C)->getHint();
9946       if (E->isTypeDependent() || E->isValueDependent() ||
9947           E->isInstantiationDependent()) {
9948         DependentHint = true;
9949       } else {
9950         Hint = E->EvaluateKnownConstInt(Context);
9951         HintLoc = C->getBeginLoc();
9952       }
9953     }
9954   }
9955   if (ErrorFound)
9956     return StmtError();
9957   const auto Pair = DSAStack->getCriticalWithHint(DirName);
9958   if (Pair.first && DirName.getName() && !DependentHint) {
9959     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
9960       Diag(StartLoc, diag::err_omp_critical_with_hint);
9961       if (HintLoc.isValid())
9962         Diag(HintLoc, diag::note_omp_critical_hint_here)
9963             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
9964       else
9965         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
9966       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
9967         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
9968             << 1
9969             << toString(C->getHint()->EvaluateKnownConstInt(Context),
9970                         /*Radix=*/10, /*Signed=*/false);
9971       } else {
9972         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
9973       }
9974     }
9975   }
9976 
9977   setFunctionHasBranchProtectedScope();
9978 
9979   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
9980                                            Clauses, AStmt);
9981   if (!Pair.first && DirName.getName() && !DependentHint)
9982     DSAStack->addCriticalWithHint(Dir, Hint);
9983   return Dir;
9984 }
9985 
9986 StmtResult Sema::ActOnOpenMPParallelForDirective(
9987     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9988     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9989   if (!AStmt)
9990     return StmtError();
9991 
9992   auto *CS = cast<CapturedStmt>(AStmt);
9993   // 1.2.2 OpenMP Language Terminology
9994   // Structured block - An executable statement with a single entry at the
9995   // top and a single exit at the bottom.
9996   // The point of exit cannot be a branch out of the structured block.
9997   // longjmp() and throw() must not violate the entry/exit criteria.
9998   CS->getCapturedDecl()->setNothrow();
9999 
10000   OMPLoopBasedDirective::HelperExprs B;
10001   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10002   // define the nested loops number.
10003   unsigned NestedLoopCount =
10004       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10005                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10006                       VarsWithImplicitDSA, B);
10007   if (NestedLoopCount == 0)
10008     return StmtError();
10009 
10010   assert((CurContext->isDependentContext() || B.builtAll()) &&
10011          "omp parallel for loop exprs were not built");
10012 
10013   if (!CurContext->isDependentContext()) {
10014     // Finalize the clauses that need pre-built expressions for CodeGen.
10015     for (OMPClause *C : Clauses) {
10016       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10017         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10018                                      B.NumIterations, *this, CurScope,
10019                                      DSAStack))
10020           return StmtError();
10021     }
10022   }
10023 
10024   setFunctionHasBranchProtectedScope();
10025   return OMPParallelForDirective::Create(
10026       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10027       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10028 }
10029 
10030 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10031     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10032     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10033   if (!AStmt)
10034     return StmtError();
10035 
10036   auto *CS = cast<CapturedStmt>(AStmt);
10037   // 1.2.2 OpenMP Language Terminology
10038   // Structured block - An executable statement with a single entry at the
10039   // top and a single exit at the bottom.
10040   // The point of exit cannot be a branch out of the structured block.
10041   // longjmp() and throw() must not violate the entry/exit criteria.
10042   CS->getCapturedDecl()->setNothrow();
10043 
10044   OMPLoopBasedDirective::HelperExprs B;
10045   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10046   // define the nested loops number.
10047   unsigned NestedLoopCount =
10048       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10049                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10050                       VarsWithImplicitDSA, B);
10051   if (NestedLoopCount == 0)
10052     return StmtError();
10053 
10054   if (!CurContext->isDependentContext()) {
10055     // Finalize the clauses that need pre-built expressions for CodeGen.
10056     for (OMPClause *C : Clauses) {
10057       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10058         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10059                                      B.NumIterations, *this, CurScope,
10060                                      DSAStack))
10061           return StmtError();
10062     }
10063   }
10064 
10065   if (checkSimdlenSafelenSpecified(*this, Clauses))
10066     return StmtError();
10067 
10068   setFunctionHasBranchProtectedScope();
10069   return OMPParallelForSimdDirective::Create(
10070       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10071 }
10072 
10073 StmtResult
10074 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10075                                          Stmt *AStmt, SourceLocation StartLoc,
10076                                          SourceLocation EndLoc) {
10077   if (!AStmt)
10078     return StmtError();
10079 
10080   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10081   auto *CS = cast<CapturedStmt>(AStmt);
10082   // 1.2.2 OpenMP Language Terminology
10083   // Structured block - An executable statement with a single entry at the
10084   // top and a single exit at the bottom.
10085   // The point of exit cannot be a branch out of the structured block.
10086   // longjmp() and throw() must not violate the entry/exit criteria.
10087   CS->getCapturedDecl()->setNothrow();
10088 
10089   setFunctionHasBranchProtectedScope();
10090 
10091   return OMPParallelMasterDirective::Create(
10092       Context, StartLoc, EndLoc, Clauses, AStmt,
10093       DSAStack->getTaskgroupReductionRef());
10094 }
10095 
10096 StmtResult
10097 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10098                                            Stmt *AStmt, SourceLocation StartLoc,
10099                                            SourceLocation EndLoc) {
10100   if (!AStmt)
10101     return StmtError();
10102 
10103   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10104   auto BaseStmt = AStmt;
10105   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10106     BaseStmt = CS->getCapturedStmt();
10107   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10108     auto S = C->children();
10109     if (S.begin() == S.end())
10110       return StmtError();
10111     // All associated statements must be '#pragma omp section' except for
10112     // the first one.
10113     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10114       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10115         if (SectionStmt)
10116           Diag(SectionStmt->getBeginLoc(),
10117                diag::err_omp_parallel_sections_substmt_not_section);
10118         return StmtError();
10119       }
10120       cast<OMPSectionDirective>(SectionStmt)
10121           ->setHasCancel(DSAStack->isCancelRegion());
10122     }
10123   } else {
10124     Diag(AStmt->getBeginLoc(),
10125          diag::err_omp_parallel_sections_not_compound_stmt);
10126     return StmtError();
10127   }
10128 
10129   setFunctionHasBranchProtectedScope();
10130 
10131   return OMPParallelSectionsDirective::Create(
10132       Context, StartLoc, EndLoc, Clauses, AStmt,
10133       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10134 }
10135 
10136 /// Find and diagnose mutually exclusive clause kinds.
10137 static bool checkMutuallyExclusiveClauses(
10138     Sema &S, ArrayRef<OMPClause *> Clauses,
10139     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10140   const OMPClause *PrevClause = nullptr;
10141   bool ErrorFound = false;
10142   for (const OMPClause *C : Clauses) {
10143     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10144       if (!PrevClause) {
10145         PrevClause = C;
10146       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10147         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10148             << getOpenMPClauseName(C->getClauseKind())
10149             << getOpenMPClauseName(PrevClause->getClauseKind());
10150         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10151             << getOpenMPClauseName(PrevClause->getClauseKind());
10152         ErrorFound = true;
10153       }
10154     }
10155   }
10156   return ErrorFound;
10157 }
10158 
10159 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10160                                           Stmt *AStmt, SourceLocation StartLoc,
10161                                           SourceLocation EndLoc) {
10162   if (!AStmt)
10163     return StmtError();
10164 
10165   // OpenMP 5.0, 2.10.1 task Construct
10166   // If a detach clause appears on the directive, then a mergeable clause cannot
10167   // appear on the same directive.
10168   if (checkMutuallyExclusiveClauses(*this, Clauses,
10169                                     {OMPC_detach, OMPC_mergeable}))
10170     return StmtError();
10171 
10172   auto *CS = cast<CapturedStmt>(AStmt);
10173   // 1.2.2 OpenMP Language Terminology
10174   // Structured block - An executable statement with a single entry at the
10175   // top and a single exit at the bottom.
10176   // The point of exit cannot be a branch out of the structured block.
10177   // longjmp() and throw() must not violate the entry/exit criteria.
10178   CS->getCapturedDecl()->setNothrow();
10179 
10180   setFunctionHasBranchProtectedScope();
10181 
10182   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10183                                   DSAStack->isCancelRegion());
10184 }
10185 
10186 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10187                                                SourceLocation EndLoc) {
10188   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10189 }
10190 
10191 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10192                                              SourceLocation EndLoc) {
10193   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10194 }
10195 
10196 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10197                                               SourceLocation EndLoc) {
10198   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
10199 }
10200 
10201 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10202                                                Stmt *AStmt,
10203                                                SourceLocation StartLoc,
10204                                                SourceLocation EndLoc) {
10205   if (!AStmt)
10206     return StmtError();
10207 
10208   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10209 
10210   setFunctionHasBranchProtectedScope();
10211 
10212   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10213                                        AStmt,
10214                                        DSAStack->getTaskgroupReductionRef());
10215 }
10216 
10217 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10218                                            SourceLocation StartLoc,
10219                                            SourceLocation EndLoc) {
10220   OMPFlushClause *FC = nullptr;
10221   OMPClause *OrderClause = nullptr;
10222   for (OMPClause *C : Clauses) {
10223     if (C->getClauseKind() == OMPC_flush)
10224       FC = cast<OMPFlushClause>(C);
10225     else
10226       OrderClause = C;
10227   }
10228   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10229   SourceLocation MemOrderLoc;
10230   for (const OMPClause *C : Clauses) {
10231     if (C->getClauseKind() == OMPC_acq_rel ||
10232         C->getClauseKind() == OMPC_acquire ||
10233         C->getClauseKind() == OMPC_release) {
10234       if (MemOrderKind != OMPC_unknown) {
10235         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10236             << getOpenMPDirectiveName(OMPD_flush) << 1
10237             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10238         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10239             << getOpenMPClauseName(MemOrderKind);
10240       } else {
10241         MemOrderKind = C->getClauseKind();
10242         MemOrderLoc = C->getBeginLoc();
10243       }
10244     }
10245   }
10246   if (FC && OrderClause) {
10247     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10248         << getOpenMPClauseName(OrderClause->getClauseKind());
10249     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10250         << getOpenMPClauseName(OrderClause->getClauseKind());
10251     return StmtError();
10252   }
10253   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10254 }
10255 
10256 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10257                                             SourceLocation StartLoc,
10258                                             SourceLocation EndLoc) {
10259   if (Clauses.empty()) {
10260     Diag(StartLoc, diag::err_omp_depobj_expected);
10261     return StmtError();
10262   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10263     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10264     return StmtError();
10265   }
10266   // Only depobj expression and another single clause is allowed.
10267   if (Clauses.size() > 2) {
10268     Diag(Clauses[2]->getBeginLoc(),
10269          diag::err_omp_depobj_single_clause_expected);
10270     return StmtError();
10271   } else if (Clauses.size() < 1) {
10272     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10273     return StmtError();
10274   }
10275   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10276 }
10277 
10278 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10279                                           SourceLocation StartLoc,
10280                                           SourceLocation EndLoc) {
10281   // Check that exactly one clause is specified.
10282   if (Clauses.size() != 1) {
10283     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10284          diag::err_omp_scan_single_clause_expected);
10285     return StmtError();
10286   }
10287   // Check that scan directive is used in the scopeof the OpenMP loop body.
10288   if (Scope *S = DSAStack->getCurScope()) {
10289     Scope *ParentS = S->getParent();
10290     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10291         !ParentS->getBreakParent()->isOpenMPLoopScope())
10292       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10293                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10294   }
10295   // Check that only one instance of scan directives is used in the same outer
10296   // region.
10297   if (DSAStack->doesParentHasScanDirective()) {
10298     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10299     Diag(DSAStack->getParentScanDirectiveLoc(),
10300          diag::note_omp_previous_directive)
10301         << "scan";
10302     return StmtError();
10303   }
10304   DSAStack->setParentHasScanDirective(StartLoc);
10305   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10306 }
10307 
10308 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10309                                              Stmt *AStmt,
10310                                              SourceLocation StartLoc,
10311                                              SourceLocation EndLoc) {
10312   const OMPClause *DependFound = nullptr;
10313   const OMPClause *DependSourceClause = nullptr;
10314   const OMPClause *DependSinkClause = nullptr;
10315   bool ErrorFound = false;
10316   const OMPThreadsClause *TC = nullptr;
10317   const OMPSIMDClause *SC = nullptr;
10318   for (const OMPClause *C : Clauses) {
10319     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10320       DependFound = C;
10321       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10322         if (DependSourceClause) {
10323           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10324               << getOpenMPDirectiveName(OMPD_ordered)
10325               << getOpenMPClauseName(OMPC_depend) << 2;
10326           ErrorFound = true;
10327         } else {
10328           DependSourceClause = C;
10329         }
10330         if (DependSinkClause) {
10331           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10332               << 0;
10333           ErrorFound = true;
10334         }
10335       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10336         if (DependSourceClause) {
10337           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10338               << 1;
10339           ErrorFound = true;
10340         }
10341         DependSinkClause = C;
10342       }
10343     } else if (C->getClauseKind() == OMPC_threads) {
10344       TC = cast<OMPThreadsClause>(C);
10345     } else if (C->getClauseKind() == OMPC_simd) {
10346       SC = cast<OMPSIMDClause>(C);
10347     }
10348   }
10349   if (!ErrorFound && !SC &&
10350       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10351     // OpenMP [2.8.1,simd Construct, Restrictions]
10352     // An ordered construct with the simd clause is the only OpenMP construct
10353     // that can appear in the simd region.
10354     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10355         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10356     ErrorFound = true;
10357   } else if (DependFound && (TC || SC)) {
10358     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10359         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10360     ErrorFound = true;
10361   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10362     Diag(DependFound->getBeginLoc(),
10363          diag::err_omp_ordered_directive_without_param);
10364     ErrorFound = true;
10365   } else if (TC || Clauses.empty()) {
10366     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10367       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10368       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10369           << (TC != nullptr);
10370       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10371       ErrorFound = true;
10372     }
10373   }
10374   if ((!AStmt && !DependFound) || ErrorFound)
10375     return StmtError();
10376 
10377   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10378   // During execution of an iteration of a worksharing-loop or a loop nest
10379   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10380   // must not execute more than one ordered region corresponding to an ordered
10381   // construct without a depend clause.
10382   if (!DependFound) {
10383     if (DSAStack->doesParentHasOrderedDirective()) {
10384       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10385       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10386            diag::note_omp_previous_directive)
10387           << "ordered";
10388       return StmtError();
10389     }
10390     DSAStack->setParentHasOrderedDirective(StartLoc);
10391   }
10392 
10393   if (AStmt) {
10394     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10395 
10396     setFunctionHasBranchProtectedScope();
10397   }
10398 
10399   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10400 }
10401 
10402 namespace {
10403 /// Helper class for checking expression in 'omp atomic [update]'
10404 /// construct.
10405 class OpenMPAtomicUpdateChecker {
10406   /// Error results for atomic update expressions.
10407   enum ExprAnalysisErrorCode {
10408     /// A statement is not an expression statement.
10409     NotAnExpression,
10410     /// Expression is not builtin binary or unary operation.
10411     NotABinaryOrUnaryExpression,
10412     /// Unary operation is not post-/pre- increment/decrement operation.
10413     NotAnUnaryIncDecExpression,
10414     /// An expression is not of scalar type.
10415     NotAScalarType,
10416     /// A binary operation is not an assignment operation.
10417     NotAnAssignmentOp,
10418     /// RHS part of the binary operation is not a binary expression.
10419     NotABinaryExpression,
10420     /// RHS part is not additive/multiplicative/shift/biwise binary
10421     /// expression.
10422     NotABinaryOperator,
10423     /// RHS binary operation does not have reference to the updated LHS
10424     /// part.
10425     NotAnUpdateExpression,
10426     /// No errors is found.
10427     NoError
10428   };
10429   /// Reference to Sema.
10430   Sema &SemaRef;
10431   /// A location for note diagnostics (when error is found).
10432   SourceLocation NoteLoc;
10433   /// 'x' lvalue part of the source atomic expression.
10434   Expr *X;
10435   /// 'expr' rvalue part of the source atomic expression.
10436   Expr *E;
10437   /// Helper expression of the form
10438   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10439   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10440   Expr *UpdateExpr;
10441   /// Is 'x' a LHS in a RHS part of full update expression. It is
10442   /// important for non-associative operations.
10443   bool IsXLHSInRHSPart;
10444   BinaryOperatorKind Op;
10445   SourceLocation OpLoc;
10446   /// true if the source expression is a postfix unary operation, false
10447   /// if it is a prefix unary operation.
10448   bool IsPostfixUpdate;
10449 
10450 public:
10451   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10452       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10453         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10454   /// Check specified statement that it is suitable for 'atomic update'
10455   /// constructs and extract 'x', 'expr' and Operation from the original
10456   /// expression. If DiagId and NoteId == 0, then only check is performed
10457   /// without error notification.
10458   /// \param DiagId Diagnostic which should be emitted if error is found.
10459   /// \param NoteId Diagnostic note for the main error message.
10460   /// \return true if statement is not an update expression, false otherwise.
10461   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10462   /// Return the 'x' lvalue part of the source atomic expression.
10463   Expr *getX() const { return X; }
10464   /// Return the 'expr' rvalue part of the source atomic expression.
10465   Expr *getExpr() const { return E; }
10466   /// Return the update expression used in calculation of the updated
10467   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10468   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10469   Expr *getUpdateExpr() const { return UpdateExpr; }
10470   /// Return true if 'x' is LHS in RHS part of full update expression,
10471   /// false otherwise.
10472   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10473 
10474   /// true if the source expression is a postfix unary operation, false
10475   /// if it is a prefix unary operation.
10476   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10477 
10478 private:
10479   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10480                             unsigned NoteId = 0);
10481 };
10482 } // namespace
10483 
10484 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10485     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10486   ExprAnalysisErrorCode ErrorFound = NoError;
10487   SourceLocation ErrorLoc, NoteLoc;
10488   SourceRange ErrorRange, NoteRange;
10489   // Allowed constructs are:
10490   //  x = x binop expr;
10491   //  x = expr binop x;
10492   if (AtomicBinOp->getOpcode() == BO_Assign) {
10493     X = AtomicBinOp->getLHS();
10494     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10495             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10496       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10497           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10498           AtomicInnerBinOp->isBitwiseOp()) {
10499         Op = AtomicInnerBinOp->getOpcode();
10500         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10501         Expr *LHS = AtomicInnerBinOp->getLHS();
10502         Expr *RHS = AtomicInnerBinOp->getRHS();
10503         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10504         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10505                                           /*Canonical=*/true);
10506         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10507                                             /*Canonical=*/true);
10508         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10509                                             /*Canonical=*/true);
10510         if (XId == LHSId) {
10511           E = RHS;
10512           IsXLHSInRHSPart = true;
10513         } else if (XId == RHSId) {
10514           E = LHS;
10515           IsXLHSInRHSPart = false;
10516         } else {
10517           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10518           ErrorRange = AtomicInnerBinOp->getSourceRange();
10519           NoteLoc = X->getExprLoc();
10520           NoteRange = X->getSourceRange();
10521           ErrorFound = NotAnUpdateExpression;
10522         }
10523       } else {
10524         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10525         ErrorRange = AtomicInnerBinOp->getSourceRange();
10526         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10527         NoteRange = SourceRange(NoteLoc, NoteLoc);
10528         ErrorFound = NotABinaryOperator;
10529       }
10530     } else {
10531       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10532       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10533       ErrorFound = NotABinaryExpression;
10534     }
10535   } else {
10536     ErrorLoc = AtomicBinOp->getExprLoc();
10537     ErrorRange = AtomicBinOp->getSourceRange();
10538     NoteLoc = AtomicBinOp->getOperatorLoc();
10539     NoteRange = SourceRange(NoteLoc, NoteLoc);
10540     ErrorFound = NotAnAssignmentOp;
10541   }
10542   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10543     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10544     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10545     return true;
10546   }
10547   if (SemaRef.CurContext->isDependentContext())
10548     E = X = UpdateExpr = nullptr;
10549   return ErrorFound != NoError;
10550 }
10551 
10552 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10553                                                unsigned NoteId) {
10554   ExprAnalysisErrorCode ErrorFound = NoError;
10555   SourceLocation ErrorLoc, NoteLoc;
10556   SourceRange ErrorRange, NoteRange;
10557   // Allowed constructs are:
10558   //  x++;
10559   //  x--;
10560   //  ++x;
10561   //  --x;
10562   //  x binop= expr;
10563   //  x = x binop expr;
10564   //  x = expr binop x;
10565   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10566     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10567     if (AtomicBody->getType()->isScalarType() ||
10568         AtomicBody->isInstantiationDependent()) {
10569       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10570               AtomicBody->IgnoreParenImpCasts())) {
10571         // Check for Compound Assignment Operation
10572         Op = BinaryOperator::getOpForCompoundAssignment(
10573             AtomicCompAssignOp->getOpcode());
10574         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10575         E = AtomicCompAssignOp->getRHS();
10576         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10577         IsXLHSInRHSPart = true;
10578       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10579                      AtomicBody->IgnoreParenImpCasts())) {
10580         // Check for Binary Operation
10581         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10582           return true;
10583       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10584                      AtomicBody->IgnoreParenImpCasts())) {
10585         // Check for Unary Operation
10586         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10587           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10588           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10589           OpLoc = AtomicUnaryOp->getOperatorLoc();
10590           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10591           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10592           IsXLHSInRHSPart = true;
10593         } else {
10594           ErrorFound = NotAnUnaryIncDecExpression;
10595           ErrorLoc = AtomicUnaryOp->getExprLoc();
10596           ErrorRange = AtomicUnaryOp->getSourceRange();
10597           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10598           NoteRange = SourceRange(NoteLoc, NoteLoc);
10599         }
10600       } else if (!AtomicBody->isInstantiationDependent()) {
10601         ErrorFound = NotABinaryOrUnaryExpression;
10602         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10603         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10604       }
10605     } else {
10606       ErrorFound = NotAScalarType;
10607       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10608       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10609     }
10610   } else {
10611     ErrorFound = NotAnExpression;
10612     NoteLoc = ErrorLoc = S->getBeginLoc();
10613     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10614   }
10615   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10616     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10617     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10618     return true;
10619   }
10620   if (SemaRef.CurContext->isDependentContext())
10621     E = X = UpdateExpr = nullptr;
10622   if (ErrorFound == NoError && E && X) {
10623     // Build an update expression of form 'OpaqueValueExpr(x) binop
10624     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10625     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10626     auto *OVEX = new (SemaRef.getASTContext())
10627         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
10628     auto *OVEExpr = new (SemaRef.getASTContext())
10629         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
10630     ExprResult Update =
10631         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10632                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10633     if (Update.isInvalid())
10634       return true;
10635     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10636                                                Sema::AA_Casting);
10637     if (Update.isInvalid())
10638       return true;
10639     UpdateExpr = Update.get();
10640   }
10641   return ErrorFound != NoError;
10642 }
10643 
10644 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10645                                             Stmt *AStmt,
10646                                             SourceLocation StartLoc,
10647                                             SourceLocation EndLoc) {
10648   // Register location of the first atomic directive.
10649   DSAStack->addAtomicDirectiveLoc(StartLoc);
10650   if (!AStmt)
10651     return StmtError();
10652 
10653   // 1.2.2 OpenMP Language Terminology
10654   // Structured block - An executable statement with a single entry at the
10655   // top and a single exit at the bottom.
10656   // The point of exit cannot be a branch out of the structured block.
10657   // longjmp() and throw() must not violate the entry/exit criteria.
10658   OpenMPClauseKind AtomicKind = OMPC_unknown;
10659   SourceLocation AtomicKindLoc;
10660   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10661   SourceLocation MemOrderLoc;
10662   for (const OMPClause *C : Clauses) {
10663     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
10664         C->getClauseKind() == OMPC_update ||
10665         C->getClauseKind() == OMPC_capture) {
10666       if (AtomicKind != OMPC_unknown) {
10667         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10668             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10669         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10670             << getOpenMPClauseName(AtomicKind);
10671       } else {
10672         AtomicKind = C->getClauseKind();
10673         AtomicKindLoc = C->getBeginLoc();
10674       }
10675     }
10676     if (C->getClauseKind() == OMPC_seq_cst ||
10677         C->getClauseKind() == OMPC_acq_rel ||
10678         C->getClauseKind() == OMPC_acquire ||
10679         C->getClauseKind() == OMPC_release ||
10680         C->getClauseKind() == OMPC_relaxed) {
10681       if (MemOrderKind != OMPC_unknown) {
10682         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10683             << getOpenMPDirectiveName(OMPD_atomic) << 0
10684             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10685         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10686             << getOpenMPClauseName(MemOrderKind);
10687       } else {
10688         MemOrderKind = C->getClauseKind();
10689         MemOrderLoc = C->getBeginLoc();
10690       }
10691     }
10692   }
10693   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10694   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10695   // release.
10696   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10697   // acquire.
10698   // If atomic-clause is update or not present then memory-order-clause must not
10699   // be acq_rel or acquire.
10700   if ((AtomicKind == OMPC_read &&
10701        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10702       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10703         AtomicKind == OMPC_unknown) &&
10704        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10705     SourceLocation Loc = AtomicKindLoc;
10706     if (AtomicKind == OMPC_unknown)
10707       Loc = StartLoc;
10708     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10709         << getOpenMPClauseName(AtomicKind)
10710         << (AtomicKind == OMPC_unknown ? 1 : 0)
10711         << getOpenMPClauseName(MemOrderKind);
10712     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10713         << getOpenMPClauseName(MemOrderKind);
10714   }
10715 
10716   Stmt *Body = AStmt;
10717   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10718     Body = EWC->getSubExpr();
10719 
10720   Expr *X = nullptr;
10721   Expr *V = nullptr;
10722   Expr *E = nullptr;
10723   Expr *UE = nullptr;
10724   bool IsXLHSInRHSPart = false;
10725   bool IsPostfixUpdate = false;
10726   // OpenMP [2.12.6, atomic Construct]
10727   // In the next expressions:
10728   // * x and v (as applicable) are both l-value expressions with scalar type.
10729   // * During the execution of an atomic region, multiple syntactic
10730   // occurrences of x must designate the same storage location.
10731   // * Neither of v and expr (as applicable) may access the storage location
10732   // designated by x.
10733   // * Neither of x and expr (as applicable) may access the storage location
10734   // designated by v.
10735   // * expr is an expression with scalar type.
10736   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
10737   // * binop, binop=, ++, and -- are not overloaded operators.
10738   // * The expression x binop expr must be numerically equivalent to x binop
10739   // (expr). This requirement is satisfied if the operators in expr have
10740   // precedence greater than binop, or by using parentheses around expr or
10741   // subexpressions of expr.
10742   // * The expression expr binop x must be numerically equivalent to (expr)
10743   // binop x. This requirement is satisfied if the operators in expr have
10744   // precedence equal to or greater than binop, or by using parentheses around
10745   // expr or subexpressions of expr.
10746   // * For forms that allow multiple occurrences of x, the number of times
10747   // that x is evaluated is unspecified.
10748   if (AtomicKind == OMPC_read) {
10749     enum {
10750       NotAnExpression,
10751       NotAnAssignmentOp,
10752       NotAScalarType,
10753       NotAnLValue,
10754       NoError
10755     } ErrorFound = NoError;
10756     SourceLocation ErrorLoc, NoteLoc;
10757     SourceRange ErrorRange, NoteRange;
10758     // If clause is read:
10759     //  v = x;
10760     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10761       const auto *AtomicBinOp =
10762           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10763       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10764         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10765         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
10766         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10767             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
10768           if (!X->isLValue() || !V->isLValue()) {
10769             const Expr *NotLValueExpr = X->isLValue() ? V : X;
10770             ErrorFound = NotAnLValue;
10771             ErrorLoc = AtomicBinOp->getExprLoc();
10772             ErrorRange = AtomicBinOp->getSourceRange();
10773             NoteLoc = NotLValueExpr->getExprLoc();
10774             NoteRange = NotLValueExpr->getSourceRange();
10775           }
10776         } else if (!X->isInstantiationDependent() ||
10777                    !V->isInstantiationDependent()) {
10778           const Expr *NotScalarExpr =
10779               (X->isInstantiationDependent() || X->getType()->isScalarType())
10780                   ? V
10781                   : X;
10782           ErrorFound = NotAScalarType;
10783           ErrorLoc = AtomicBinOp->getExprLoc();
10784           ErrorRange = AtomicBinOp->getSourceRange();
10785           NoteLoc = NotScalarExpr->getExprLoc();
10786           NoteRange = NotScalarExpr->getSourceRange();
10787         }
10788       } else if (!AtomicBody->isInstantiationDependent()) {
10789         ErrorFound = NotAnAssignmentOp;
10790         ErrorLoc = AtomicBody->getExprLoc();
10791         ErrorRange = AtomicBody->getSourceRange();
10792         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10793                               : AtomicBody->getExprLoc();
10794         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10795                                 : AtomicBody->getSourceRange();
10796       }
10797     } else {
10798       ErrorFound = NotAnExpression;
10799       NoteLoc = ErrorLoc = Body->getBeginLoc();
10800       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10801     }
10802     if (ErrorFound != NoError) {
10803       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
10804           << ErrorRange;
10805       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10806                                                       << NoteRange;
10807       return StmtError();
10808     }
10809     if (CurContext->isDependentContext())
10810       V = X = nullptr;
10811   } else if (AtomicKind == OMPC_write) {
10812     enum {
10813       NotAnExpression,
10814       NotAnAssignmentOp,
10815       NotAScalarType,
10816       NotAnLValue,
10817       NoError
10818     } ErrorFound = NoError;
10819     SourceLocation ErrorLoc, NoteLoc;
10820     SourceRange ErrorRange, NoteRange;
10821     // If clause is write:
10822     //  x = expr;
10823     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10824       const auto *AtomicBinOp =
10825           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10826       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10827         X = AtomicBinOp->getLHS();
10828         E = AtomicBinOp->getRHS();
10829         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10830             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
10831           if (!X->isLValue()) {
10832             ErrorFound = NotAnLValue;
10833             ErrorLoc = AtomicBinOp->getExprLoc();
10834             ErrorRange = AtomicBinOp->getSourceRange();
10835             NoteLoc = X->getExprLoc();
10836             NoteRange = X->getSourceRange();
10837           }
10838         } else if (!X->isInstantiationDependent() ||
10839                    !E->isInstantiationDependent()) {
10840           const Expr *NotScalarExpr =
10841               (X->isInstantiationDependent() || X->getType()->isScalarType())
10842                   ? E
10843                   : X;
10844           ErrorFound = NotAScalarType;
10845           ErrorLoc = AtomicBinOp->getExprLoc();
10846           ErrorRange = AtomicBinOp->getSourceRange();
10847           NoteLoc = NotScalarExpr->getExprLoc();
10848           NoteRange = NotScalarExpr->getSourceRange();
10849         }
10850       } else if (!AtomicBody->isInstantiationDependent()) {
10851         ErrorFound = NotAnAssignmentOp;
10852         ErrorLoc = AtomicBody->getExprLoc();
10853         ErrorRange = AtomicBody->getSourceRange();
10854         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10855                               : AtomicBody->getExprLoc();
10856         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10857                                 : AtomicBody->getSourceRange();
10858       }
10859     } else {
10860       ErrorFound = NotAnExpression;
10861       NoteLoc = ErrorLoc = Body->getBeginLoc();
10862       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10863     }
10864     if (ErrorFound != NoError) {
10865       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
10866           << ErrorRange;
10867       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10868                                                       << NoteRange;
10869       return StmtError();
10870     }
10871     if (CurContext->isDependentContext())
10872       E = X = nullptr;
10873   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
10874     // If clause is update:
10875     //  x++;
10876     //  x--;
10877     //  ++x;
10878     //  --x;
10879     //  x binop= expr;
10880     //  x = x binop expr;
10881     //  x = expr binop x;
10882     OpenMPAtomicUpdateChecker Checker(*this);
10883     if (Checker.checkStatement(
10884             Body, (AtomicKind == OMPC_update)
10885                       ? diag::err_omp_atomic_update_not_expression_statement
10886                       : diag::err_omp_atomic_not_expression_statement,
10887             diag::note_omp_atomic_update))
10888       return StmtError();
10889     if (!CurContext->isDependentContext()) {
10890       E = Checker.getExpr();
10891       X = Checker.getX();
10892       UE = Checker.getUpdateExpr();
10893       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10894     }
10895   } else if (AtomicKind == OMPC_capture) {
10896     enum {
10897       NotAnAssignmentOp,
10898       NotACompoundStatement,
10899       NotTwoSubstatements,
10900       NotASpecificExpression,
10901       NoError
10902     } ErrorFound = NoError;
10903     SourceLocation ErrorLoc, NoteLoc;
10904     SourceRange ErrorRange, NoteRange;
10905     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10906       // If clause is a capture:
10907       //  v = x++;
10908       //  v = x--;
10909       //  v = ++x;
10910       //  v = --x;
10911       //  v = x binop= expr;
10912       //  v = x = x binop expr;
10913       //  v = x = expr binop x;
10914       const auto *AtomicBinOp =
10915           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10916       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10917         V = AtomicBinOp->getLHS();
10918         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10919         OpenMPAtomicUpdateChecker Checker(*this);
10920         if (Checker.checkStatement(
10921                 Body, diag::err_omp_atomic_capture_not_expression_statement,
10922                 diag::note_omp_atomic_update))
10923           return StmtError();
10924         E = Checker.getExpr();
10925         X = Checker.getX();
10926         UE = Checker.getUpdateExpr();
10927         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10928         IsPostfixUpdate = Checker.isPostfixUpdate();
10929       } else if (!AtomicBody->isInstantiationDependent()) {
10930         ErrorLoc = AtomicBody->getExprLoc();
10931         ErrorRange = AtomicBody->getSourceRange();
10932         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10933                               : AtomicBody->getExprLoc();
10934         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10935                                 : AtomicBody->getSourceRange();
10936         ErrorFound = NotAnAssignmentOp;
10937       }
10938       if (ErrorFound != NoError) {
10939         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
10940             << ErrorRange;
10941         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10942         return StmtError();
10943       }
10944       if (CurContext->isDependentContext())
10945         UE = V = E = X = nullptr;
10946     } else {
10947       // If clause is a capture:
10948       //  { v = x; x = expr; }
10949       //  { v = x; x++; }
10950       //  { v = x; x--; }
10951       //  { v = x; ++x; }
10952       //  { v = x; --x; }
10953       //  { v = x; x binop= expr; }
10954       //  { v = x; x = x binop expr; }
10955       //  { v = x; x = expr binop x; }
10956       //  { x++; v = x; }
10957       //  { x--; v = x; }
10958       //  { ++x; v = x; }
10959       //  { --x; v = x; }
10960       //  { x binop= expr; v = x; }
10961       //  { x = x binop expr; v = x; }
10962       //  { x = expr binop x; v = x; }
10963       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
10964         // Check that this is { expr1; expr2; }
10965         if (CS->size() == 2) {
10966           Stmt *First = CS->body_front();
10967           Stmt *Second = CS->body_back();
10968           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
10969             First = EWC->getSubExpr()->IgnoreParenImpCasts();
10970           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
10971             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
10972           // Need to find what subexpression is 'v' and what is 'x'.
10973           OpenMPAtomicUpdateChecker Checker(*this);
10974           bool IsUpdateExprFound = !Checker.checkStatement(Second);
10975           BinaryOperator *BinOp = nullptr;
10976           if (IsUpdateExprFound) {
10977             BinOp = dyn_cast<BinaryOperator>(First);
10978             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10979           }
10980           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10981             //  { v = x; x++; }
10982             //  { v = x; x--; }
10983             //  { v = x; ++x; }
10984             //  { v = x; --x; }
10985             //  { v = x; x binop= expr; }
10986             //  { v = x; x = x binop expr; }
10987             //  { v = x; x = expr binop x; }
10988             // Check that the first expression has form v = x.
10989             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10990             llvm::FoldingSetNodeID XId, PossibleXId;
10991             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10992             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10993             IsUpdateExprFound = XId == PossibleXId;
10994             if (IsUpdateExprFound) {
10995               V = BinOp->getLHS();
10996               X = Checker.getX();
10997               E = Checker.getExpr();
10998               UE = Checker.getUpdateExpr();
10999               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11000               IsPostfixUpdate = true;
11001             }
11002           }
11003           if (!IsUpdateExprFound) {
11004             IsUpdateExprFound = !Checker.checkStatement(First);
11005             BinOp = nullptr;
11006             if (IsUpdateExprFound) {
11007               BinOp = dyn_cast<BinaryOperator>(Second);
11008               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11009             }
11010             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11011               //  { x++; v = x; }
11012               //  { x--; v = x; }
11013               //  { ++x; v = x; }
11014               //  { --x; v = x; }
11015               //  { x binop= expr; v = x; }
11016               //  { x = x binop expr; v = x; }
11017               //  { x = expr binop x; v = x; }
11018               // Check that the second expression has form v = x.
11019               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11020               llvm::FoldingSetNodeID XId, PossibleXId;
11021               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11022               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11023               IsUpdateExprFound = XId == PossibleXId;
11024               if (IsUpdateExprFound) {
11025                 V = BinOp->getLHS();
11026                 X = Checker.getX();
11027                 E = Checker.getExpr();
11028                 UE = Checker.getUpdateExpr();
11029                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11030                 IsPostfixUpdate = false;
11031               }
11032             }
11033           }
11034           if (!IsUpdateExprFound) {
11035             //  { v = x; x = expr; }
11036             auto *FirstExpr = dyn_cast<Expr>(First);
11037             auto *SecondExpr = dyn_cast<Expr>(Second);
11038             if (!FirstExpr || !SecondExpr ||
11039                 !(FirstExpr->isInstantiationDependent() ||
11040                   SecondExpr->isInstantiationDependent())) {
11041               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11042               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11043                 ErrorFound = NotAnAssignmentOp;
11044                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11045                                                 : First->getBeginLoc();
11046                 NoteRange = ErrorRange = FirstBinOp
11047                                              ? FirstBinOp->getSourceRange()
11048                                              : SourceRange(ErrorLoc, ErrorLoc);
11049               } else {
11050                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11051                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11052                   ErrorFound = NotAnAssignmentOp;
11053                   NoteLoc = ErrorLoc = SecondBinOp
11054                                            ? SecondBinOp->getOperatorLoc()
11055                                            : Second->getBeginLoc();
11056                   NoteRange = ErrorRange =
11057                       SecondBinOp ? SecondBinOp->getSourceRange()
11058                                   : SourceRange(ErrorLoc, ErrorLoc);
11059                 } else {
11060                   Expr *PossibleXRHSInFirst =
11061                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11062                   Expr *PossibleXLHSInSecond =
11063                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11064                   llvm::FoldingSetNodeID X1Id, X2Id;
11065                   PossibleXRHSInFirst->Profile(X1Id, Context,
11066                                                /*Canonical=*/true);
11067                   PossibleXLHSInSecond->Profile(X2Id, Context,
11068                                                 /*Canonical=*/true);
11069                   IsUpdateExprFound = X1Id == X2Id;
11070                   if (IsUpdateExprFound) {
11071                     V = FirstBinOp->getLHS();
11072                     X = SecondBinOp->getLHS();
11073                     E = SecondBinOp->getRHS();
11074                     UE = nullptr;
11075                     IsXLHSInRHSPart = false;
11076                     IsPostfixUpdate = true;
11077                   } else {
11078                     ErrorFound = NotASpecificExpression;
11079                     ErrorLoc = FirstBinOp->getExprLoc();
11080                     ErrorRange = FirstBinOp->getSourceRange();
11081                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11082                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11083                   }
11084                 }
11085               }
11086             }
11087           }
11088         } else {
11089           NoteLoc = ErrorLoc = Body->getBeginLoc();
11090           NoteRange = ErrorRange =
11091               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11092           ErrorFound = NotTwoSubstatements;
11093         }
11094       } else {
11095         NoteLoc = ErrorLoc = Body->getBeginLoc();
11096         NoteRange = ErrorRange =
11097             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11098         ErrorFound = NotACompoundStatement;
11099       }
11100       if (ErrorFound != NoError) {
11101         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11102             << ErrorRange;
11103         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11104         return StmtError();
11105       }
11106       if (CurContext->isDependentContext())
11107         UE = V = E = X = nullptr;
11108     }
11109   }
11110 
11111   setFunctionHasBranchProtectedScope();
11112 
11113   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11114                                     X, V, E, UE, IsXLHSInRHSPart,
11115                                     IsPostfixUpdate);
11116 }
11117 
11118 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11119                                             Stmt *AStmt,
11120                                             SourceLocation StartLoc,
11121                                             SourceLocation EndLoc) {
11122   if (!AStmt)
11123     return StmtError();
11124 
11125   auto *CS = cast<CapturedStmt>(AStmt);
11126   // 1.2.2 OpenMP Language Terminology
11127   // Structured block - An executable statement with a single entry at the
11128   // top and a single exit at the bottom.
11129   // The point of exit cannot be a branch out of the structured block.
11130   // longjmp() and throw() must not violate the entry/exit criteria.
11131   CS->getCapturedDecl()->setNothrow();
11132   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11133        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11134     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11135     // 1.2.2 OpenMP Language Terminology
11136     // Structured block - An executable statement with a single entry at the
11137     // top and a single exit at the bottom.
11138     // The point of exit cannot be a branch out of the structured block.
11139     // longjmp() and throw() must not violate the entry/exit criteria.
11140     CS->getCapturedDecl()->setNothrow();
11141   }
11142 
11143   // OpenMP [2.16, Nesting of Regions]
11144   // If specified, a teams construct must be contained within a target
11145   // construct. That target construct must contain no statements or directives
11146   // outside of the teams construct.
11147   if (DSAStack->hasInnerTeamsRegion()) {
11148     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11149     bool OMPTeamsFound = true;
11150     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11151       auto I = CS->body_begin();
11152       while (I != CS->body_end()) {
11153         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11154         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11155             OMPTeamsFound) {
11156 
11157           OMPTeamsFound = false;
11158           break;
11159         }
11160         ++I;
11161       }
11162       assert(I != CS->body_end() && "Not found statement");
11163       S = *I;
11164     } else {
11165       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11166       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11167     }
11168     if (!OMPTeamsFound) {
11169       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11170       Diag(DSAStack->getInnerTeamsRegionLoc(),
11171            diag::note_omp_nested_teams_construct_here);
11172       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11173           << isa<OMPExecutableDirective>(S);
11174       return StmtError();
11175     }
11176   }
11177 
11178   setFunctionHasBranchProtectedScope();
11179 
11180   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11181 }
11182 
11183 StmtResult
11184 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11185                                          Stmt *AStmt, SourceLocation StartLoc,
11186                                          SourceLocation EndLoc) {
11187   if (!AStmt)
11188     return StmtError();
11189 
11190   auto *CS = cast<CapturedStmt>(AStmt);
11191   // 1.2.2 OpenMP Language Terminology
11192   // Structured block - An executable statement with a single entry at the
11193   // top and a single exit at the bottom.
11194   // The point of exit cannot be a branch out of the structured block.
11195   // longjmp() and throw() must not violate the entry/exit criteria.
11196   CS->getCapturedDecl()->setNothrow();
11197   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11198        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11199     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11200     // 1.2.2 OpenMP Language Terminology
11201     // Structured block - An executable statement with a single entry at the
11202     // top and a single exit at the bottom.
11203     // The point of exit cannot be a branch out of the structured block.
11204     // longjmp() and throw() must not violate the entry/exit criteria.
11205     CS->getCapturedDecl()->setNothrow();
11206   }
11207 
11208   setFunctionHasBranchProtectedScope();
11209 
11210   return OMPTargetParallelDirective::Create(
11211       Context, StartLoc, EndLoc, Clauses, AStmt,
11212       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11213 }
11214 
11215 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11216     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11217     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11218   if (!AStmt)
11219     return StmtError();
11220 
11221   auto *CS = cast<CapturedStmt>(AStmt);
11222   // 1.2.2 OpenMP Language Terminology
11223   // Structured block - An executable statement with a single entry at the
11224   // top and a single exit at the bottom.
11225   // The point of exit cannot be a branch out of the structured block.
11226   // longjmp() and throw() must not violate the entry/exit criteria.
11227   CS->getCapturedDecl()->setNothrow();
11228   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11229        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11230     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11231     // 1.2.2 OpenMP Language Terminology
11232     // Structured block - An executable statement with a single entry at the
11233     // top and a single exit at the bottom.
11234     // The point of exit cannot be a branch out of the structured block.
11235     // longjmp() and throw() must not violate the entry/exit criteria.
11236     CS->getCapturedDecl()->setNothrow();
11237   }
11238 
11239   OMPLoopBasedDirective::HelperExprs B;
11240   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11241   // define the nested loops number.
11242   unsigned NestedLoopCount =
11243       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11244                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11245                       VarsWithImplicitDSA, B);
11246   if (NestedLoopCount == 0)
11247     return StmtError();
11248 
11249   assert((CurContext->isDependentContext() || B.builtAll()) &&
11250          "omp target parallel for loop exprs were not built");
11251 
11252   if (!CurContext->isDependentContext()) {
11253     // Finalize the clauses that need pre-built expressions for CodeGen.
11254     for (OMPClause *C : Clauses) {
11255       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11256         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11257                                      B.NumIterations, *this, CurScope,
11258                                      DSAStack))
11259           return StmtError();
11260     }
11261   }
11262 
11263   setFunctionHasBranchProtectedScope();
11264   return OMPTargetParallelForDirective::Create(
11265       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11266       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11267 }
11268 
11269 /// Check for existence of a map clause in the list of clauses.
11270 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11271                        const OpenMPClauseKind K) {
11272   return llvm::any_of(
11273       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11274 }
11275 
11276 template <typename... Params>
11277 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11278                        const Params... ClauseTypes) {
11279   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11280 }
11281 
11282 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11283                                                 Stmt *AStmt,
11284                                                 SourceLocation StartLoc,
11285                                                 SourceLocation EndLoc) {
11286   if (!AStmt)
11287     return StmtError();
11288 
11289   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11290 
11291   // OpenMP [2.12.2, target data Construct, Restrictions]
11292   // At least one map, use_device_addr or use_device_ptr clause must appear on
11293   // the directive.
11294   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11295       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11296     StringRef Expected;
11297     if (LangOpts.OpenMP < 50)
11298       Expected = "'map' or 'use_device_ptr'";
11299     else
11300       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11301     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11302         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11303     return StmtError();
11304   }
11305 
11306   setFunctionHasBranchProtectedScope();
11307 
11308   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11309                                         AStmt);
11310 }
11311 
11312 StmtResult
11313 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11314                                           SourceLocation StartLoc,
11315                                           SourceLocation EndLoc, Stmt *AStmt) {
11316   if (!AStmt)
11317     return StmtError();
11318 
11319   auto *CS = cast<CapturedStmt>(AStmt);
11320   // 1.2.2 OpenMP Language Terminology
11321   // Structured block - An executable statement with a single entry at the
11322   // top and a single exit at the bottom.
11323   // The point of exit cannot be a branch out of the structured block.
11324   // longjmp() and throw() must not violate the entry/exit criteria.
11325   CS->getCapturedDecl()->setNothrow();
11326   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11327        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11328     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11329     // 1.2.2 OpenMP Language Terminology
11330     // Structured block - An executable statement with a single entry at the
11331     // top and a single exit at the bottom.
11332     // The point of exit cannot be a branch out of the structured block.
11333     // longjmp() and throw() must not violate the entry/exit criteria.
11334     CS->getCapturedDecl()->setNothrow();
11335   }
11336 
11337   // OpenMP [2.10.2, Restrictions, p. 99]
11338   // At least one map clause must appear on the directive.
11339   if (!hasClauses(Clauses, OMPC_map)) {
11340     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11341         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11342     return StmtError();
11343   }
11344 
11345   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11346                                              AStmt);
11347 }
11348 
11349 StmtResult
11350 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11351                                          SourceLocation StartLoc,
11352                                          SourceLocation EndLoc, Stmt *AStmt) {
11353   if (!AStmt)
11354     return StmtError();
11355 
11356   auto *CS = cast<CapturedStmt>(AStmt);
11357   // 1.2.2 OpenMP Language Terminology
11358   // Structured block - An executable statement with a single entry at the
11359   // top and a single exit at the bottom.
11360   // The point of exit cannot be a branch out of the structured block.
11361   // longjmp() and throw() must not violate the entry/exit criteria.
11362   CS->getCapturedDecl()->setNothrow();
11363   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11364        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11365     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11366     // 1.2.2 OpenMP Language Terminology
11367     // Structured block - An executable statement with a single entry at the
11368     // top and a single exit at the bottom.
11369     // The point of exit cannot be a branch out of the structured block.
11370     // longjmp() and throw() must not violate the entry/exit criteria.
11371     CS->getCapturedDecl()->setNothrow();
11372   }
11373 
11374   // OpenMP [2.10.3, Restrictions, p. 102]
11375   // At least one map clause must appear on the directive.
11376   if (!hasClauses(Clauses, OMPC_map)) {
11377     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11378         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11379     return StmtError();
11380   }
11381 
11382   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11383                                             AStmt);
11384 }
11385 
11386 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11387                                                   SourceLocation StartLoc,
11388                                                   SourceLocation EndLoc,
11389                                                   Stmt *AStmt) {
11390   if (!AStmt)
11391     return StmtError();
11392 
11393   auto *CS = cast<CapturedStmt>(AStmt);
11394   // 1.2.2 OpenMP Language Terminology
11395   // Structured block - An executable statement with a single entry at the
11396   // top and a single exit at the bottom.
11397   // The point of exit cannot be a branch out of the structured block.
11398   // longjmp() and throw() must not violate the entry/exit criteria.
11399   CS->getCapturedDecl()->setNothrow();
11400   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11401        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11402     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11403     // 1.2.2 OpenMP Language Terminology
11404     // Structured block - An executable statement with a single entry at the
11405     // top and a single exit at the bottom.
11406     // The point of exit cannot be a branch out of the structured block.
11407     // longjmp() and throw() must not violate the entry/exit criteria.
11408     CS->getCapturedDecl()->setNothrow();
11409   }
11410 
11411   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11412     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11413     return StmtError();
11414   }
11415   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11416                                           AStmt);
11417 }
11418 
11419 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11420                                            Stmt *AStmt, SourceLocation StartLoc,
11421                                            SourceLocation EndLoc) {
11422   if (!AStmt)
11423     return StmtError();
11424 
11425   auto *CS = cast<CapturedStmt>(AStmt);
11426   // 1.2.2 OpenMP Language Terminology
11427   // Structured block - An executable statement with a single entry at the
11428   // top and a single exit at the bottom.
11429   // The point of exit cannot be a branch out of the structured block.
11430   // longjmp() and throw() must not violate the entry/exit criteria.
11431   CS->getCapturedDecl()->setNothrow();
11432 
11433   setFunctionHasBranchProtectedScope();
11434 
11435   DSAStack->setParentTeamsRegionLoc(StartLoc);
11436 
11437   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11438 }
11439 
11440 StmtResult
11441 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11442                                             SourceLocation EndLoc,
11443                                             OpenMPDirectiveKind CancelRegion) {
11444   if (DSAStack->isParentNowaitRegion()) {
11445     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11446     return StmtError();
11447   }
11448   if (DSAStack->isParentOrderedRegion()) {
11449     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11450     return StmtError();
11451   }
11452   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11453                                                CancelRegion);
11454 }
11455 
11456 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11457                                             SourceLocation StartLoc,
11458                                             SourceLocation EndLoc,
11459                                             OpenMPDirectiveKind CancelRegion) {
11460   if (DSAStack->isParentNowaitRegion()) {
11461     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11462     return StmtError();
11463   }
11464   if (DSAStack->isParentOrderedRegion()) {
11465     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11466     return StmtError();
11467   }
11468   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11469   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11470                                     CancelRegion);
11471 }
11472 
11473 static bool checkReductionClauseWithNogroup(Sema &S,
11474                                             ArrayRef<OMPClause *> Clauses) {
11475   const OMPClause *ReductionClause = nullptr;
11476   const OMPClause *NogroupClause = nullptr;
11477   for (const OMPClause *C : Clauses) {
11478     if (C->getClauseKind() == OMPC_reduction) {
11479       ReductionClause = C;
11480       if (NogroupClause)
11481         break;
11482       continue;
11483     }
11484     if (C->getClauseKind() == OMPC_nogroup) {
11485       NogroupClause = C;
11486       if (ReductionClause)
11487         break;
11488       continue;
11489     }
11490   }
11491   if (ReductionClause && NogroupClause) {
11492     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11493         << SourceRange(NogroupClause->getBeginLoc(),
11494                        NogroupClause->getEndLoc());
11495     return true;
11496   }
11497   return false;
11498 }
11499 
11500 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11501     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11502     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11503   if (!AStmt)
11504     return StmtError();
11505 
11506   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11507   OMPLoopBasedDirective::HelperExprs B;
11508   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11509   // define the nested loops number.
11510   unsigned NestedLoopCount =
11511       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11512                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11513                       VarsWithImplicitDSA, B);
11514   if (NestedLoopCount == 0)
11515     return StmtError();
11516 
11517   assert((CurContext->isDependentContext() || B.builtAll()) &&
11518          "omp for loop exprs were not built");
11519 
11520   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11521   // The grainsize clause and num_tasks clause are mutually exclusive and may
11522   // not appear on the same taskloop directive.
11523   if (checkMutuallyExclusiveClauses(*this, Clauses,
11524                                     {OMPC_grainsize, OMPC_num_tasks}))
11525     return StmtError();
11526   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11527   // If a reduction clause is present on the taskloop directive, the nogroup
11528   // clause must not be specified.
11529   if (checkReductionClauseWithNogroup(*this, Clauses))
11530     return StmtError();
11531 
11532   setFunctionHasBranchProtectedScope();
11533   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11534                                       NestedLoopCount, Clauses, AStmt, B,
11535                                       DSAStack->isCancelRegion());
11536 }
11537 
11538 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11539     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11540     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11541   if (!AStmt)
11542     return StmtError();
11543 
11544   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11545   OMPLoopBasedDirective::HelperExprs B;
11546   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11547   // define the nested loops number.
11548   unsigned NestedLoopCount =
11549       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11550                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11551                       VarsWithImplicitDSA, B);
11552   if (NestedLoopCount == 0)
11553     return StmtError();
11554 
11555   assert((CurContext->isDependentContext() || B.builtAll()) &&
11556          "omp for loop exprs were not built");
11557 
11558   if (!CurContext->isDependentContext()) {
11559     // Finalize the clauses that need pre-built expressions for CodeGen.
11560     for (OMPClause *C : Clauses) {
11561       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11562         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11563                                      B.NumIterations, *this, CurScope,
11564                                      DSAStack))
11565           return StmtError();
11566     }
11567   }
11568 
11569   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11570   // The grainsize clause and num_tasks clause are mutually exclusive and may
11571   // not appear on the same taskloop directive.
11572   if (checkMutuallyExclusiveClauses(*this, Clauses,
11573                                     {OMPC_grainsize, OMPC_num_tasks}))
11574     return StmtError();
11575   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11576   // If a reduction clause is present on the taskloop directive, the nogroup
11577   // clause must not be specified.
11578   if (checkReductionClauseWithNogroup(*this, Clauses))
11579     return StmtError();
11580   if (checkSimdlenSafelenSpecified(*this, Clauses))
11581     return StmtError();
11582 
11583   setFunctionHasBranchProtectedScope();
11584   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11585                                           NestedLoopCount, Clauses, AStmt, B);
11586 }
11587 
11588 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11589     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11590     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11591   if (!AStmt)
11592     return StmtError();
11593 
11594   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11595   OMPLoopBasedDirective::HelperExprs B;
11596   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11597   // define the nested loops number.
11598   unsigned NestedLoopCount =
11599       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11600                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11601                       VarsWithImplicitDSA, B);
11602   if (NestedLoopCount == 0)
11603     return StmtError();
11604 
11605   assert((CurContext->isDependentContext() || B.builtAll()) &&
11606          "omp for loop exprs were not built");
11607 
11608   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11609   // The grainsize clause and num_tasks clause are mutually exclusive and may
11610   // not appear on the same taskloop directive.
11611   if (checkMutuallyExclusiveClauses(*this, Clauses,
11612                                     {OMPC_grainsize, OMPC_num_tasks}))
11613     return StmtError();
11614   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11615   // If a reduction clause is present on the taskloop directive, the nogroup
11616   // clause must not be specified.
11617   if (checkReductionClauseWithNogroup(*this, Clauses))
11618     return StmtError();
11619 
11620   setFunctionHasBranchProtectedScope();
11621   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11622                                             NestedLoopCount, Clauses, AStmt, B,
11623                                             DSAStack->isCancelRegion());
11624 }
11625 
11626 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11627     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11628     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11629   if (!AStmt)
11630     return StmtError();
11631 
11632   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11633   OMPLoopBasedDirective::HelperExprs B;
11634   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11635   // define the nested loops number.
11636   unsigned NestedLoopCount =
11637       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11638                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11639                       VarsWithImplicitDSA, B);
11640   if (NestedLoopCount == 0)
11641     return StmtError();
11642 
11643   assert((CurContext->isDependentContext() || B.builtAll()) &&
11644          "omp for loop exprs were not built");
11645 
11646   if (!CurContext->isDependentContext()) {
11647     // Finalize the clauses that need pre-built expressions for CodeGen.
11648     for (OMPClause *C : Clauses) {
11649       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11650         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11651                                      B.NumIterations, *this, CurScope,
11652                                      DSAStack))
11653           return StmtError();
11654     }
11655   }
11656 
11657   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11658   // The grainsize clause and num_tasks clause are mutually exclusive and may
11659   // not appear on the same taskloop directive.
11660   if (checkMutuallyExclusiveClauses(*this, Clauses,
11661                                     {OMPC_grainsize, OMPC_num_tasks}))
11662     return StmtError();
11663   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11664   // If a reduction clause is present on the taskloop directive, the nogroup
11665   // clause must not be specified.
11666   if (checkReductionClauseWithNogroup(*this, Clauses))
11667     return StmtError();
11668   if (checkSimdlenSafelenSpecified(*this, Clauses))
11669     return StmtError();
11670 
11671   setFunctionHasBranchProtectedScope();
11672   return OMPMasterTaskLoopSimdDirective::Create(
11673       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11674 }
11675 
11676 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11677     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11678     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11679   if (!AStmt)
11680     return StmtError();
11681 
11682   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11683   auto *CS = cast<CapturedStmt>(AStmt);
11684   // 1.2.2 OpenMP Language Terminology
11685   // Structured block - An executable statement with a single entry at the
11686   // top and a single exit at the bottom.
11687   // The point of exit cannot be a branch out of the structured block.
11688   // longjmp() and throw() must not violate the entry/exit criteria.
11689   CS->getCapturedDecl()->setNothrow();
11690   for (int ThisCaptureLevel =
11691            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11692        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11693     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11694     // 1.2.2 OpenMP Language Terminology
11695     // Structured block - An executable statement with a single entry at the
11696     // top and a single exit at the bottom.
11697     // The point of exit cannot be a branch out of the structured block.
11698     // longjmp() and throw() must not violate the entry/exit criteria.
11699     CS->getCapturedDecl()->setNothrow();
11700   }
11701 
11702   OMPLoopBasedDirective::HelperExprs B;
11703   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11704   // define the nested loops number.
11705   unsigned NestedLoopCount = checkOpenMPLoop(
11706       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11707       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11708       VarsWithImplicitDSA, B);
11709   if (NestedLoopCount == 0)
11710     return StmtError();
11711 
11712   assert((CurContext->isDependentContext() || B.builtAll()) &&
11713          "omp for loop exprs were not built");
11714 
11715   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11716   // The grainsize clause and num_tasks clause are mutually exclusive and may
11717   // not appear on the same taskloop directive.
11718   if (checkMutuallyExclusiveClauses(*this, Clauses,
11719                                     {OMPC_grainsize, OMPC_num_tasks}))
11720     return StmtError();
11721   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11722   // If a reduction clause is present on the taskloop directive, the nogroup
11723   // clause must not be specified.
11724   if (checkReductionClauseWithNogroup(*this, Clauses))
11725     return StmtError();
11726 
11727   setFunctionHasBranchProtectedScope();
11728   return OMPParallelMasterTaskLoopDirective::Create(
11729       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11730       DSAStack->isCancelRegion());
11731 }
11732 
11733 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11734     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11735     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11736   if (!AStmt)
11737     return StmtError();
11738 
11739   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11740   auto *CS = cast<CapturedStmt>(AStmt);
11741   // 1.2.2 OpenMP Language Terminology
11742   // Structured block - An executable statement with a single entry at the
11743   // top and a single exit at the bottom.
11744   // The point of exit cannot be a branch out of the structured block.
11745   // longjmp() and throw() must not violate the entry/exit criteria.
11746   CS->getCapturedDecl()->setNothrow();
11747   for (int ThisCaptureLevel =
11748            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
11749        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11750     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11751     // 1.2.2 OpenMP Language Terminology
11752     // Structured block - An executable statement with a single entry at the
11753     // top and a single exit at the bottom.
11754     // The point of exit cannot be a branch out of the structured block.
11755     // longjmp() and throw() must not violate the entry/exit criteria.
11756     CS->getCapturedDecl()->setNothrow();
11757   }
11758 
11759   OMPLoopBasedDirective::HelperExprs B;
11760   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11761   // define the nested loops number.
11762   unsigned NestedLoopCount = checkOpenMPLoop(
11763       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11764       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11765       VarsWithImplicitDSA, B);
11766   if (NestedLoopCount == 0)
11767     return StmtError();
11768 
11769   assert((CurContext->isDependentContext() || B.builtAll()) &&
11770          "omp for loop exprs were not built");
11771 
11772   if (!CurContext->isDependentContext()) {
11773     // Finalize the clauses that need pre-built expressions for CodeGen.
11774     for (OMPClause *C : Clauses) {
11775       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11776         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11777                                      B.NumIterations, *this, CurScope,
11778                                      DSAStack))
11779           return StmtError();
11780     }
11781   }
11782 
11783   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11784   // The grainsize clause and num_tasks clause are mutually exclusive and may
11785   // not appear on the same taskloop directive.
11786   if (checkMutuallyExclusiveClauses(*this, Clauses,
11787                                     {OMPC_grainsize, OMPC_num_tasks}))
11788     return StmtError();
11789   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11790   // If a reduction clause is present on the taskloop directive, the nogroup
11791   // clause must not be specified.
11792   if (checkReductionClauseWithNogroup(*this, Clauses))
11793     return StmtError();
11794   if (checkSimdlenSafelenSpecified(*this, Clauses))
11795     return StmtError();
11796 
11797   setFunctionHasBranchProtectedScope();
11798   return OMPParallelMasterTaskLoopSimdDirective::Create(
11799       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11800 }
11801 
11802 StmtResult Sema::ActOnOpenMPDistributeDirective(
11803     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11804     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11805   if (!AStmt)
11806     return StmtError();
11807 
11808   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11809   OMPLoopBasedDirective::HelperExprs B;
11810   // In presence of clause 'collapse' with number of loops, it will
11811   // define the nested loops number.
11812   unsigned NestedLoopCount =
11813       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
11814                       nullptr /*ordered not a clause on distribute*/, AStmt,
11815                       *this, *DSAStack, VarsWithImplicitDSA, B);
11816   if (NestedLoopCount == 0)
11817     return StmtError();
11818 
11819   assert((CurContext->isDependentContext() || B.builtAll()) &&
11820          "omp for loop exprs were not built");
11821 
11822   setFunctionHasBranchProtectedScope();
11823   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
11824                                         NestedLoopCount, Clauses, AStmt, B);
11825 }
11826 
11827 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
11828     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11829     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11830   if (!AStmt)
11831     return StmtError();
11832 
11833   auto *CS = cast<CapturedStmt>(AStmt);
11834   // 1.2.2 OpenMP Language Terminology
11835   // Structured block - An executable statement with a single entry at the
11836   // top and a single exit at the bottom.
11837   // The point of exit cannot be a branch out of the structured block.
11838   // longjmp() and throw() must not violate the entry/exit criteria.
11839   CS->getCapturedDecl()->setNothrow();
11840   for (int ThisCaptureLevel =
11841            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
11842        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11843     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11844     // 1.2.2 OpenMP Language Terminology
11845     // Structured block - An executable statement with a single entry at the
11846     // top and a single exit at the bottom.
11847     // The point of exit cannot be a branch out of the structured block.
11848     // longjmp() and throw() must not violate the entry/exit criteria.
11849     CS->getCapturedDecl()->setNothrow();
11850   }
11851 
11852   OMPLoopBasedDirective::HelperExprs B;
11853   // In presence of clause 'collapse' with number of loops, it will
11854   // define the nested loops number.
11855   unsigned NestedLoopCount = checkOpenMPLoop(
11856       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11857       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11858       VarsWithImplicitDSA, B);
11859   if (NestedLoopCount == 0)
11860     return StmtError();
11861 
11862   assert((CurContext->isDependentContext() || B.builtAll()) &&
11863          "omp for loop exprs were not built");
11864 
11865   setFunctionHasBranchProtectedScope();
11866   return OMPDistributeParallelForDirective::Create(
11867       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11868       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11869 }
11870 
11871 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
11872     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11873     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11874   if (!AStmt)
11875     return StmtError();
11876 
11877   auto *CS = cast<CapturedStmt>(AStmt);
11878   // 1.2.2 OpenMP Language Terminology
11879   // Structured block - An executable statement with a single entry at the
11880   // top and a single exit at the bottom.
11881   // The point of exit cannot be a branch out of the structured block.
11882   // longjmp() and throw() must not violate the entry/exit criteria.
11883   CS->getCapturedDecl()->setNothrow();
11884   for (int ThisCaptureLevel =
11885            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
11886        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11887     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11888     // 1.2.2 OpenMP Language Terminology
11889     // Structured block - An executable statement with a single entry at the
11890     // top and a single exit at the bottom.
11891     // The point of exit cannot be a branch out of the structured block.
11892     // longjmp() and throw() must not violate the entry/exit criteria.
11893     CS->getCapturedDecl()->setNothrow();
11894   }
11895 
11896   OMPLoopBasedDirective::HelperExprs B;
11897   // In presence of clause 'collapse' with number of loops, it will
11898   // define the nested loops number.
11899   unsigned NestedLoopCount = checkOpenMPLoop(
11900       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11901       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11902       VarsWithImplicitDSA, B);
11903   if (NestedLoopCount == 0)
11904     return StmtError();
11905 
11906   assert((CurContext->isDependentContext() || B.builtAll()) &&
11907          "omp for loop exprs were not built");
11908 
11909   if (!CurContext->isDependentContext()) {
11910     // Finalize the clauses that need pre-built expressions for CodeGen.
11911     for (OMPClause *C : Clauses) {
11912       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11913         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11914                                      B.NumIterations, *this, CurScope,
11915                                      DSAStack))
11916           return StmtError();
11917     }
11918   }
11919 
11920   if (checkSimdlenSafelenSpecified(*this, Clauses))
11921     return StmtError();
11922 
11923   setFunctionHasBranchProtectedScope();
11924   return OMPDistributeParallelForSimdDirective::Create(
11925       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11926 }
11927 
11928 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
11929     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11930     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11931   if (!AStmt)
11932     return StmtError();
11933 
11934   auto *CS = cast<CapturedStmt>(AStmt);
11935   // 1.2.2 OpenMP Language Terminology
11936   // Structured block - An executable statement with a single entry at the
11937   // top and a single exit at the bottom.
11938   // The point of exit cannot be a branch out of the structured block.
11939   // longjmp() and throw() must not violate the entry/exit criteria.
11940   CS->getCapturedDecl()->setNothrow();
11941   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
11942        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11943     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11944     // 1.2.2 OpenMP Language Terminology
11945     // Structured block - An executable statement with a single entry at the
11946     // top and a single exit at the bottom.
11947     // The point of exit cannot be a branch out of the structured block.
11948     // longjmp() and throw() must not violate the entry/exit criteria.
11949     CS->getCapturedDecl()->setNothrow();
11950   }
11951 
11952   OMPLoopBasedDirective::HelperExprs B;
11953   // In presence of clause 'collapse' with number of loops, it will
11954   // define the nested loops number.
11955   unsigned NestedLoopCount =
11956       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
11957                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11958                       *DSAStack, VarsWithImplicitDSA, B);
11959   if (NestedLoopCount == 0)
11960     return StmtError();
11961 
11962   assert((CurContext->isDependentContext() || B.builtAll()) &&
11963          "omp for loop exprs were not built");
11964 
11965   if (!CurContext->isDependentContext()) {
11966     // Finalize the clauses that need pre-built expressions for CodeGen.
11967     for (OMPClause *C : Clauses) {
11968       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11969         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11970                                      B.NumIterations, *this, CurScope,
11971                                      DSAStack))
11972           return StmtError();
11973     }
11974   }
11975 
11976   if (checkSimdlenSafelenSpecified(*this, Clauses))
11977     return StmtError();
11978 
11979   setFunctionHasBranchProtectedScope();
11980   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11981                                             NestedLoopCount, Clauses, AStmt, B);
11982 }
11983 
11984 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11985     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11986     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11987   if (!AStmt)
11988     return StmtError();
11989 
11990   auto *CS = cast<CapturedStmt>(AStmt);
11991   // 1.2.2 OpenMP Language Terminology
11992   // Structured block - An executable statement with a single entry at the
11993   // top and a single exit at the bottom.
11994   // The point of exit cannot be a branch out of the structured block.
11995   // longjmp() and throw() must not violate the entry/exit criteria.
11996   CS->getCapturedDecl()->setNothrow();
11997   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11998        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11999     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12000     // 1.2.2 OpenMP Language Terminology
12001     // Structured block - An executable statement with a single entry at the
12002     // top and a single exit at the bottom.
12003     // The point of exit cannot be a branch out of the structured block.
12004     // longjmp() and throw() must not violate the entry/exit criteria.
12005     CS->getCapturedDecl()->setNothrow();
12006   }
12007 
12008   OMPLoopBasedDirective::HelperExprs B;
12009   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12010   // define the nested loops number.
12011   unsigned NestedLoopCount = checkOpenMPLoop(
12012       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12013       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12014       VarsWithImplicitDSA, B);
12015   if (NestedLoopCount == 0)
12016     return StmtError();
12017 
12018   assert((CurContext->isDependentContext() || B.builtAll()) &&
12019          "omp target parallel for simd loop exprs were not built");
12020 
12021   if (!CurContext->isDependentContext()) {
12022     // Finalize the clauses that need pre-built expressions for CodeGen.
12023     for (OMPClause *C : Clauses) {
12024       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12025         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12026                                      B.NumIterations, *this, CurScope,
12027                                      DSAStack))
12028           return StmtError();
12029     }
12030   }
12031   if (checkSimdlenSafelenSpecified(*this, Clauses))
12032     return StmtError();
12033 
12034   setFunctionHasBranchProtectedScope();
12035   return OMPTargetParallelForSimdDirective::Create(
12036       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12037 }
12038 
12039 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12040     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12041     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12042   if (!AStmt)
12043     return StmtError();
12044 
12045   auto *CS = cast<CapturedStmt>(AStmt);
12046   // 1.2.2 OpenMP Language Terminology
12047   // Structured block - An executable statement with a single entry at the
12048   // top and a single exit at the bottom.
12049   // The point of exit cannot be a branch out of the structured block.
12050   // longjmp() and throw() must not violate the entry/exit criteria.
12051   CS->getCapturedDecl()->setNothrow();
12052   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12053        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12054     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12055     // 1.2.2 OpenMP Language Terminology
12056     // Structured block - An executable statement with a single entry at the
12057     // top and a single exit at the bottom.
12058     // The point of exit cannot be a branch out of the structured block.
12059     // longjmp() and throw() must not violate the entry/exit criteria.
12060     CS->getCapturedDecl()->setNothrow();
12061   }
12062 
12063   OMPLoopBasedDirective::HelperExprs B;
12064   // In presence of clause 'collapse' with number of loops, it will define the
12065   // nested loops number.
12066   unsigned NestedLoopCount =
12067       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12068                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12069                       VarsWithImplicitDSA, B);
12070   if (NestedLoopCount == 0)
12071     return StmtError();
12072 
12073   assert((CurContext->isDependentContext() || B.builtAll()) &&
12074          "omp target simd loop exprs were not built");
12075 
12076   if (!CurContext->isDependentContext()) {
12077     // Finalize the clauses that need pre-built expressions for CodeGen.
12078     for (OMPClause *C : Clauses) {
12079       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12080         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12081                                      B.NumIterations, *this, CurScope,
12082                                      DSAStack))
12083           return StmtError();
12084     }
12085   }
12086 
12087   if (checkSimdlenSafelenSpecified(*this, Clauses))
12088     return StmtError();
12089 
12090   setFunctionHasBranchProtectedScope();
12091   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12092                                         NestedLoopCount, Clauses, AStmt, B);
12093 }
12094 
12095 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12096     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12097     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12098   if (!AStmt)
12099     return StmtError();
12100 
12101   auto *CS = cast<CapturedStmt>(AStmt);
12102   // 1.2.2 OpenMP Language Terminology
12103   // Structured block - An executable statement with a single entry at the
12104   // top and a single exit at the bottom.
12105   // The point of exit cannot be a branch out of the structured block.
12106   // longjmp() and throw() must not violate the entry/exit criteria.
12107   CS->getCapturedDecl()->setNothrow();
12108   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12109        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12110     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12111     // 1.2.2 OpenMP Language Terminology
12112     // Structured block - An executable statement with a single entry at the
12113     // top and a single exit at the bottom.
12114     // The point of exit cannot be a branch out of the structured block.
12115     // longjmp() and throw() must not violate the entry/exit criteria.
12116     CS->getCapturedDecl()->setNothrow();
12117   }
12118 
12119   OMPLoopBasedDirective::HelperExprs B;
12120   // In presence of clause 'collapse' with number of loops, it will
12121   // define the nested loops number.
12122   unsigned NestedLoopCount =
12123       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12124                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12125                       *DSAStack, VarsWithImplicitDSA, B);
12126   if (NestedLoopCount == 0)
12127     return StmtError();
12128 
12129   assert((CurContext->isDependentContext() || B.builtAll()) &&
12130          "omp teams distribute loop exprs were not built");
12131 
12132   setFunctionHasBranchProtectedScope();
12133 
12134   DSAStack->setParentTeamsRegionLoc(StartLoc);
12135 
12136   return OMPTeamsDistributeDirective::Create(
12137       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12138 }
12139 
12140 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12141     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12142     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12143   if (!AStmt)
12144     return StmtError();
12145 
12146   auto *CS = cast<CapturedStmt>(AStmt);
12147   // 1.2.2 OpenMP Language Terminology
12148   // Structured block - An executable statement with a single entry at the
12149   // top and a single exit at the bottom.
12150   // The point of exit cannot be a branch out of the structured block.
12151   // longjmp() and throw() must not violate the entry/exit criteria.
12152   CS->getCapturedDecl()->setNothrow();
12153   for (int ThisCaptureLevel =
12154            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12155        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12156     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12157     // 1.2.2 OpenMP Language Terminology
12158     // Structured block - An executable statement with a single entry at the
12159     // top and a single exit at the bottom.
12160     // The point of exit cannot be a branch out of the structured block.
12161     // longjmp() and throw() must not violate the entry/exit criteria.
12162     CS->getCapturedDecl()->setNothrow();
12163   }
12164 
12165   OMPLoopBasedDirective::HelperExprs B;
12166   // In presence of clause 'collapse' with number of loops, it will
12167   // define the nested loops number.
12168   unsigned NestedLoopCount = checkOpenMPLoop(
12169       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12170       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12171       VarsWithImplicitDSA, B);
12172 
12173   if (NestedLoopCount == 0)
12174     return StmtError();
12175 
12176   assert((CurContext->isDependentContext() || B.builtAll()) &&
12177          "omp teams distribute simd loop exprs were not built");
12178 
12179   if (!CurContext->isDependentContext()) {
12180     // Finalize the clauses that need pre-built expressions for CodeGen.
12181     for (OMPClause *C : Clauses) {
12182       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12183         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12184                                      B.NumIterations, *this, CurScope,
12185                                      DSAStack))
12186           return StmtError();
12187     }
12188   }
12189 
12190   if (checkSimdlenSafelenSpecified(*this, Clauses))
12191     return StmtError();
12192 
12193   setFunctionHasBranchProtectedScope();
12194 
12195   DSAStack->setParentTeamsRegionLoc(StartLoc);
12196 
12197   return OMPTeamsDistributeSimdDirective::Create(
12198       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12199 }
12200 
12201 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12202     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12203     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12204   if (!AStmt)
12205     return StmtError();
12206 
12207   auto *CS = cast<CapturedStmt>(AStmt);
12208   // 1.2.2 OpenMP Language Terminology
12209   // Structured block - An executable statement with a single entry at the
12210   // top and a single exit at the bottom.
12211   // The point of exit cannot be a branch out of the structured block.
12212   // longjmp() and throw() must not violate the entry/exit criteria.
12213   CS->getCapturedDecl()->setNothrow();
12214 
12215   for (int ThisCaptureLevel =
12216            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12217        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12218     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12219     // 1.2.2 OpenMP Language Terminology
12220     // Structured block - An executable statement with a single entry at the
12221     // top and a single exit at the bottom.
12222     // The point of exit cannot be a branch out of the structured block.
12223     // longjmp() and throw() must not violate the entry/exit criteria.
12224     CS->getCapturedDecl()->setNothrow();
12225   }
12226 
12227   OMPLoopBasedDirective::HelperExprs B;
12228   // In presence of clause 'collapse' with number of loops, it will
12229   // define the nested loops number.
12230   unsigned NestedLoopCount = checkOpenMPLoop(
12231       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12232       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12233       VarsWithImplicitDSA, B);
12234 
12235   if (NestedLoopCount == 0)
12236     return StmtError();
12237 
12238   assert((CurContext->isDependentContext() || B.builtAll()) &&
12239          "omp for loop exprs were not built");
12240 
12241   if (!CurContext->isDependentContext()) {
12242     // Finalize the clauses that need pre-built expressions for CodeGen.
12243     for (OMPClause *C : Clauses) {
12244       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12245         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12246                                      B.NumIterations, *this, CurScope,
12247                                      DSAStack))
12248           return StmtError();
12249     }
12250   }
12251 
12252   if (checkSimdlenSafelenSpecified(*this, Clauses))
12253     return StmtError();
12254 
12255   setFunctionHasBranchProtectedScope();
12256 
12257   DSAStack->setParentTeamsRegionLoc(StartLoc);
12258 
12259   return OMPTeamsDistributeParallelForSimdDirective::Create(
12260       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12261 }
12262 
12263 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12264     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12265     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12266   if (!AStmt)
12267     return StmtError();
12268 
12269   auto *CS = cast<CapturedStmt>(AStmt);
12270   // 1.2.2 OpenMP Language Terminology
12271   // Structured block - An executable statement with a single entry at the
12272   // top and a single exit at the bottom.
12273   // The point of exit cannot be a branch out of the structured block.
12274   // longjmp() and throw() must not violate the entry/exit criteria.
12275   CS->getCapturedDecl()->setNothrow();
12276 
12277   for (int ThisCaptureLevel =
12278            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12279        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12280     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12281     // 1.2.2 OpenMP Language Terminology
12282     // Structured block - An executable statement with a single entry at the
12283     // top and a single exit at the bottom.
12284     // The point of exit cannot be a branch out of the structured block.
12285     // longjmp() and throw() must not violate the entry/exit criteria.
12286     CS->getCapturedDecl()->setNothrow();
12287   }
12288 
12289   OMPLoopBasedDirective::HelperExprs B;
12290   // In presence of clause 'collapse' with number of loops, it will
12291   // define the nested loops number.
12292   unsigned NestedLoopCount = checkOpenMPLoop(
12293       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12294       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12295       VarsWithImplicitDSA, B);
12296 
12297   if (NestedLoopCount == 0)
12298     return StmtError();
12299 
12300   assert((CurContext->isDependentContext() || B.builtAll()) &&
12301          "omp for loop exprs were not built");
12302 
12303   setFunctionHasBranchProtectedScope();
12304 
12305   DSAStack->setParentTeamsRegionLoc(StartLoc);
12306 
12307   return OMPTeamsDistributeParallelForDirective::Create(
12308       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12309       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12310 }
12311 
12312 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12313                                                  Stmt *AStmt,
12314                                                  SourceLocation StartLoc,
12315                                                  SourceLocation EndLoc) {
12316   if (!AStmt)
12317     return StmtError();
12318 
12319   auto *CS = cast<CapturedStmt>(AStmt);
12320   // 1.2.2 OpenMP Language Terminology
12321   // Structured block - An executable statement with a single entry at the
12322   // top and a single exit at the bottom.
12323   // The point of exit cannot be a branch out of the structured block.
12324   // longjmp() and throw() must not violate the entry/exit criteria.
12325   CS->getCapturedDecl()->setNothrow();
12326 
12327   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12328        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12329     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12330     // 1.2.2 OpenMP Language Terminology
12331     // Structured block - An executable statement with a single entry at the
12332     // top and a single exit at the bottom.
12333     // The point of exit cannot be a branch out of the structured block.
12334     // longjmp() and throw() must not violate the entry/exit criteria.
12335     CS->getCapturedDecl()->setNothrow();
12336   }
12337   setFunctionHasBranchProtectedScope();
12338 
12339   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12340                                          AStmt);
12341 }
12342 
12343 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12344     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12345     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12346   if (!AStmt)
12347     return StmtError();
12348 
12349   auto *CS = cast<CapturedStmt>(AStmt);
12350   // 1.2.2 OpenMP Language Terminology
12351   // Structured block - An executable statement with a single entry at the
12352   // top and a single exit at the bottom.
12353   // The point of exit cannot be a branch out of the structured block.
12354   // longjmp() and throw() must not violate the entry/exit criteria.
12355   CS->getCapturedDecl()->setNothrow();
12356   for (int ThisCaptureLevel =
12357            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12358        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12359     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12360     // 1.2.2 OpenMP Language Terminology
12361     // Structured block - An executable statement with a single entry at the
12362     // top and a single exit at the bottom.
12363     // The point of exit cannot be a branch out of the structured block.
12364     // longjmp() and throw() must not violate the entry/exit criteria.
12365     CS->getCapturedDecl()->setNothrow();
12366   }
12367 
12368   OMPLoopBasedDirective::HelperExprs B;
12369   // In presence of clause 'collapse' with number of loops, it will
12370   // define the nested loops number.
12371   unsigned NestedLoopCount = checkOpenMPLoop(
12372       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12373       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12374       VarsWithImplicitDSA, B);
12375   if (NestedLoopCount == 0)
12376     return StmtError();
12377 
12378   assert((CurContext->isDependentContext() || B.builtAll()) &&
12379          "omp target teams distribute loop exprs were not built");
12380 
12381   setFunctionHasBranchProtectedScope();
12382   return OMPTargetTeamsDistributeDirective::Create(
12383       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12384 }
12385 
12386 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12387     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12388     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12389   if (!AStmt)
12390     return StmtError();
12391 
12392   auto *CS = cast<CapturedStmt>(AStmt);
12393   // 1.2.2 OpenMP Language Terminology
12394   // Structured block - An executable statement with a single entry at the
12395   // top and a single exit at the bottom.
12396   // The point of exit cannot be a branch out of the structured block.
12397   // longjmp() and throw() must not violate the entry/exit criteria.
12398   CS->getCapturedDecl()->setNothrow();
12399   for (int ThisCaptureLevel =
12400            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12401        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12402     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12403     // 1.2.2 OpenMP Language Terminology
12404     // Structured block - An executable statement with a single entry at the
12405     // top and a single exit at the bottom.
12406     // The point of exit cannot be a branch out of the structured block.
12407     // longjmp() and throw() must not violate the entry/exit criteria.
12408     CS->getCapturedDecl()->setNothrow();
12409   }
12410 
12411   OMPLoopBasedDirective::HelperExprs B;
12412   // In presence of clause 'collapse' with number of loops, it will
12413   // define the nested loops number.
12414   unsigned NestedLoopCount = checkOpenMPLoop(
12415       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12416       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12417       VarsWithImplicitDSA, B);
12418   if (NestedLoopCount == 0)
12419     return StmtError();
12420 
12421   assert((CurContext->isDependentContext() || B.builtAll()) &&
12422          "omp target teams distribute parallel for loop exprs were not built");
12423 
12424   if (!CurContext->isDependentContext()) {
12425     // Finalize the clauses that need pre-built expressions for CodeGen.
12426     for (OMPClause *C : Clauses) {
12427       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12428         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12429                                      B.NumIterations, *this, CurScope,
12430                                      DSAStack))
12431           return StmtError();
12432     }
12433   }
12434 
12435   setFunctionHasBranchProtectedScope();
12436   return OMPTargetTeamsDistributeParallelForDirective::Create(
12437       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12438       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12439 }
12440 
12441 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12442     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12443     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12444   if (!AStmt)
12445     return StmtError();
12446 
12447   auto *CS = cast<CapturedStmt>(AStmt);
12448   // 1.2.2 OpenMP Language Terminology
12449   // Structured block - An executable statement with a single entry at the
12450   // top and a single exit at the bottom.
12451   // The point of exit cannot be a branch out of the structured block.
12452   // longjmp() and throw() must not violate the entry/exit criteria.
12453   CS->getCapturedDecl()->setNothrow();
12454   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12455            OMPD_target_teams_distribute_parallel_for_simd);
12456        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12457     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12458     // 1.2.2 OpenMP Language Terminology
12459     // Structured block - An executable statement with a single entry at the
12460     // top and a single exit at the bottom.
12461     // The point of exit cannot be a branch out of the structured block.
12462     // longjmp() and throw() must not violate the entry/exit criteria.
12463     CS->getCapturedDecl()->setNothrow();
12464   }
12465 
12466   OMPLoopBasedDirective::HelperExprs B;
12467   // In presence of clause 'collapse' with number of loops, it will
12468   // define the nested loops number.
12469   unsigned NestedLoopCount =
12470       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12471                       getCollapseNumberExpr(Clauses),
12472                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12473                       *DSAStack, VarsWithImplicitDSA, B);
12474   if (NestedLoopCount == 0)
12475     return StmtError();
12476 
12477   assert((CurContext->isDependentContext() || B.builtAll()) &&
12478          "omp target teams distribute parallel for simd loop exprs were not "
12479          "built");
12480 
12481   if (!CurContext->isDependentContext()) {
12482     // Finalize the clauses that need pre-built expressions for CodeGen.
12483     for (OMPClause *C : Clauses) {
12484       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12485         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12486                                      B.NumIterations, *this, CurScope,
12487                                      DSAStack))
12488           return StmtError();
12489     }
12490   }
12491 
12492   if (checkSimdlenSafelenSpecified(*this, Clauses))
12493     return StmtError();
12494 
12495   setFunctionHasBranchProtectedScope();
12496   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12497       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12498 }
12499 
12500 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12501     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12502     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12503   if (!AStmt)
12504     return StmtError();
12505 
12506   auto *CS = cast<CapturedStmt>(AStmt);
12507   // 1.2.2 OpenMP Language Terminology
12508   // Structured block - An executable statement with a single entry at the
12509   // top and a single exit at the bottom.
12510   // The point of exit cannot be a branch out of the structured block.
12511   // longjmp() and throw() must not violate the entry/exit criteria.
12512   CS->getCapturedDecl()->setNothrow();
12513   for (int ThisCaptureLevel =
12514            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12515        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12516     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12517     // 1.2.2 OpenMP Language Terminology
12518     // Structured block - An executable statement with a single entry at the
12519     // top and a single exit at the bottom.
12520     // The point of exit cannot be a branch out of the structured block.
12521     // longjmp() and throw() must not violate the entry/exit criteria.
12522     CS->getCapturedDecl()->setNothrow();
12523   }
12524 
12525   OMPLoopBasedDirective::HelperExprs B;
12526   // In presence of clause 'collapse' with number of loops, it will
12527   // define the nested loops number.
12528   unsigned NestedLoopCount = checkOpenMPLoop(
12529       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12530       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12531       VarsWithImplicitDSA, B);
12532   if (NestedLoopCount == 0)
12533     return StmtError();
12534 
12535   assert((CurContext->isDependentContext() || B.builtAll()) &&
12536          "omp target teams distribute simd loop exprs were not built");
12537 
12538   if (!CurContext->isDependentContext()) {
12539     // Finalize the clauses that need pre-built expressions for CodeGen.
12540     for (OMPClause *C : Clauses) {
12541       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12542         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12543                                      B.NumIterations, *this, CurScope,
12544                                      DSAStack))
12545           return StmtError();
12546     }
12547   }
12548 
12549   if (checkSimdlenSafelenSpecified(*this, Clauses))
12550     return StmtError();
12551 
12552   setFunctionHasBranchProtectedScope();
12553   return OMPTargetTeamsDistributeSimdDirective::Create(
12554       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12555 }
12556 
12557 bool Sema::checkTransformableLoopNest(
12558     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
12559     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
12560     Stmt *&Body,
12561     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
12562         &OriginalInits) {
12563   OriginalInits.emplace_back();
12564   bool Result = OMPLoopBasedDirective::doForAllLoops(
12565       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
12566       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
12567                                                         Stmt *CurStmt) {
12568         VarsWithInheritedDSAType TmpDSA;
12569         unsigned SingleNumLoops =
12570             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
12571                             TmpDSA, LoopHelpers[Cnt]);
12572         if (SingleNumLoops == 0)
12573           return true;
12574         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12575         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12576           OriginalInits.back().push_back(For->getInit());
12577           Body = For->getBody();
12578         } else {
12579           assert(isa<CXXForRangeStmt>(CurStmt) &&
12580                  "Expected canonical for or range-based for loops.");
12581           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12582           OriginalInits.back().push_back(CXXFor->getBeginStmt());
12583           Body = CXXFor->getBody();
12584         }
12585         OriginalInits.emplace_back();
12586         return false;
12587       },
12588       [&OriginalInits](OMPLoopBasedDirective *Transform) {
12589         Stmt *DependentPreInits;
12590         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
12591           DependentPreInits = Dir->getPreInits();
12592         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
12593           DependentPreInits = Dir->getPreInits();
12594         else
12595           llvm_unreachable("Unhandled loop transformation");
12596         if (!DependentPreInits)
12597           return;
12598         for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
12599           OriginalInits.back().push_back(C);
12600       });
12601   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
12602   OriginalInits.pop_back();
12603   return Result;
12604 }
12605 
12606 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12607                                           Stmt *AStmt, SourceLocation StartLoc,
12608                                           SourceLocation EndLoc) {
12609   auto SizesClauses =
12610       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12611   if (SizesClauses.empty()) {
12612     // A missing 'sizes' clause is already reported by the parser.
12613     return StmtError();
12614   }
12615   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12616   unsigned NumLoops = SizesClause->getNumSizes();
12617 
12618   // Empty statement should only be possible if there already was an error.
12619   if (!AStmt)
12620     return StmtError();
12621 
12622   // Verify and diagnose loop nest.
12623   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12624   Stmt *Body = nullptr;
12625   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
12626       OriginalInits;
12627   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
12628                                   OriginalInits))
12629     return StmtError();
12630 
12631   // Delay tiling to when template is completely instantiated.
12632   if (CurContext->isDependentContext())
12633     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12634                                     NumLoops, AStmt, nullptr, nullptr);
12635 
12636   SmallVector<Decl *, 4> PreInits;
12637 
12638   // Create iteration variables for the generated loops.
12639   SmallVector<VarDecl *, 4> FloorIndVars;
12640   SmallVector<VarDecl *, 4> TileIndVars;
12641   FloorIndVars.resize(NumLoops);
12642   TileIndVars.resize(NumLoops);
12643   for (unsigned I = 0; I < NumLoops; ++I) {
12644     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12645 
12646     assert(LoopHelper.Counters.size() == 1 &&
12647            "Expect single-dimensional loop iteration space");
12648     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12649     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12650     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12651     QualType CntTy = IterVarRef->getType();
12652 
12653     // Iteration variable for the floor (i.e. outer) loop.
12654     {
12655       std::string FloorCntName =
12656           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12657       VarDecl *FloorCntDecl =
12658           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12659       FloorIndVars[I] = FloorCntDecl;
12660     }
12661 
12662     // Iteration variable for the tile (i.e. inner) loop.
12663     {
12664       std::string TileCntName =
12665           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12666 
12667       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12668       // used by the expressions to derive the original iteration variable's
12669       // value from the logical iteration number.
12670       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12671       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12672       TileIndVars[I] = TileCntDecl;
12673     }
12674     for (auto &P : OriginalInits[I]) {
12675       if (auto *D = P.dyn_cast<Decl *>())
12676         PreInits.push_back(D);
12677       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12678         PreInits.append(PI->decl_begin(), PI->decl_end());
12679     }
12680     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12681       PreInits.append(PI->decl_begin(), PI->decl_end());
12682     // Gather declarations for the data members used as counters.
12683     for (Expr *CounterRef : LoopHelper.Counters) {
12684       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12685       if (isa<OMPCapturedExprDecl>(CounterDecl))
12686         PreInits.push_back(CounterDecl);
12687     }
12688   }
12689 
12690   // Once the original iteration values are set, append the innermost body.
12691   Stmt *Inner = Body;
12692 
12693   // Create tile loops from the inside to the outside.
12694   for (int I = NumLoops - 1; I >= 0; --I) {
12695     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12696     Expr *NumIterations = LoopHelper.NumIterations;
12697     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12698     QualType CntTy = OrigCntVar->getType();
12699     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12700     Scope *CurScope = getCurScope();
12701 
12702     // Commonly used variables.
12703     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12704                                            OrigCntVar->getExprLoc());
12705     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12706                                             OrigCntVar->getExprLoc());
12707 
12708     // For init-statement: auto .tile.iv = .floor.iv
12709     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12710                          /*DirectInit=*/false);
12711     Decl *CounterDecl = TileIndVars[I];
12712     StmtResult InitStmt = new (Context)
12713         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12714                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12715     if (!InitStmt.isUsable())
12716       return StmtError();
12717 
12718     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
12719     // NumIterations)
12720     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12721                                       BO_Add, FloorIV, DimTileSize);
12722     if (!EndOfTile.isUsable())
12723       return StmtError();
12724     ExprResult IsPartialTile =
12725         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
12726                    NumIterations, EndOfTile.get());
12727     if (!IsPartialTile.isUsable())
12728       return StmtError();
12729     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
12730         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
12731         IsPartialTile.get(), NumIterations, EndOfTile.get());
12732     if (!MinTileAndIterSpace.isUsable())
12733       return StmtError();
12734     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12735                                      BO_LT, TileIV, MinTileAndIterSpace.get());
12736     if (!CondExpr.isUsable())
12737       return StmtError();
12738 
12739     // For incr-statement: ++.tile.iv
12740     ExprResult IncrStmt =
12741         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
12742     if (!IncrStmt.isUsable())
12743       return StmtError();
12744 
12745     // Statements to set the original iteration variable's value from the
12746     // logical iteration number.
12747     // Generated for loop is:
12748     // Original_for_init;
12749     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
12750     // NumIterations); ++.tile.iv) {
12751     //   Original_Body;
12752     //   Original_counter_update;
12753     // }
12754     // FIXME: If the innermost body is an loop itself, inserting these
12755     // statements stops it being recognized  as a perfectly nested loop (e.g.
12756     // for applying tiling again). If this is the case, sink the expressions
12757     // further into the inner loop.
12758     SmallVector<Stmt *, 4> BodyParts;
12759     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
12760     BodyParts.push_back(Inner);
12761     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
12762                                  Inner->getEndLoc());
12763     Inner = new (Context)
12764         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12765                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12766                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12767   }
12768 
12769   // Create floor loops from the inside to the outside.
12770   for (int I = NumLoops - 1; I >= 0; --I) {
12771     auto &LoopHelper = LoopHelpers[I];
12772     Expr *NumIterations = LoopHelper.NumIterations;
12773     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12774     QualType CntTy = OrigCntVar->getType();
12775     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12776     Scope *CurScope = getCurScope();
12777 
12778     // Commonly used variables.
12779     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12780                                             OrigCntVar->getExprLoc());
12781 
12782     // For init-statement: auto .floor.iv = 0
12783     AddInitializerToDecl(
12784         FloorIndVars[I],
12785         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
12786         /*DirectInit=*/false);
12787     Decl *CounterDecl = FloorIndVars[I];
12788     StmtResult InitStmt = new (Context)
12789         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12790                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12791     if (!InitStmt.isUsable())
12792       return StmtError();
12793 
12794     // For cond-expression: .floor.iv < NumIterations
12795     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12796                                      BO_LT, FloorIV, NumIterations);
12797     if (!CondExpr.isUsable())
12798       return StmtError();
12799 
12800     // For incr-statement: .floor.iv += DimTileSize
12801     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
12802                                      BO_AddAssign, FloorIV, DimTileSize);
12803     if (!IncrStmt.isUsable())
12804       return StmtError();
12805 
12806     Inner = new (Context)
12807         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12808                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12809                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12810   }
12811 
12812   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
12813                                   AStmt, Inner,
12814                                   buildPreInits(Context, PreInits));
12815 }
12816 
12817 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
12818                                             Stmt *AStmt,
12819                                             SourceLocation StartLoc,
12820                                             SourceLocation EndLoc) {
12821   // Empty statement should only be possible if there already was an error.
12822   if (!AStmt)
12823     return StmtError();
12824 
12825   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
12826     return StmtError();
12827 
12828   const OMPFullClause *FullClause =
12829       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
12830   const OMPPartialClause *PartialClause =
12831       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
12832   assert(!(FullClause && PartialClause) &&
12833          "mutual exclusivity must have been checked before");
12834 
12835   constexpr unsigned NumLoops = 1;
12836   Stmt *Body = nullptr;
12837   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
12838       NumLoops);
12839   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
12840       OriginalInits;
12841   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
12842                                   Body, OriginalInits))
12843     return StmtError();
12844 
12845   // Delay unrolling to when template is completely instantiated.
12846   if (CurContext->isDependentContext())
12847     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
12848                                       nullptr, nullptr);
12849 
12850   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
12851 
12852   if (FullClause) {
12853     if (!VerifyPositiveIntegerConstantInClause(
12854              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
12855              /*SuppressExprDigs=*/true)
12856              .isUsable()) {
12857       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
12858       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
12859           << "#pragma omp unroll full";
12860       return StmtError();
12861     }
12862   }
12863 
12864   // The generated loop may only be passed to other loop-associated directive
12865   // when a partial clause is specified. Without the requirement it is
12866   // sufficient to generate loop unroll metadata at code-generation.
12867   if (!PartialClause)
12868     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
12869                                       nullptr, nullptr);
12870 
12871   // Otherwise, we need to provide a de-sugared/transformed AST that can be
12872   // associated with another loop directive.
12873   //
12874   // The canonical loop analysis return by checkTransformableLoopNest assumes
12875   // the following structure to be the same loop without transformations or
12876   // directives applied: \code OriginalInits; LoopHelper.PreInits;
12877   // LoopHelper.Counters;
12878   // for (; IV < LoopHelper.NumIterations; ++IV) {
12879   //   LoopHelper.Updates;
12880   //   Body;
12881   // }
12882   // \endcode
12883   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
12884   // and referenced by LoopHelper.IterationVarRef.
12885   //
12886   // The unrolling directive transforms this into the following loop:
12887   // \code
12888   // OriginalInits;         \
12889   // LoopHelper.PreInits;    > NewPreInits
12890   // LoopHelper.Counters;   /
12891   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
12892   //   #pragma clang loop unroll_count(Factor)
12893   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
12894   //   {
12895   //     LoopHelper.Updates;
12896   //     Body;
12897   //   }
12898   // }
12899   // \endcode
12900   // where UIV is a new logical iteration counter. IV must be the same VarDecl
12901   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
12902   // references it. If the partially unrolled loop is associated with another
12903   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
12904   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
12905   // OpenMP canonical loop. The inner loop is not an associable canonical loop
12906   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
12907   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
12908   // property of the OMPLoopBasedDirective instead of statements in
12909   // CompoundStatement. This is to allow the loop to become a non-outermost loop
12910   // of a canonical loop nest where these PreInits are emitted before the
12911   // outermost directive.
12912 
12913   // Determine the PreInit declarations.
12914   SmallVector<Decl *, 4> PreInits;
12915   assert(OriginalInits.size() == 1 &&
12916          "Expecting a single-dimensional loop iteration space");
12917   for (auto &P : OriginalInits[0]) {
12918     if (auto *D = P.dyn_cast<Decl *>())
12919       PreInits.push_back(D);
12920     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12921       PreInits.append(PI->decl_begin(), PI->decl_end());
12922   }
12923   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12924     PreInits.append(PI->decl_begin(), PI->decl_end());
12925   // Gather declarations for the data members used as counters.
12926   for (Expr *CounterRef : LoopHelper.Counters) {
12927     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12928     if (isa<OMPCapturedExprDecl>(CounterDecl))
12929       PreInits.push_back(CounterDecl);
12930   }
12931 
12932   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12933   QualType IVTy = IterationVarRef->getType();
12934   assert(LoopHelper.Counters.size() == 1 &&
12935          "Expecting a single-dimensional loop iteration space");
12936   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12937 
12938   // Determine the unroll factor.
12939   uint64_t Factor;
12940   SourceLocation FactorLoc;
12941   if (Expr *FactorVal = PartialClause->getFactor()) {
12942     Factor =
12943         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
12944     FactorLoc = FactorVal->getExprLoc();
12945   } else {
12946     // TODO: Use a better profitability model.
12947     Factor = 2;
12948   }
12949   assert(Factor > 0 && "Expected positive unroll factor");
12950   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
12951     return IntegerLiteral::Create(
12952         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
12953         FactorLoc);
12954   };
12955 
12956   // Iteration variable SourceLocations.
12957   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
12958   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
12959   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
12960 
12961   // Internal variable names.
12962   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
12963   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
12964   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
12965   std::string InnerTripCountName =
12966       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
12967 
12968   // Create the iteration variable for the unrolled loop.
12969   VarDecl *OuterIVDecl =
12970       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
12971   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
12972     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
12973   };
12974 
12975   // Iteration variable for the inner loop: Reuse the iteration variable created
12976   // by checkOpenMPLoop.
12977   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
12978   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
12979   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
12980     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
12981   };
12982 
12983   // Make a copy of the NumIterations expression for each use: By the AST
12984   // constraints, every expression object in a DeclContext must be unique.
12985   CaptureVars CopyTransformer(*this);
12986   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
12987     return AssertSuccess(
12988         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
12989   };
12990 
12991   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
12992   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
12993   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
12994   StmtResult InnerInit = new (Context)
12995       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
12996   if (!InnerInit.isUsable())
12997     return StmtError();
12998 
12999   // Inner For cond-expression:
13000   // \code
13001   //   .unroll_inner.iv < .unrolled.iv + Factor &&
13002   //   .unroll_inner.iv < NumIterations
13003   // \endcode
13004   // This conjunction of two conditions allows ScalarEvolution to derive the
13005   // maximum trip count of the inner loop.
13006   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13007                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
13008   if (!EndOfTile.isUsable())
13009     return StmtError();
13010   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13011                                      BO_LE, MakeInnerRef(), EndOfTile.get());
13012   if (!InnerCond1.isUsable())
13013     return StmtError();
13014   ExprResult InnerCond2 =
13015       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
13016                  MakeNumIterations());
13017   if (!InnerCond2.isUsable())
13018     return StmtError();
13019   ExprResult InnerCond =
13020       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
13021                  InnerCond1.get(), InnerCond2.get());
13022   if (!InnerCond.isUsable())
13023     return StmtError();
13024 
13025   // Inner For incr-statement: ++.unroll_inner.iv
13026   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
13027                                       UO_PreInc, MakeInnerRef());
13028   if (!InnerIncr.isUsable())
13029     return StmtError();
13030 
13031   // Inner For statement.
13032   SmallVector<Stmt *> InnerBodyStmts;
13033   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13034   InnerBodyStmts.push_back(Body);
13035   CompoundStmt *InnerBody = CompoundStmt::Create(
13036       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
13037   ForStmt *InnerFor = new (Context)
13038       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
13039               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
13040               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13041 
13042   // Unroll metadata for the inner loop.
13043   // This needs to take into account the remainder portion of the unrolled loop,
13044   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
13045   // supports multiple loop exits. Instead, unroll using a factor equivalent to
13046   // the maximum trip count, which will also generate a remainder loop. Just
13047   // `unroll(enable)` (which could have been useful if the user has not
13048   // specified a concrete factor; even though the outer loop cannot be
13049   // influenced anymore, would avoid more code bloat than necessary) will refuse
13050   // the loop because "Won't unroll; remainder loop could not be generated when
13051   // assuming runtime trip count". Even if it did work, it must not choose a
13052   // larger unroll factor than the maximum loop length, or it would always just
13053   // execute the remainder loop.
13054   LoopHintAttr *UnrollHintAttr =
13055       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
13056                                    LoopHintAttr::Numeric, MakeFactorExpr());
13057   AttributedStmt *InnerUnrolled =
13058       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
13059 
13060   // Outer For init-statement: auto .unrolled.iv = 0
13061   AddInitializerToDecl(
13062       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13063       /*DirectInit=*/false);
13064   StmtResult OuterInit = new (Context)
13065       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13066   if (!OuterInit.isUsable())
13067     return StmtError();
13068 
13069   // Outer For cond-expression: .unrolled.iv < NumIterations
13070   ExprResult OuterConde =
13071       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
13072                  MakeNumIterations());
13073   if (!OuterConde.isUsable())
13074     return StmtError();
13075 
13076   // Outer For incr-statement: .unrolled.iv += Factor
13077   ExprResult OuterIncr =
13078       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
13079                  MakeOuterRef(), MakeFactorExpr());
13080   if (!OuterIncr.isUsable())
13081     return StmtError();
13082 
13083   // Outer For statement.
13084   ForStmt *OuterFor = new (Context)
13085       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
13086               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
13087               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13088 
13089   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13090                                     OuterFor, buildPreInits(Context, PreInits));
13091 }
13092 
13093 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
13094                                              SourceLocation StartLoc,
13095                                              SourceLocation LParenLoc,
13096                                              SourceLocation EndLoc) {
13097   OMPClause *Res = nullptr;
13098   switch (Kind) {
13099   case OMPC_final:
13100     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
13101     break;
13102   case OMPC_num_threads:
13103     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
13104     break;
13105   case OMPC_safelen:
13106     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
13107     break;
13108   case OMPC_simdlen:
13109     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
13110     break;
13111   case OMPC_allocator:
13112     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
13113     break;
13114   case OMPC_collapse:
13115     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
13116     break;
13117   case OMPC_ordered:
13118     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
13119     break;
13120   case OMPC_num_teams:
13121     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
13122     break;
13123   case OMPC_thread_limit:
13124     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
13125     break;
13126   case OMPC_priority:
13127     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
13128     break;
13129   case OMPC_grainsize:
13130     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
13131     break;
13132   case OMPC_num_tasks:
13133     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
13134     break;
13135   case OMPC_hint:
13136     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
13137     break;
13138   case OMPC_depobj:
13139     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
13140     break;
13141   case OMPC_detach:
13142     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
13143     break;
13144   case OMPC_novariants:
13145     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
13146     break;
13147   case OMPC_nocontext:
13148     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
13149     break;
13150   case OMPC_filter:
13151     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
13152     break;
13153   case OMPC_partial:
13154     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
13155     break;
13156   case OMPC_device:
13157   case OMPC_if:
13158   case OMPC_default:
13159   case OMPC_proc_bind:
13160   case OMPC_schedule:
13161   case OMPC_private:
13162   case OMPC_firstprivate:
13163   case OMPC_lastprivate:
13164   case OMPC_shared:
13165   case OMPC_reduction:
13166   case OMPC_task_reduction:
13167   case OMPC_in_reduction:
13168   case OMPC_linear:
13169   case OMPC_aligned:
13170   case OMPC_copyin:
13171   case OMPC_copyprivate:
13172   case OMPC_nowait:
13173   case OMPC_untied:
13174   case OMPC_mergeable:
13175   case OMPC_threadprivate:
13176   case OMPC_sizes:
13177   case OMPC_allocate:
13178   case OMPC_flush:
13179   case OMPC_read:
13180   case OMPC_write:
13181   case OMPC_update:
13182   case OMPC_capture:
13183   case OMPC_seq_cst:
13184   case OMPC_acq_rel:
13185   case OMPC_acquire:
13186   case OMPC_release:
13187   case OMPC_relaxed:
13188   case OMPC_depend:
13189   case OMPC_threads:
13190   case OMPC_simd:
13191   case OMPC_map:
13192   case OMPC_nogroup:
13193   case OMPC_dist_schedule:
13194   case OMPC_defaultmap:
13195   case OMPC_unknown:
13196   case OMPC_uniform:
13197   case OMPC_to:
13198   case OMPC_from:
13199   case OMPC_use_device_ptr:
13200   case OMPC_use_device_addr:
13201   case OMPC_is_device_ptr:
13202   case OMPC_unified_address:
13203   case OMPC_unified_shared_memory:
13204   case OMPC_reverse_offload:
13205   case OMPC_dynamic_allocators:
13206   case OMPC_atomic_default_mem_order:
13207   case OMPC_device_type:
13208   case OMPC_match:
13209   case OMPC_nontemporal:
13210   case OMPC_order:
13211   case OMPC_destroy:
13212   case OMPC_inclusive:
13213   case OMPC_exclusive:
13214   case OMPC_uses_allocators:
13215   case OMPC_affinity:
13216   default:
13217     llvm_unreachable("Clause is not allowed.");
13218   }
13219   return Res;
13220 }
13221 
13222 // An OpenMP directive such as 'target parallel' has two captured regions:
13223 // for the 'target' and 'parallel' respectively.  This function returns
13224 // the region in which to capture expressions associated with a clause.
13225 // A return value of OMPD_unknown signifies that the expression should not
13226 // be captured.
13227 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
13228     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
13229     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
13230   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13231   switch (CKind) {
13232   case OMPC_if:
13233     switch (DKind) {
13234     case OMPD_target_parallel_for_simd:
13235       if (OpenMPVersion >= 50 &&
13236           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13237         CaptureRegion = OMPD_parallel;
13238         break;
13239       }
13240       LLVM_FALLTHROUGH;
13241     case OMPD_target_parallel:
13242     case OMPD_target_parallel_for:
13243       // If this clause applies to the nested 'parallel' region, capture within
13244       // the 'target' region, otherwise do not capture.
13245       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13246         CaptureRegion = OMPD_target;
13247       break;
13248     case OMPD_target_teams_distribute_parallel_for_simd:
13249       if (OpenMPVersion >= 50 &&
13250           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13251         CaptureRegion = OMPD_parallel;
13252         break;
13253       }
13254       LLVM_FALLTHROUGH;
13255     case OMPD_target_teams_distribute_parallel_for:
13256       // If this clause applies to the nested 'parallel' region, capture within
13257       // the 'teams' region, otherwise do not capture.
13258       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13259         CaptureRegion = OMPD_teams;
13260       break;
13261     case OMPD_teams_distribute_parallel_for_simd:
13262       if (OpenMPVersion >= 50 &&
13263           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13264         CaptureRegion = OMPD_parallel;
13265         break;
13266       }
13267       LLVM_FALLTHROUGH;
13268     case OMPD_teams_distribute_parallel_for:
13269       CaptureRegion = OMPD_teams;
13270       break;
13271     case OMPD_target_update:
13272     case OMPD_target_enter_data:
13273     case OMPD_target_exit_data:
13274       CaptureRegion = OMPD_task;
13275       break;
13276     case OMPD_parallel_master_taskloop:
13277       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
13278         CaptureRegion = OMPD_parallel;
13279       break;
13280     case OMPD_parallel_master_taskloop_simd:
13281       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
13282           NameModifier == OMPD_taskloop) {
13283         CaptureRegion = OMPD_parallel;
13284         break;
13285       }
13286       if (OpenMPVersion <= 45)
13287         break;
13288       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13289         CaptureRegion = OMPD_taskloop;
13290       break;
13291     case OMPD_parallel_for_simd:
13292       if (OpenMPVersion <= 45)
13293         break;
13294       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13295         CaptureRegion = OMPD_parallel;
13296       break;
13297     case OMPD_taskloop_simd:
13298     case OMPD_master_taskloop_simd:
13299       if (OpenMPVersion <= 45)
13300         break;
13301       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13302         CaptureRegion = OMPD_taskloop;
13303       break;
13304     case OMPD_distribute_parallel_for_simd:
13305       if (OpenMPVersion <= 45)
13306         break;
13307       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13308         CaptureRegion = OMPD_parallel;
13309       break;
13310     case OMPD_target_simd:
13311       if (OpenMPVersion >= 50 &&
13312           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13313         CaptureRegion = OMPD_target;
13314       break;
13315     case OMPD_teams_distribute_simd:
13316     case OMPD_target_teams_distribute_simd:
13317       if (OpenMPVersion >= 50 &&
13318           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13319         CaptureRegion = OMPD_teams;
13320       break;
13321     case OMPD_cancel:
13322     case OMPD_parallel:
13323     case OMPD_parallel_master:
13324     case OMPD_parallel_sections:
13325     case OMPD_parallel_for:
13326     case OMPD_target:
13327     case OMPD_target_teams:
13328     case OMPD_target_teams_distribute:
13329     case OMPD_distribute_parallel_for:
13330     case OMPD_task:
13331     case OMPD_taskloop:
13332     case OMPD_master_taskloop:
13333     case OMPD_target_data:
13334     case OMPD_simd:
13335     case OMPD_for_simd:
13336     case OMPD_distribute_simd:
13337       // Do not capture if-clause expressions.
13338       break;
13339     case OMPD_threadprivate:
13340     case OMPD_allocate:
13341     case OMPD_taskyield:
13342     case OMPD_barrier:
13343     case OMPD_taskwait:
13344     case OMPD_cancellation_point:
13345     case OMPD_flush:
13346     case OMPD_depobj:
13347     case OMPD_scan:
13348     case OMPD_declare_reduction:
13349     case OMPD_declare_mapper:
13350     case OMPD_declare_simd:
13351     case OMPD_declare_variant:
13352     case OMPD_begin_declare_variant:
13353     case OMPD_end_declare_variant:
13354     case OMPD_declare_target:
13355     case OMPD_end_declare_target:
13356     case OMPD_teams:
13357     case OMPD_tile:
13358     case OMPD_unroll:
13359     case OMPD_for:
13360     case OMPD_sections:
13361     case OMPD_section:
13362     case OMPD_single:
13363     case OMPD_master:
13364     case OMPD_masked:
13365     case OMPD_critical:
13366     case OMPD_taskgroup:
13367     case OMPD_distribute:
13368     case OMPD_ordered:
13369     case OMPD_atomic:
13370     case OMPD_teams_distribute:
13371     case OMPD_requires:
13372       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13373     case OMPD_unknown:
13374     default:
13375       llvm_unreachable("Unknown OpenMP directive");
13376     }
13377     break;
13378   case OMPC_num_threads:
13379     switch (DKind) {
13380     case OMPD_target_parallel:
13381     case OMPD_target_parallel_for:
13382     case OMPD_target_parallel_for_simd:
13383       CaptureRegion = OMPD_target;
13384       break;
13385     case OMPD_teams_distribute_parallel_for:
13386     case OMPD_teams_distribute_parallel_for_simd:
13387     case OMPD_target_teams_distribute_parallel_for:
13388     case OMPD_target_teams_distribute_parallel_for_simd:
13389       CaptureRegion = OMPD_teams;
13390       break;
13391     case OMPD_parallel:
13392     case OMPD_parallel_master:
13393     case OMPD_parallel_sections:
13394     case OMPD_parallel_for:
13395     case OMPD_parallel_for_simd:
13396     case OMPD_distribute_parallel_for:
13397     case OMPD_distribute_parallel_for_simd:
13398     case OMPD_parallel_master_taskloop:
13399     case OMPD_parallel_master_taskloop_simd:
13400       // Do not capture num_threads-clause expressions.
13401       break;
13402     case OMPD_target_data:
13403     case OMPD_target_enter_data:
13404     case OMPD_target_exit_data:
13405     case OMPD_target_update:
13406     case OMPD_target:
13407     case OMPD_target_simd:
13408     case OMPD_target_teams:
13409     case OMPD_target_teams_distribute:
13410     case OMPD_target_teams_distribute_simd:
13411     case OMPD_cancel:
13412     case OMPD_task:
13413     case OMPD_taskloop:
13414     case OMPD_taskloop_simd:
13415     case OMPD_master_taskloop:
13416     case OMPD_master_taskloop_simd:
13417     case OMPD_threadprivate:
13418     case OMPD_allocate:
13419     case OMPD_taskyield:
13420     case OMPD_barrier:
13421     case OMPD_taskwait:
13422     case OMPD_cancellation_point:
13423     case OMPD_flush:
13424     case OMPD_depobj:
13425     case OMPD_scan:
13426     case OMPD_declare_reduction:
13427     case OMPD_declare_mapper:
13428     case OMPD_declare_simd:
13429     case OMPD_declare_variant:
13430     case OMPD_begin_declare_variant:
13431     case OMPD_end_declare_variant:
13432     case OMPD_declare_target:
13433     case OMPD_end_declare_target:
13434     case OMPD_teams:
13435     case OMPD_simd:
13436     case OMPD_tile:
13437     case OMPD_unroll:
13438     case OMPD_for:
13439     case OMPD_for_simd:
13440     case OMPD_sections:
13441     case OMPD_section:
13442     case OMPD_single:
13443     case OMPD_master:
13444     case OMPD_masked:
13445     case OMPD_critical:
13446     case OMPD_taskgroup:
13447     case OMPD_distribute:
13448     case OMPD_ordered:
13449     case OMPD_atomic:
13450     case OMPD_distribute_simd:
13451     case OMPD_teams_distribute:
13452     case OMPD_teams_distribute_simd:
13453     case OMPD_requires:
13454       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13455     case OMPD_unknown:
13456     default:
13457       llvm_unreachable("Unknown OpenMP directive");
13458     }
13459     break;
13460   case OMPC_num_teams:
13461     switch (DKind) {
13462     case OMPD_target_teams:
13463     case OMPD_target_teams_distribute:
13464     case OMPD_target_teams_distribute_simd:
13465     case OMPD_target_teams_distribute_parallel_for:
13466     case OMPD_target_teams_distribute_parallel_for_simd:
13467       CaptureRegion = OMPD_target;
13468       break;
13469     case OMPD_teams_distribute_parallel_for:
13470     case OMPD_teams_distribute_parallel_for_simd:
13471     case OMPD_teams:
13472     case OMPD_teams_distribute:
13473     case OMPD_teams_distribute_simd:
13474       // Do not capture num_teams-clause expressions.
13475       break;
13476     case OMPD_distribute_parallel_for:
13477     case OMPD_distribute_parallel_for_simd:
13478     case OMPD_task:
13479     case OMPD_taskloop:
13480     case OMPD_taskloop_simd:
13481     case OMPD_master_taskloop:
13482     case OMPD_master_taskloop_simd:
13483     case OMPD_parallel_master_taskloop:
13484     case OMPD_parallel_master_taskloop_simd:
13485     case OMPD_target_data:
13486     case OMPD_target_enter_data:
13487     case OMPD_target_exit_data:
13488     case OMPD_target_update:
13489     case OMPD_cancel:
13490     case OMPD_parallel:
13491     case OMPD_parallel_master:
13492     case OMPD_parallel_sections:
13493     case OMPD_parallel_for:
13494     case OMPD_parallel_for_simd:
13495     case OMPD_target:
13496     case OMPD_target_simd:
13497     case OMPD_target_parallel:
13498     case OMPD_target_parallel_for:
13499     case OMPD_target_parallel_for_simd:
13500     case OMPD_threadprivate:
13501     case OMPD_allocate:
13502     case OMPD_taskyield:
13503     case OMPD_barrier:
13504     case OMPD_taskwait:
13505     case OMPD_cancellation_point:
13506     case OMPD_flush:
13507     case OMPD_depobj:
13508     case OMPD_scan:
13509     case OMPD_declare_reduction:
13510     case OMPD_declare_mapper:
13511     case OMPD_declare_simd:
13512     case OMPD_declare_variant:
13513     case OMPD_begin_declare_variant:
13514     case OMPD_end_declare_variant:
13515     case OMPD_declare_target:
13516     case OMPD_end_declare_target:
13517     case OMPD_simd:
13518     case OMPD_tile:
13519     case OMPD_unroll:
13520     case OMPD_for:
13521     case OMPD_for_simd:
13522     case OMPD_sections:
13523     case OMPD_section:
13524     case OMPD_single:
13525     case OMPD_master:
13526     case OMPD_masked:
13527     case OMPD_critical:
13528     case OMPD_taskgroup:
13529     case OMPD_distribute:
13530     case OMPD_ordered:
13531     case OMPD_atomic:
13532     case OMPD_distribute_simd:
13533     case OMPD_requires:
13534       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13535     case OMPD_unknown:
13536     default:
13537       llvm_unreachable("Unknown OpenMP directive");
13538     }
13539     break;
13540   case OMPC_thread_limit:
13541     switch (DKind) {
13542     case OMPD_target_teams:
13543     case OMPD_target_teams_distribute:
13544     case OMPD_target_teams_distribute_simd:
13545     case OMPD_target_teams_distribute_parallel_for:
13546     case OMPD_target_teams_distribute_parallel_for_simd:
13547       CaptureRegion = OMPD_target;
13548       break;
13549     case OMPD_teams_distribute_parallel_for:
13550     case OMPD_teams_distribute_parallel_for_simd:
13551     case OMPD_teams:
13552     case OMPD_teams_distribute:
13553     case OMPD_teams_distribute_simd:
13554       // Do not capture thread_limit-clause expressions.
13555       break;
13556     case OMPD_distribute_parallel_for:
13557     case OMPD_distribute_parallel_for_simd:
13558     case OMPD_task:
13559     case OMPD_taskloop:
13560     case OMPD_taskloop_simd:
13561     case OMPD_master_taskloop:
13562     case OMPD_master_taskloop_simd:
13563     case OMPD_parallel_master_taskloop:
13564     case OMPD_parallel_master_taskloop_simd:
13565     case OMPD_target_data:
13566     case OMPD_target_enter_data:
13567     case OMPD_target_exit_data:
13568     case OMPD_target_update:
13569     case OMPD_cancel:
13570     case OMPD_parallel:
13571     case OMPD_parallel_master:
13572     case OMPD_parallel_sections:
13573     case OMPD_parallel_for:
13574     case OMPD_parallel_for_simd:
13575     case OMPD_target:
13576     case OMPD_target_simd:
13577     case OMPD_target_parallel:
13578     case OMPD_target_parallel_for:
13579     case OMPD_target_parallel_for_simd:
13580     case OMPD_threadprivate:
13581     case OMPD_allocate:
13582     case OMPD_taskyield:
13583     case OMPD_barrier:
13584     case OMPD_taskwait:
13585     case OMPD_cancellation_point:
13586     case OMPD_flush:
13587     case OMPD_depobj:
13588     case OMPD_scan:
13589     case OMPD_declare_reduction:
13590     case OMPD_declare_mapper:
13591     case OMPD_declare_simd:
13592     case OMPD_declare_variant:
13593     case OMPD_begin_declare_variant:
13594     case OMPD_end_declare_variant:
13595     case OMPD_declare_target:
13596     case OMPD_end_declare_target:
13597     case OMPD_simd:
13598     case OMPD_tile:
13599     case OMPD_unroll:
13600     case OMPD_for:
13601     case OMPD_for_simd:
13602     case OMPD_sections:
13603     case OMPD_section:
13604     case OMPD_single:
13605     case OMPD_master:
13606     case OMPD_masked:
13607     case OMPD_critical:
13608     case OMPD_taskgroup:
13609     case OMPD_distribute:
13610     case OMPD_ordered:
13611     case OMPD_atomic:
13612     case OMPD_distribute_simd:
13613     case OMPD_requires:
13614       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13615     case OMPD_unknown:
13616     default:
13617       llvm_unreachable("Unknown OpenMP directive");
13618     }
13619     break;
13620   case OMPC_schedule:
13621     switch (DKind) {
13622     case OMPD_parallel_for:
13623     case OMPD_parallel_for_simd:
13624     case OMPD_distribute_parallel_for:
13625     case OMPD_distribute_parallel_for_simd:
13626     case OMPD_teams_distribute_parallel_for:
13627     case OMPD_teams_distribute_parallel_for_simd:
13628     case OMPD_target_parallel_for:
13629     case OMPD_target_parallel_for_simd:
13630     case OMPD_target_teams_distribute_parallel_for:
13631     case OMPD_target_teams_distribute_parallel_for_simd:
13632       CaptureRegion = OMPD_parallel;
13633       break;
13634     case OMPD_for:
13635     case OMPD_for_simd:
13636       // Do not capture schedule-clause expressions.
13637       break;
13638     case OMPD_task:
13639     case OMPD_taskloop:
13640     case OMPD_taskloop_simd:
13641     case OMPD_master_taskloop:
13642     case OMPD_master_taskloop_simd:
13643     case OMPD_parallel_master_taskloop:
13644     case OMPD_parallel_master_taskloop_simd:
13645     case OMPD_target_data:
13646     case OMPD_target_enter_data:
13647     case OMPD_target_exit_data:
13648     case OMPD_target_update:
13649     case OMPD_teams:
13650     case OMPD_teams_distribute:
13651     case OMPD_teams_distribute_simd:
13652     case OMPD_target_teams_distribute:
13653     case OMPD_target_teams_distribute_simd:
13654     case OMPD_target:
13655     case OMPD_target_simd:
13656     case OMPD_target_parallel:
13657     case OMPD_cancel:
13658     case OMPD_parallel:
13659     case OMPD_parallel_master:
13660     case OMPD_parallel_sections:
13661     case OMPD_threadprivate:
13662     case OMPD_allocate:
13663     case OMPD_taskyield:
13664     case OMPD_barrier:
13665     case OMPD_taskwait:
13666     case OMPD_cancellation_point:
13667     case OMPD_flush:
13668     case OMPD_depobj:
13669     case OMPD_scan:
13670     case OMPD_declare_reduction:
13671     case OMPD_declare_mapper:
13672     case OMPD_declare_simd:
13673     case OMPD_declare_variant:
13674     case OMPD_begin_declare_variant:
13675     case OMPD_end_declare_variant:
13676     case OMPD_declare_target:
13677     case OMPD_end_declare_target:
13678     case OMPD_simd:
13679     case OMPD_tile:
13680     case OMPD_unroll:
13681     case OMPD_sections:
13682     case OMPD_section:
13683     case OMPD_single:
13684     case OMPD_master:
13685     case OMPD_masked:
13686     case OMPD_critical:
13687     case OMPD_taskgroup:
13688     case OMPD_distribute:
13689     case OMPD_ordered:
13690     case OMPD_atomic:
13691     case OMPD_distribute_simd:
13692     case OMPD_target_teams:
13693     case OMPD_requires:
13694       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13695     case OMPD_unknown:
13696     default:
13697       llvm_unreachable("Unknown OpenMP directive");
13698     }
13699     break;
13700   case OMPC_dist_schedule:
13701     switch (DKind) {
13702     case OMPD_teams_distribute_parallel_for:
13703     case OMPD_teams_distribute_parallel_for_simd:
13704     case OMPD_teams_distribute:
13705     case OMPD_teams_distribute_simd:
13706     case OMPD_target_teams_distribute_parallel_for:
13707     case OMPD_target_teams_distribute_parallel_for_simd:
13708     case OMPD_target_teams_distribute:
13709     case OMPD_target_teams_distribute_simd:
13710       CaptureRegion = OMPD_teams;
13711       break;
13712     case OMPD_distribute_parallel_for:
13713     case OMPD_distribute_parallel_for_simd:
13714     case OMPD_distribute:
13715     case OMPD_distribute_simd:
13716       // Do not capture dist_schedule-clause expressions.
13717       break;
13718     case OMPD_parallel_for:
13719     case OMPD_parallel_for_simd:
13720     case OMPD_target_parallel_for_simd:
13721     case OMPD_target_parallel_for:
13722     case OMPD_task:
13723     case OMPD_taskloop:
13724     case OMPD_taskloop_simd:
13725     case OMPD_master_taskloop:
13726     case OMPD_master_taskloop_simd:
13727     case OMPD_parallel_master_taskloop:
13728     case OMPD_parallel_master_taskloop_simd:
13729     case OMPD_target_data:
13730     case OMPD_target_enter_data:
13731     case OMPD_target_exit_data:
13732     case OMPD_target_update:
13733     case OMPD_teams:
13734     case OMPD_target:
13735     case OMPD_target_simd:
13736     case OMPD_target_parallel:
13737     case OMPD_cancel:
13738     case OMPD_parallel:
13739     case OMPD_parallel_master:
13740     case OMPD_parallel_sections:
13741     case OMPD_threadprivate:
13742     case OMPD_allocate:
13743     case OMPD_taskyield:
13744     case OMPD_barrier:
13745     case OMPD_taskwait:
13746     case OMPD_cancellation_point:
13747     case OMPD_flush:
13748     case OMPD_depobj:
13749     case OMPD_scan:
13750     case OMPD_declare_reduction:
13751     case OMPD_declare_mapper:
13752     case OMPD_declare_simd:
13753     case OMPD_declare_variant:
13754     case OMPD_begin_declare_variant:
13755     case OMPD_end_declare_variant:
13756     case OMPD_declare_target:
13757     case OMPD_end_declare_target:
13758     case OMPD_simd:
13759     case OMPD_tile:
13760     case OMPD_unroll:
13761     case OMPD_for:
13762     case OMPD_for_simd:
13763     case OMPD_sections:
13764     case OMPD_section:
13765     case OMPD_single:
13766     case OMPD_master:
13767     case OMPD_masked:
13768     case OMPD_critical:
13769     case OMPD_taskgroup:
13770     case OMPD_ordered:
13771     case OMPD_atomic:
13772     case OMPD_target_teams:
13773     case OMPD_requires:
13774       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
13775     case OMPD_unknown:
13776     default:
13777       llvm_unreachable("Unknown OpenMP directive");
13778     }
13779     break;
13780   case OMPC_device:
13781     switch (DKind) {
13782     case OMPD_target_update:
13783     case OMPD_target_enter_data:
13784     case OMPD_target_exit_data:
13785     case OMPD_target:
13786     case OMPD_target_simd:
13787     case OMPD_target_teams:
13788     case OMPD_target_parallel:
13789     case OMPD_target_teams_distribute:
13790     case OMPD_target_teams_distribute_simd:
13791     case OMPD_target_parallel_for:
13792     case OMPD_target_parallel_for_simd:
13793     case OMPD_target_teams_distribute_parallel_for:
13794     case OMPD_target_teams_distribute_parallel_for_simd:
13795     case OMPD_dispatch:
13796       CaptureRegion = OMPD_task;
13797       break;
13798     case OMPD_target_data:
13799     case OMPD_interop:
13800       // Do not capture device-clause expressions.
13801       break;
13802     case OMPD_teams_distribute_parallel_for:
13803     case OMPD_teams_distribute_parallel_for_simd:
13804     case OMPD_teams:
13805     case OMPD_teams_distribute:
13806     case OMPD_teams_distribute_simd:
13807     case OMPD_distribute_parallel_for:
13808     case OMPD_distribute_parallel_for_simd:
13809     case OMPD_task:
13810     case OMPD_taskloop:
13811     case OMPD_taskloop_simd:
13812     case OMPD_master_taskloop:
13813     case OMPD_master_taskloop_simd:
13814     case OMPD_parallel_master_taskloop:
13815     case OMPD_parallel_master_taskloop_simd:
13816     case OMPD_cancel:
13817     case OMPD_parallel:
13818     case OMPD_parallel_master:
13819     case OMPD_parallel_sections:
13820     case OMPD_parallel_for:
13821     case OMPD_parallel_for_simd:
13822     case OMPD_threadprivate:
13823     case OMPD_allocate:
13824     case OMPD_taskyield:
13825     case OMPD_barrier:
13826     case OMPD_taskwait:
13827     case OMPD_cancellation_point:
13828     case OMPD_flush:
13829     case OMPD_depobj:
13830     case OMPD_scan:
13831     case OMPD_declare_reduction:
13832     case OMPD_declare_mapper:
13833     case OMPD_declare_simd:
13834     case OMPD_declare_variant:
13835     case OMPD_begin_declare_variant:
13836     case OMPD_end_declare_variant:
13837     case OMPD_declare_target:
13838     case OMPD_end_declare_target:
13839     case OMPD_simd:
13840     case OMPD_tile:
13841     case OMPD_unroll:
13842     case OMPD_for:
13843     case OMPD_for_simd:
13844     case OMPD_sections:
13845     case OMPD_section:
13846     case OMPD_single:
13847     case OMPD_master:
13848     case OMPD_masked:
13849     case OMPD_critical:
13850     case OMPD_taskgroup:
13851     case OMPD_distribute:
13852     case OMPD_ordered:
13853     case OMPD_atomic:
13854     case OMPD_distribute_simd:
13855     case OMPD_requires:
13856       llvm_unreachable("Unexpected OpenMP directive with device-clause");
13857     case OMPD_unknown:
13858     default:
13859       llvm_unreachable("Unknown OpenMP directive");
13860     }
13861     break;
13862   case OMPC_grainsize:
13863   case OMPC_num_tasks:
13864   case OMPC_final:
13865   case OMPC_priority:
13866     switch (DKind) {
13867     case OMPD_task:
13868     case OMPD_taskloop:
13869     case OMPD_taskloop_simd:
13870     case OMPD_master_taskloop:
13871     case OMPD_master_taskloop_simd:
13872       break;
13873     case OMPD_parallel_master_taskloop:
13874     case OMPD_parallel_master_taskloop_simd:
13875       CaptureRegion = OMPD_parallel;
13876       break;
13877     case OMPD_target_update:
13878     case OMPD_target_enter_data:
13879     case OMPD_target_exit_data:
13880     case OMPD_target:
13881     case OMPD_target_simd:
13882     case OMPD_target_teams:
13883     case OMPD_target_parallel:
13884     case OMPD_target_teams_distribute:
13885     case OMPD_target_teams_distribute_simd:
13886     case OMPD_target_parallel_for:
13887     case OMPD_target_parallel_for_simd:
13888     case OMPD_target_teams_distribute_parallel_for:
13889     case OMPD_target_teams_distribute_parallel_for_simd:
13890     case OMPD_target_data:
13891     case OMPD_teams_distribute_parallel_for:
13892     case OMPD_teams_distribute_parallel_for_simd:
13893     case OMPD_teams:
13894     case OMPD_teams_distribute:
13895     case OMPD_teams_distribute_simd:
13896     case OMPD_distribute_parallel_for:
13897     case OMPD_distribute_parallel_for_simd:
13898     case OMPD_cancel:
13899     case OMPD_parallel:
13900     case OMPD_parallel_master:
13901     case OMPD_parallel_sections:
13902     case OMPD_parallel_for:
13903     case OMPD_parallel_for_simd:
13904     case OMPD_threadprivate:
13905     case OMPD_allocate:
13906     case OMPD_taskyield:
13907     case OMPD_barrier:
13908     case OMPD_taskwait:
13909     case OMPD_cancellation_point:
13910     case OMPD_flush:
13911     case OMPD_depobj:
13912     case OMPD_scan:
13913     case OMPD_declare_reduction:
13914     case OMPD_declare_mapper:
13915     case OMPD_declare_simd:
13916     case OMPD_declare_variant:
13917     case OMPD_begin_declare_variant:
13918     case OMPD_end_declare_variant:
13919     case OMPD_declare_target:
13920     case OMPD_end_declare_target:
13921     case OMPD_simd:
13922     case OMPD_tile:
13923     case OMPD_unroll:
13924     case OMPD_for:
13925     case OMPD_for_simd:
13926     case OMPD_sections:
13927     case OMPD_section:
13928     case OMPD_single:
13929     case OMPD_master:
13930     case OMPD_masked:
13931     case OMPD_critical:
13932     case OMPD_taskgroup:
13933     case OMPD_distribute:
13934     case OMPD_ordered:
13935     case OMPD_atomic:
13936     case OMPD_distribute_simd:
13937     case OMPD_requires:
13938       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
13939     case OMPD_unknown:
13940     default:
13941       llvm_unreachable("Unknown OpenMP directive");
13942     }
13943     break;
13944   case OMPC_novariants:
13945   case OMPC_nocontext:
13946     switch (DKind) {
13947     case OMPD_dispatch:
13948       CaptureRegion = OMPD_task;
13949       break;
13950     default:
13951       llvm_unreachable("Unexpected OpenMP directive");
13952     }
13953     break;
13954   case OMPC_filter:
13955     // Do not capture filter-clause expressions.
13956     break;
13957   case OMPC_firstprivate:
13958   case OMPC_lastprivate:
13959   case OMPC_reduction:
13960   case OMPC_task_reduction:
13961   case OMPC_in_reduction:
13962   case OMPC_linear:
13963   case OMPC_default:
13964   case OMPC_proc_bind:
13965   case OMPC_safelen:
13966   case OMPC_simdlen:
13967   case OMPC_sizes:
13968   case OMPC_allocator:
13969   case OMPC_collapse:
13970   case OMPC_private:
13971   case OMPC_shared:
13972   case OMPC_aligned:
13973   case OMPC_copyin:
13974   case OMPC_copyprivate:
13975   case OMPC_ordered:
13976   case OMPC_nowait:
13977   case OMPC_untied:
13978   case OMPC_mergeable:
13979   case OMPC_threadprivate:
13980   case OMPC_allocate:
13981   case OMPC_flush:
13982   case OMPC_depobj:
13983   case OMPC_read:
13984   case OMPC_write:
13985   case OMPC_update:
13986   case OMPC_capture:
13987   case OMPC_seq_cst:
13988   case OMPC_acq_rel:
13989   case OMPC_acquire:
13990   case OMPC_release:
13991   case OMPC_relaxed:
13992   case OMPC_depend:
13993   case OMPC_threads:
13994   case OMPC_simd:
13995   case OMPC_map:
13996   case OMPC_nogroup:
13997   case OMPC_hint:
13998   case OMPC_defaultmap:
13999   case OMPC_unknown:
14000   case OMPC_uniform:
14001   case OMPC_to:
14002   case OMPC_from:
14003   case OMPC_use_device_ptr:
14004   case OMPC_use_device_addr:
14005   case OMPC_is_device_ptr:
14006   case OMPC_unified_address:
14007   case OMPC_unified_shared_memory:
14008   case OMPC_reverse_offload:
14009   case OMPC_dynamic_allocators:
14010   case OMPC_atomic_default_mem_order:
14011   case OMPC_device_type:
14012   case OMPC_match:
14013   case OMPC_nontemporal:
14014   case OMPC_order:
14015   case OMPC_destroy:
14016   case OMPC_detach:
14017   case OMPC_inclusive:
14018   case OMPC_exclusive:
14019   case OMPC_uses_allocators:
14020   case OMPC_affinity:
14021   default:
14022     llvm_unreachable("Unexpected OpenMP clause.");
14023   }
14024   return CaptureRegion;
14025 }
14026 
14027 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
14028                                      Expr *Condition, SourceLocation StartLoc,
14029                                      SourceLocation LParenLoc,
14030                                      SourceLocation NameModifierLoc,
14031                                      SourceLocation ColonLoc,
14032                                      SourceLocation EndLoc) {
14033   Expr *ValExpr = Condition;
14034   Stmt *HelperValStmt = nullptr;
14035   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14036   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14037       !Condition->isInstantiationDependent() &&
14038       !Condition->containsUnexpandedParameterPack()) {
14039     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14040     if (Val.isInvalid())
14041       return nullptr;
14042 
14043     ValExpr = Val.get();
14044 
14045     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14046     CaptureRegion = getOpenMPCaptureRegionForClause(
14047         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
14048     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14049       ValExpr = MakeFullExpr(ValExpr).get();
14050       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14051       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14052       HelperValStmt = buildPreInits(Context, Captures);
14053     }
14054   }
14055 
14056   return new (Context)
14057       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
14058                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
14059 }
14060 
14061 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
14062                                         SourceLocation StartLoc,
14063                                         SourceLocation LParenLoc,
14064                                         SourceLocation EndLoc) {
14065   Expr *ValExpr = Condition;
14066   Stmt *HelperValStmt = nullptr;
14067   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14068   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14069       !Condition->isInstantiationDependent() &&
14070       !Condition->containsUnexpandedParameterPack()) {
14071     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14072     if (Val.isInvalid())
14073       return nullptr;
14074 
14075     ValExpr = MakeFullExpr(Val.get()).get();
14076 
14077     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14078     CaptureRegion =
14079         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
14080     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14081       ValExpr = MakeFullExpr(ValExpr).get();
14082       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14083       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14084       HelperValStmt = buildPreInits(Context, Captures);
14085     }
14086   }
14087 
14088   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
14089                                       StartLoc, LParenLoc, EndLoc);
14090 }
14091 
14092 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
14093                                                         Expr *Op) {
14094   if (!Op)
14095     return ExprError();
14096 
14097   class IntConvertDiagnoser : public ICEConvertDiagnoser {
14098   public:
14099     IntConvertDiagnoser()
14100         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
14101     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14102                                          QualType T) override {
14103       return S.Diag(Loc, diag::err_omp_not_integral) << T;
14104     }
14105     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
14106                                              QualType T) override {
14107       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
14108     }
14109     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
14110                                                QualType T,
14111                                                QualType ConvTy) override {
14112       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
14113     }
14114     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
14115                                            QualType ConvTy) override {
14116       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14117              << ConvTy->isEnumeralType() << ConvTy;
14118     }
14119     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
14120                                             QualType T) override {
14121       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
14122     }
14123     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
14124                                         QualType ConvTy) override {
14125       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14126              << ConvTy->isEnumeralType() << ConvTy;
14127     }
14128     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
14129                                              QualType) override {
14130       llvm_unreachable("conversion functions are permitted");
14131     }
14132   } ConvertDiagnoser;
14133   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
14134 }
14135 
14136 static bool
14137 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
14138                           bool StrictlyPositive, bool BuildCapture = false,
14139                           OpenMPDirectiveKind DKind = OMPD_unknown,
14140                           OpenMPDirectiveKind *CaptureRegion = nullptr,
14141                           Stmt **HelperValStmt = nullptr) {
14142   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
14143       !ValExpr->isInstantiationDependent()) {
14144     SourceLocation Loc = ValExpr->getExprLoc();
14145     ExprResult Value =
14146         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
14147     if (Value.isInvalid())
14148       return false;
14149 
14150     ValExpr = Value.get();
14151     // The expression must evaluate to a non-negative integer value.
14152     if (Optional<llvm::APSInt> Result =
14153             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
14154       if (Result->isSigned() &&
14155           !((!StrictlyPositive && Result->isNonNegative()) ||
14156             (StrictlyPositive && Result->isStrictlyPositive()))) {
14157         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
14158             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14159             << ValExpr->getSourceRange();
14160         return false;
14161       }
14162     }
14163     if (!BuildCapture)
14164       return true;
14165     *CaptureRegion =
14166         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
14167     if (*CaptureRegion != OMPD_unknown &&
14168         !SemaRef.CurContext->isDependentContext()) {
14169       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
14170       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14171       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
14172       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
14173     }
14174   }
14175   return true;
14176 }
14177 
14178 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
14179                                              SourceLocation StartLoc,
14180                                              SourceLocation LParenLoc,
14181                                              SourceLocation EndLoc) {
14182   Expr *ValExpr = NumThreads;
14183   Stmt *HelperValStmt = nullptr;
14184 
14185   // OpenMP [2.5, Restrictions]
14186   //  The num_threads expression must evaluate to a positive integer value.
14187   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
14188                                  /*StrictlyPositive=*/true))
14189     return nullptr;
14190 
14191   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14192   OpenMPDirectiveKind CaptureRegion =
14193       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
14194   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14195     ValExpr = MakeFullExpr(ValExpr).get();
14196     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14197     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14198     HelperValStmt = buildPreInits(Context, Captures);
14199   }
14200 
14201   return new (Context) OMPNumThreadsClause(
14202       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14203 }
14204 
14205 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
14206                                                        OpenMPClauseKind CKind,
14207                                                        bool StrictlyPositive,
14208                                                        bool SuppressExprDiags) {
14209   if (!E)
14210     return ExprError();
14211   if (E->isValueDependent() || E->isTypeDependent() ||
14212       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14213     return E;
14214 
14215   llvm::APSInt Result;
14216   ExprResult ICE;
14217   if (SuppressExprDiags) {
14218     // Use a custom diagnoser that suppresses 'note' diagnostics about the
14219     // expression.
14220     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
14221       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
14222       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
14223                                                  SourceLocation Loc) override {
14224         llvm_unreachable("Diagnostic suppressed");
14225       }
14226     } Diagnoser;
14227     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
14228   } else {
14229     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
14230   }
14231   if (ICE.isInvalid())
14232     return ExprError();
14233 
14234   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
14235       (!StrictlyPositive && !Result.isNonNegative())) {
14236     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
14237         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14238         << E->getSourceRange();
14239     return ExprError();
14240   }
14241   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
14242     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
14243         << E->getSourceRange();
14244     return ExprError();
14245   }
14246   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
14247     DSAStack->setAssociatedLoops(Result.getExtValue());
14248   else if (CKind == OMPC_ordered)
14249     DSAStack->setAssociatedLoops(Result.getExtValue());
14250   return ICE;
14251 }
14252 
14253 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
14254                                           SourceLocation LParenLoc,
14255                                           SourceLocation EndLoc) {
14256   // OpenMP [2.8.1, simd construct, Description]
14257   // The parameter of the safelen clause must be a constant
14258   // positive integer expression.
14259   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
14260   if (Safelen.isInvalid())
14261     return nullptr;
14262   return new (Context)
14263       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
14264 }
14265 
14266 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
14267                                           SourceLocation LParenLoc,
14268                                           SourceLocation EndLoc) {
14269   // OpenMP [2.8.1, simd construct, Description]
14270   // The parameter of the simdlen clause must be a constant
14271   // positive integer expression.
14272   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
14273   if (Simdlen.isInvalid())
14274     return nullptr;
14275   return new (Context)
14276       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
14277 }
14278 
14279 /// Tries to find omp_allocator_handle_t type.
14280 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
14281                                     DSAStackTy *Stack) {
14282   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
14283   if (!OMPAllocatorHandleT.isNull())
14284     return true;
14285   // Build the predefined allocator expressions.
14286   bool ErrorFound = false;
14287   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
14288     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
14289     StringRef Allocator =
14290         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
14291     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
14292     auto *VD = dyn_cast_or_null<ValueDecl>(
14293         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
14294     if (!VD) {
14295       ErrorFound = true;
14296       break;
14297     }
14298     QualType AllocatorType =
14299         VD->getType().getNonLValueExprType(S.getASTContext());
14300     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
14301     if (!Res.isUsable()) {
14302       ErrorFound = true;
14303       break;
14304     }
14305     if (OMPAllocatorHandleT.isNull())
14306       OMPAllocatorHandleT = AllocatorType;
14307     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
14308       ErrorFound = true;
14309       break;
14310     }
14311     Stack->setAllocator(AllocatorKind, Res.get());
14312   }
14313   if (ErrorFound) {
14314     S.Diag(Loc, diag::err_omp_implied_type_not_found)
14315         << "omp_allocator_handle_t";
14316     return false;
14317   }
14318   OMPAllocatorHandleT.addConst();
14319   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
14320   return true;
14321 }
14322 
14323 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
14324                                             SourceLocation LParenLoc,
14325                                             SourceLocation EndLoc) {
14326   // OpenMP [2.11.3, allocate Directive, Description]
14327   // allocator is an expression of omp_allocator_handle_t type.
14328   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
14329     return nullptr;
14330 
14331   ExprResult Allocator = DefaultLvalueConversion(A);
14332   if (Allocator.isInvalid())
14333     return nullptr;
14334   Allocator = PerformImplicitConversion(Allocator.get(),
14335                                         DSAStack->getOMPAllocatorHandleT(),
14336                                         Sema::AA_Initializing,
14337                                         /*AllowExplicit=*/true);
14338   if (Allocator.isInvalid())
14339     return nullptr;
14340   return new (Context)
14341       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
14342 }
14343 
14344 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
14345                                            SourceLocation StartLoc,
14346                                            SourceLocation LParenLoc,
14347                                            SourceLocation EndLoc) {
14348   // OpenMP [2.7.1, loop construct, Description]
14349   // OpenMP [2.8.1, simd construct, Description]
14350   // OpenMP [2.9.6, distribute construct, Description]
14351   // The parameter of the collapse clause must be a constant
14352   // positive integer expression.
14353   ExprResult NumForLoopsResult =
14354       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
14355   if (NumForLoopsResult.isInvalid())
14356     return nullptr;
14357   return new (Context)
14358       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
14359 }
14360 
14361 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
14362                                           SourceLocation EndLoc,
14363                                           SourceLocation LParenLoc,
14364                                           Expr *NumForLoops) {
14365   // OpenMP [2.7.1, loop construct, Description]
14366   // OpenMP [2.8.1, simd construct, Description]
14367   // OpenMP [2.9.6, distribute construct, Description]
14368   // The parameter of the ordered clause must be a constant
14369   // positive integer expression if any.
14370   if (NumForLoops && LParenLoc.isValid()) {
14371     ExprResult NumForLoopsResult =
14372         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
14373     if (NumForLoopsResult.isInvalid())
14374       return nullptr;
14375     NumForLoops = NumForLoopsResult.get();
14376   } else {
14377     NumForLoops = nullptr;
14378   }
14379   auto *Clause = OMPOrderedClause::Create(
14380       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
14381       StartLoc, LParenLoc, EndLoc);
14382   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
14383   return Clause;
14384 }
14385 
14386 OMPClause *Sema::ActOnOpenMPSimpleClause(
14387     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
14388     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14389   OMPClause *Res = nullptr;
14390   switch (Kind) {
14391   case OMPC_default:
14392     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
14393                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14394     break;
14395   case OMPC_proc_bind:
14396     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14397                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14398     break;
14399   case OMPC_atomic_default_mem_order:
14400     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14401         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14402         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14403     break;
14404   case OMPC_order:
14405     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14406                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14407     break;
14408   case OMPC_update:
14409     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14410                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14411     break;
14412   case OMPC_if:
14413   case OMPC_final:
14414   case OMPC_num_threads:
14415   case OMPC_safelen:
14416   case OMPC_simdlen:
14417   case OMPC_sizes:
14418   case OMPC_allocator:
14419   case OMPC_collapse:
14420   case OMPC_schedule:
14421   case OMPC_private:
14422   case OMPC_firstprivate:
14423   case OMPC_lastprivate:
14424   case OMPC_shared:
14425   case OMPC_reduction:
14426   case OMPC_task_reduction:
14427   case OMPC_in_reduction:
14428   case OMPC_linear:
14429   case OMPC_aligned:
14430   case OMPC_copyin:
14431   case OMPC_copyprivate:
14432   case OMPC_ordered:
14433   case OMPC_nowait:
14434   case OMPC_untied:
14435   case OMPC_mergeable:
14436   case OMPC_threadprivate:
14437   case OMPC_allocate:
14438   case OMPC_flush:
14439   case OMPC_depobj:
14440   case OMPC_read:
14441   case OMPC_write:
14442   case OMPC_capture:
14443   case OMPC_seq_cst:
14444   case OMPC_acq_rel:
14445   case OMPC_acquire:
14446   case OMPC_release:
14447   case OMPC_relaxed:
14448   case OMPC_depend:
14449   case OMPC_device:
14450   case OMPC_threads:
14451   case OMPC_simd:
14452   case OMPC_map:
14453   case OMPC_num_teams:
14454   case OMPC_thread_limit:
14455   case OMPC_priority:
14456   case OMPC_grainsize:
14457   case OMPC_nogroup:
14458   case OMPC_num_tasks:
14459   case OMPC_hint:
14460   case OMPC_dist_schedule:
14461   case OMPC_defaultmap:
14462   case OMPC_unknown:
14463   case OMPC_uniform:
14464   case OMPC_to:
14465   case OMPC_from:
14466   case OMPC_use_device_ptr:
14467   case OMPC_use_device_addr:
14468   case OMPC_is_device_ptr:
14469   case OMPC_unified_address:
14470   case OMPC_unified_shared_memory:
14471   case OMPC_reverse_offload:
14472   case OMPC_dynamic_allocators:
14473   case OMPC_device_type:
14474   case OMPC_match:
14475   case OMPC_nontemporal:
14476   case OMPC_destroy:
14477   case OMPC_novariants:
14478   case OMPC_nocontext:
14479   case OMPC_detach:
14480   case OMPC_inclusive:
14481   case OMPC_exclusive:
14482   case OMPC_uses_allocators:
14483   case OMPC_affinity:
14484   default:
14485     llvm_unreachable("Clause is not allowed.");
14486   }
14487   return Res;
14488 }
14489 
14490 static std::string
14491 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14492                         ArrayRef<unsigned> Exclude = llvm::None) {
14493   SmallString<256> Buffer;
14494   llvm::raw_svector_ostream Out(Buffer);
14495   unsigned Skipped = Exclude.size();
14496   auto S = Exclude.begin(), E = Exclude.end();
14497   for (unsigned I = First; I < Last; ++I) {
14498     if (std::find(S, E, I) != E) {
14499       --Skipped;
14500       continue;
14501     }
14502     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14503     if (I + Skipped + 2 == Last)
14504       Out << " or ";
14505     else if (I + Skipped + 1 != Last)
14506       Out << ", ";
14507   }
14508   return std::string(Out.str());
14509 }
14510 
14511 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14512                                           SourceLocation KindKwLoc,
14513                                           SourceLocation StartLoc,
14514                                           SourceLocation LParenLoc,
14515                                           SourceLocation EndLoc) {
14516   if (Kind == OMP_DEFAULT_unknown) {
14517     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14518         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14519                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14520         << getOpenMPClauseName(OMPC_default);
14521     return nullptr;
14522   }
14523 
14524   switch (Kind) {
14525   case OMP_DEFAULT_none:
14526     DSAStack->setDefaultDSANone(KindKwLoc);
14527     break;
14528   case OMP_DEFAULT_shared:
14529     DSAStack->setDefaultDSAShared(KindKwLoc);
14530     break;
14531   case OMP_DEFAULT_firstprivate:
14532     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14533     break;
14534   default:
14535     llvm_unreachable("DSA unexpected in OpenMP default clause");
14536   }
14537 
14538   return new (Context)
14539       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14540 }
14541 
14542 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14543                                            SourceLocation KindKwLoc,
14544                                            SourceLocation StartLoc,
14545                                            SourceLocation LParenLoc,
14546                                            SourceLocation EndLoc) {
14547   if (Kind == OMP_PROC_BIND_unknown) {
14548     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14549         << getListOfPossibleValues(OMPC_proc_bind,
14550                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14551                                    /*Last=*/
14552                                    unsigned(LangOpts.OpenMP > 50
14553                                                 ? OMP_PROC_BIND_primary
14554                                                 : OMP_PROC_BIND_spread) +
14555                                        1)
14556         << getOpenMPClauseName(OMPC_proc_bind);
14557     return nullptr;
14558   }
14559   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14560     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14561         << getListOfPossibleValues(OMPC_proc_bind,
14562                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14563                                    /*Last=*/
14564                                    unsigned(OMP_PROC_BIND_spread) + 1)
14565         << getOpenMPClauseName(OMPC_proc_bind);
14566   return new (Context)
14567       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14568 }
14569 
14570 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14571     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14572     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14573   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14574     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14575         << getListOfPossibleValues(
14576                OMPC_atomic_default_mem_order, /*First=*/0,
14577                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14578         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14579     return nullptr;
14580   }
14581   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14582                                                       LParenLoc, EndLoc);
14583 }
14584 
14585 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14586                                         SourceLocation KindKwLoc,
14587                                         SourceLocation StartLoc,
14588                                         SourceLocation LParenLoc,
14589                                         SourceLocation EndLoc) {
14590   if (Kind == OMPC_ORDER_unknown) {
14591     static_assert(OMPC_ORDER_unknown > 0,
14592                   "OMPC_ORDER_unknown not greater than 0");
14593     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14594         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14595                                    /*Last=*/OMPC_ORDER_unknown)
14596         << getOpenMPClauseName(OMPC_order);
14597     return nullptr;
14598   }
14599   return new (Context)
14600       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14601 }
14602 
14603 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14604                                          SourceLocation KindKwLoc,
14605                                          SourceLocation StartLoc,
14606                                          SourceLocation LParenLoc,
14607                                          SourceLocation EndLoc) {
14608   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14609       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14610     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14611                          OMPC_DEPEND_depobj};
14612     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14613         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14614                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14615         << getOpenMPClauseName(OMPC_update);
14616     return nullptr;
14617   }
14618   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14619                                  EndLoc);
14620 }
14621 
14622 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14623                                         SourceLocation StartLoc,
14624                                         SourceLocation LParenLoc,
14625                                         SourceLocation EndLoc) {
14626   for (Expr *SizeExpr : SizeExprs) {
14627     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14628         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14629     if (!NumForLoopsResult.isUsable())
14630       return nullptr;
14631   }
14632 
14633   DSAStack->setAssociatedLoops(SizeExprs.size());
14634   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14635                                 SizeExprs);
14636 }
14637 
14638 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
14639                                        SourceLocation EndLoc) {
14640   return OMPFullClause::Create(Context, StartLoc, EndLoc);
14641 }
14642 
14643 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
14644                                           SourceLocation StartLoc,
14645                                           SourceLocation LParenLoc,
14646                                           SourceLocation EndLoc) {
14647   if (FactorExpr) {
14648     // If an argument is specified, it must be a constant (or an unevaluated
14649     // template expression).
14650     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
14651         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
14652     if (FactorResult.isInvalid())
14653       return nullptr;
14654     FactorExpr = FactorResult.get();
14655   }
14656 
14657   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14658                                   FactorExpr);
14659 }
14660 
14661 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14662     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14663     SourceLocation StartLoc, SourceLocation LParenLoc,
14664     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
14665     SourceLocation EndLoc) {
14666   OMPClause *Res = nullptr;
14667   switch (Kind) {
14668   case OMPC_schedule:
14669     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
14670     assert(Argument.size() == NumberOfElements &&
14671            ArgumentLoc.size() == NumberOfElements);
14672     Res = ActOnOpenMPScheduleClause(
14673         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
14674         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
14675         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
14676         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
14677         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
14678     break;
14679   case OMPC_if:
14680     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14681     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
14682                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
14683                               DelimLoc, EndLoc);
14684     break;
14685   case OMPC_dist_schedule:
14686     Res = ActOnOpenMPDistScheduleClause(
14687         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
14688         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
14689     break;
14690   case OMPC_defaultmap:
14691     enum { Modifier, DefaultmapKind };
14692     Res = ActOnOpenMPDefaultmapClause(
14693         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
14694         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
14695         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
14696         EndLoc);
14697     break;
14698   case OMPC_device:
14699     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14700     Res = ActOnOpenMPDeviceClause(
14701         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
14702         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
14703     break;
14704   case OMPC_final:
14705   case OMPC_num_threads:
14706   case OMPC_safelen:
14707   case OMPC_simdlen:
14708   case OMPC_sizes:
14709   case OMPC_allocator:
14710   case OMPC_collapse:
14711   case OMPC_default:
14712   case OMPC_proc_bind:
14713   case OMPC_private:
14714   case OMPC_firstprivate:
14715   case OMPC_lastprivate:
14716   case OMPC_shared:
14717   case OMPC_reduction:
14718   case OMPC_task_reduction:
14719   case OMPC_in_reduction:
14720   case OMPC_linear:
14721   case OMPC_aligned:
14722   case OMPC_copyin:
14723   case OMPC_copyprivate:
14724   case OMPC_ordered:
14725   case OMPC_nowait:
14726   case OMPC_untied:
14727   case OMPC_mergeable:
14728   case OMPC_threadprivate:
14729   case OMPC_allocate:
14730   case OMPC_flush:
14731   case OMPC_depobj:
14732   case OMPC_read:
14733   case OMPC_write:
14734   case OMPC_update:
14735   case OMPC_capture:
14736   case OMPC_seq_cst:
14737   case OMPC_acq_rel:
14738   case OMPC_acquire:
14739   case OMPC_release:
14740   case OMPC_relaxed:
14741   case OMPC_depend:
14742   case OMPC_threads:
14743   case OMPC_simd:
14744   case OMPC_map:
14745   case OMPC_num_teams:
14746   case OMPC_thread_limit:
14747   case OMPC_priority:
14748   case OMPC_grainsize:
14749   case OMPC_nogroup:
14750   case OMPC_num_tasks:
14751   case OMPC_hint:
14752   case OMPC_unknown:
14753   case OMPC_uniform:
14754   case OMPC_to:
14755   case OMPC_from:
14756   case OMPC_use_device_ptr:
14757   case OMPC_use_device_addr:
14758   case OMPC_is_device_ptr:
14759   case OMPC_unified_address:
14760   case OMPC_unified_shared_memory:
14761   case OMPC_reverse_offload:
14762   case OMPC_dynamic_allocators:
14763   case OMPC_atomic_default_mem_order:
14764   case OMPC_device_type:
14765   case OMPC_match:
14766   case OMPC_nontemporal:
14767   case OMPC_order:
14768   case OMPC_destroy:
14769   case OMPC_novariants:
14770   case OMPC_nocontext:
14771   case OMPC_detach:
14772   case OMPC_inclusive:
14773   case OMPC_exclusive:
14774   case OMPC_uses_allocators:
14775   case OMPC_affinity:
14776   default:
14777     llvm_unreachable("Clause is not allowed.");
14778   }
14779   return Res;
14780 }
14781 
14782 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
14783                                    OpenMPScheduleClauseModifier M2,
14784                                    SourceLocation M1Loc, SourceLocation M2Loc) {
14785   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
14786     SmallVector<unsigned, 2> Excluded;
14787     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
14788       Excluded.push_back(M2);
14789     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
14790       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
14791     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
14792       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
14793     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
14794         << getListOfPossibleValues(OMPC_schedule,
14795                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
14796                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14797                                    Excluded)
14798         << getOpenMPClauseName(OMPC_schedule);
14799     return true;
14800   }
14801   return false;
14802 }
14803 
14804 OMPClause *Sema::ActOnOpenMPScheduleClause(
14805     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
14806     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14807     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
14808     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
14809   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
14810       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
14811     return nullptr;
14812   // OpenMP, 2.7.1, Loop Construct, Restrictions
14813   // Either the monotonic modifier or the nonmonotonic modifier can be specified
14814   // but not both.
14815   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
14816       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
14817        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
14818       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
14819        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
14820     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
14821         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
14822         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
14823     return nullptr;
14824   }
14825   if (Kind == OMPC_SCHEDULE_unknown) {
14826     std::string Values;
14827     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
14828       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
14829       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14830                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14831                                        Exclude);
14832     } else {
14833       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14834                                        /*Last=*/OMPC_SCHEDULE_unknown);
14835     }
14836     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14837         << Values << getOpenMPClauseName(OMPC_schedule);
14838     return nullptr;
14839   }
14840   // OpenMP, 2.7.1, Loop Construct, Restrictions
14841   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
14842   // schedule(guided).
14843   // OpenMP 5.0 does not have this restriction.
14844   if (LangOpts.OpenMP < 50 &&
14845       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
14846        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
14847       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
14848     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
14849          diag::err_omp_schedule_nonmonotonic_static);
14850     return nullptr;
14851   }
14852   Expr *ValExpr = ChunkSize;
14853   Stmt *HelperValStmt = nullptr;
14854   if (ChunkSize) {
14855     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14856         !ChunkSize->isInstantiationDependent() &&
14857         !ChunkSize->containsUnexpandedParameterPack()) {
14858       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14859       ExprResult Val =
14860           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14861       if (Val.isInvalid())
14862         return nullptr;
14863 
14864       ValExpr = Val.get();
14865 
14866       // OpenMP [2.7.1, Restrictions]
14867       //  chunk_size must be a loop invariant integer expression with a positive
14868       //  value.
14869       if (Optional<llvm::APSInt> Result =
14870               ValExpr->getIntegerConstantExpr(Context)) {
14871         if (Result->isSigned() && !Result->isStrictlyPositive()) {
14872           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14873               << "schedule" << 1 << ChunkSize->getSourceRange();
14874           return nullptr;
14875         }
14876       } else if (getOpenMPCaptureRegionForClause(
14877                      DSAStack->getCurrentDirective(), OMPC_schedule,
14878                      LangOpts.OpenMP) != OMPD_unknown &&
14879                  !CurContext->isDependentContext()) {
14880         ValExpr = MakeFullExpr(ValExpr).get();
14881         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14882         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14883         HelperValStmt = buildPreInits(Context, Captures);
14884       }
14885     }
14886   }
14887 
14888   return new (Context)
14889       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
14890                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
14891 }
14892 
14893 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
14894                                    SourceLocation StartLoc,
14895                                    SourceLocation EndLoc) {
14896   OMPClause *Res = nullptr;
14897   switch (Kind) {
14898   case OMPC_ordered:
14899     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
14900     break;
14901   case OMPC_nowait:
14902     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
14903     break;
14904   case OMPC_untied:
14905     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
14906     break;
14907   case OMPC_mergeable:
14908     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
14909     break;
14910   case OMPC_read:
14911     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
14912     break;
14913   case OMPC_write:
14914     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
14915     break;
14916   case OMPC_update:
14917     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
14918     break;
14919   case OMPC_capture:
14920     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
14921     break;
14922   case OMPC_seq_cst:
14923     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
14924     break;
14925   case OMPC_acq_rel:
14926     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
14927     break;
14928   case OMPC_acquire:
14929     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
14930     break;
14931   case OMPC_release:
14932     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
14933     break;
14934   case OMPC_relaxed:
14935     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
14936     break;
14937   case OMPC_threads:
14938     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
14939     break;
14940   case OMPC_simd:
14941     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
14942     break;
14943   case OMPC_nogroup:
14944     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
14945     break;
14946   case OMPC_unified_address:
14947     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
14948     break;
14949   case OMPC_unified_shared_memory:
14950     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14951     break;
14952   case OMPC_reverse_offload:
14953     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
14954     break;
14955   case OMPC_dynamic_allocators:
14956     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
14957     break;
14958   case OMPC_destroy:
14959     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
14960                                    /*LParenLoc=*/SourceLocation(),
14961                                    /*VarLoc=*/SourceLocation(), EndLoc);
14962     break;
14963   case OMPC_full:
14964     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
14965     break;
14966   case OMPC_partial:
14967     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
14968     break;
14969   case OMPC_if:
14970   case OMPC_final:
14971   case OMPC_num_threads:
14972   case OMPC_safelen:
14973   case OMPC_simdlen:
14974   case OMPC_sizes:
14975   case OMPC_allocator:
14976   case OMPC_collapse:
14977   case OMPC_schedule:
14978   case OMPC_private:
14979   case OMPC_firstprivate:
14980   case OMPC_lastprivate:
14981   case OMPC_shared:
14982   case OMPC_reduction:
14983   case OMPC_task_reduction:
14984   case OMPC_in_reduction:
14985   case OMPC_linear:
14986   case OMPC_aligned:
14987   case OMPC_copyin:
14988   case OMPC_copyprivate:
14989   case OMPC_default:
14990   case OMPC_proc_bind:
14991   case OMPC_threadprivate:
14992   case OMPC_allocate:
14993   case OMPC_flush:
14994   case OMPC_depobj:
14995   case OMPC_depend:
14996   case OMPC_device:
14997   case OMPC_map:
14998   case OMPC_num_teams:
14999   case OMPC_thread_limit:
15000   case OMPC_priority:
15001   case OMPC_grainsize:
15002   case OMPC_num_tasks:
15003   case OMPC_hint:
15004   case OMPC_dist_schedule:
15005   case OMPC_defaultmap:
15006   case OMPC_unknown:
15007   case OMPC_uniform:
15008   case OMPC_to:
15009   case OMPC_from:
15010   case OMPC_use_device_ptr:
15011   case OMPC_use_device_addr:
15012   case OMPC_is_device_ptr:
15013   case OMPC_atomic_default_mem_order:
15014   case OMPC_device_type:
15015   case OMPC_match:
15016   case OMPC_nontemporal:
15017   case OMPC_order:
15018   case OMPC_novariants:
15019   case OMPC_nocontext:
15020   case OMPC_detach:
15021   case OMPC_inclusive:
15022   case OMPC_exclusive:
15023   case OMPC_uses_allocators:
15024   case OMPC_affinity:
15025   default:
15026     llvm_unreachable("Clause is not allowed.");
15027   }
15028   return Res;
15029 }
15030 
15031 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
15032                                          SourceLocation EndLoc) {
15033   DSAStack->setNowaitRegion();
15034   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
15035 }
15036 
15037 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
15038                                          SourceLocation EndLoc) {
15039   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
15040 }
15041 
15042 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
15043                                             SourceLocation EndLoc) {
15044   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
15045 }
15046 
15047 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
15048                                        SourceLocation EndLoc) {
15049   return new (Context) OMPReadClause(StartLoc, EndLoc);
15050 }
15051 
15052 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
15053                                         SourceLocation EndLoc) {
15054   return new (Context) OMPWriteClause(StartLoc, EndLoc);
15055 }
15056 
15057 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
15058                                          SourceLocation EndLoc) {
15059   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
15060 }
15061 
15062 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
15063                                           SourceLocation EndLoc) {
15064   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
15065 }
15066 
15067 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
15068                                          SourceLocation EndLoc) {
15069   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
15070 }
15071 
15072 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
15073                                          SourceLocation EndLoc) {
15074   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
15075 }
15076 
15077 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
15078                                           SourceLocation EndLoc) {
15079   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
15080 }
15081 
15082 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
15083                                           SourceLocation EndLoc) {
15084   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
15085 }
15086 
15087 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
15088                                           SourceLocation EndLoc) {
15089   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
15090 }
15091 
15092 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
15093                                           SourceLocation EndLoc) {
15094   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
15095 }
15096 
15097 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
15098                                        SourceLocation EndLoc) {
15099   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
15100 }
15101 
15102 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
15103                                           SourceLocation EndLoc) {
15104   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
15105 }
15106 
15107 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
15108                                                  SourceLocation EndLoc) {
15109   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
15110 }
15111 
15112 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
15113                                                       SourceLocation EndLoc) {
15114   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15115 }
15116 
15117 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
15118                                                  SourceLocation EndLoc) {
15119   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
15120 }
15121 
15122 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
15123                                                     SourceLocation EndLoc) {
15124   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
15125 }
15126 
15127 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
15128                                              SourceLocation StartLoc,
15129                                              SourceLocation EndLoc) {
15130 
15131   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15132   // At least one action-clause must appear on a directive.
15133   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
15134     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
15135     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
15136         << Expected << getOpenMPDirectiveName(OMPD_interop);
15137     return StmtError();
15138   }
15139 
15140   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15141   // A depend clause can only appear on the directive if a targetsync
15142   // interop-type is present or the interop-var was initialized with
15143   // the targetsync interop-type.
15144 
15145   // If there is any 'init' clause diagnose if there is no 'init' clause with
15146   // interop-type of 'targetsync'. Cases involving other directives cannot be
15147   // diagnosed.
15148   const OMPDependClause *DependClause = nullptr;
15149   bool HasInitClause = false;
15150   bool IsTargetSync = false;
15151   for (const OMPClause *C : Clauses) {
15152     if (IsTargetSync)
15153       break;
15154     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
15155       HasInitClause = true;
15156       if (InitClause->getIsTargetSync())
15157         IsTargetSync = true;
15158     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
15159       DependClause = DC;
15160     }
15161   }
15162   if (DependClause && HasInitClause && !IsTargetSync) {
15163     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
15164     return StmtError();
15165   }
15166 
15167   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15168   // Each interop-var may be specified for at most one action-clause of each
15169   // interop construct.
15170   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
15171   for (const OMPClause *C : Clauses) {
15172     OpenMPClauseKind ClauseKind = C->getClauseKind();
15173     const DeclRefExpr *DRE = nullptr;
15174     SourceLocation VarLoc;
15175 
15176     if (ClauseKind == OMPC_init) {
15177       const auto *IC = cast<OMPInitClause>(C);
15178       VarLoc = IC->getVarLoc();
15179       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
15180     } else if (ClauseKind == OMPC_use) {
15181       const auto *UC = cast<OMPUseClause>(C);
15182       VarLoc = UC->getVarLoc();
15183       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
15184     } else if (ClauseKind == OMPC_destroy) {
15185       const auto *DC = cast<OMPDestroyClause>(C);
15186       VarLoc = DC->getVarLoc();
15187       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
15188     }
15189 
15190     if (!DRE)
15191       continue;
15192 
15193     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
15194       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
15195         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
15196         return StmtError();
15197       }
15198     }
15199   }
15200 
15201   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
15202 }
15203 
15204 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
15205                                    SourceLocation VarLoc,
15206                                    OpenMPClauseKind Kind) {
15207   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
15208       InteropVarExpr->isInstantiationDependent() ||
15209       InteropVarExpr->containsUnexpandedParameterPack())
15210     return true;
15211 
15212   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
15213   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
15214     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
15215     return false;
15216   }
15217 
15218   // Interop variable should be of type omp_interop_t.
15219   bool HasError = false;
15220   QualType InteropType;
15221   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
15222                       VarLoc, Sema::LookupOrdinaryName);
15223   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
15224     NamedDecl *ND = Result.getFoundDecl();
15225     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
15226       InteropType = QualType(TD->getTypeForDecl(), 0);
15227     } else {
15228       HasError = true;
15229     }
15230   } else {
15231     HasError = true;
15232   }
15233 
15234   if (HasError) {
15235     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
15236         << "omp_interop_t";
15237     return false;
15238   }
15239 
15240   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
15241   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
15242     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
15243     return false;
15244   }
15245 
15246   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15247   // The interop-var passed to init or destroy must be non-const.
15248   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
15249       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
15250     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
15251         << /*non-const*/ 1;
15252     return false;
15253   }
15254   return true;
15255 }
15256 
15257 OMPClause *
15258 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
15259                             bool IsTarget, bool IsTargetSync,
15260                             SourceLocation StartLoc, SourceLocation LParenLoc,
15261                             SourceLocation VarLoc, SourceLocation EndLoc) {
15262 
15263   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
15264     return nullptr;
15265 
15266   // Check prefer_type values.  These foreign-runtime-id values are either
15267   // string literals or constant integral expressions.
15268   for (const Expr *E : PrefExprs) {
15269     if (E->isValueDependent() || E->isTypeDependent() ||
15270         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15271       continue;
15272     if (E->isIntegerConstantExpr(Context))
15273       continue;
15274     if (isa<StringLiteral>(E))
15275       continue;
15276     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
15277     return nullptr;
15278   }
15279 
15280   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
15281                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
15282                                EndLoc);
15283 }
15284 
15285 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
15286                                       SourceLocation LParenLoc,
15287                                       SourceLocation VarLoc,
15288                                       SourceLocation EndLoc) {
15289 
15290   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
15291     return nullptr;
15292 
15293   return new (Context)
15294       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15295 }
15296 
15297 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
15298                                           SourceLocation StartLoc,
15299                                           SourceLocation LParenLoc,
15300                                           SourceLocation VarLoc,
15301                                           SourceLocation EndLoc) {
15302   if (InteropVar &&
15303       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
15304     return nullptr;
15305 
15306   return new (Context)
15307       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15308 }
15309 
15310 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
15311                                              SourceLocation StartLoc,
15312                                              SourceLocation LParenLoc,
15313                                              SourceLocation EndLoc) {
15314   Expr *ValExpr = Condition;
15315   Stmt *HelperValStmt = nullptr;
15316   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15317   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15318       !Condition->isInstantiationDependent() &&
15319       !Condition->containsUnexpandedParameterPack()) {
15320     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15321     if (Val.isInvalid())
15322       return nullptr;
15323 
15324     ValExpr = MakeFullExpr(Val.get()).get();
15325 
15326     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15327     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
15328                                                     LangOpts.OpenMP);
15329     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15330       ValExpr = MakeFullExpr(ValExpr).get();
15331       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15332       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15333       HelperValStmt = buildPreInits(Context, Captures);
15334     }
15335   }
15336 
15337   return new (Context) OMPNovariantsClause(
15338       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15339 }
15340 
15341 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
15342                                             SourceLocation StartLoc,
15343                                             SourceLocation LParenLoc,
15344                                             SourceLocation EndLoc) {
15345   Expr *ValExpr = Condition;
15346   Stmt *HelperValStmt = nullptr;
15347   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15348   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15349       !Condition->isInstantiationDependent() &&
15350       !Condition->containsUnexpandedParameterPack()) {
15351     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15352     if (Val.isInvalid())
15353       return nullptr;
15354 
15355     ValExpr = MakeFullExpr(Val.get()).get();
15356 
15357     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15358     CaptureRegion =
15359         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
15360     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15361       ValExpr = MakeFullExpr(ValExpr).get();
15362       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15363       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15364       HelperValStmt = buildPreInits(Context, Captures);
15365     }
15366   }
15367 
15368   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
15369                                           StartLoc, LParenLoc, EndLoc);
15370 }
15371 
15372 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
15373                                          SourceLocation StartLoc,
15374                                          SourceLocation LParenLoc,
15375                                          SourceLocation EndLoc) {
15376   Expr *ValExpr = ThreadID;
15377   Stmt *HelperValStmt = nullptr;
15378 
15379   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15380   OpenMPDirectiveKind CaptureRegion =
15381       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
15382   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15383     ValExpr = MakeFullExpr(ValExpr).get();
15384     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15385     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15386     HelperValStmt = buildPreInits(Context, Captures);
15387   }
15388 
15389   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
15390                                        StartLoc, LParenLoc, EndLoc);
15391 }
15392 
15393 OMPClause *Sema::ActOnOpenMPVarListClause(
15394     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
15395     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
15396     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
15397     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
15398     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15399     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
15400     SourceLocation ExtraModifierLoc,
15401     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
15402     ArrayRef<SourceLocation> MotionModifiersLoc) {
15403   SourceLocation StartLoc = Locs.StartLoc;
15404   SourceLocation LParenLoc = Locs.LParenLoc;
15405   SourceLocation EndLoc = Locs.EndLoc;
15406   OMPClause *Res = nullptr;
15407   switch (Kind) {
15408   case OMPC_private:
15409     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15410     break;
15411   case OMPC_firstprivate:
15412     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15413     break;
15414   case OMPC_lastprivate:
15415     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
15416            "Unexpected lastprivate modifier.");
15417     Res = ActOnOpenMPLastprivateClause(
15418         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
15419         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
15420     break;
15421   case OMPC_shared:
15422     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
15423     break;
15424   case OMPC_reduction:
15425     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
15426            "Unexpected lastprivate modifier.");
15427     Res = ActOnOpenMPReductionClause(
15428         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
15429         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
15430         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
15431     break;
15432   case OMPC_task_reduction:
15433     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15434                                          EndLoc, ReductionOrMapperIdScopeSpec,
15435                                          ReductionOrMapperId);
15436     break;
15437   case OMPC_in_reduction:
15438     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15439                                        EndLoc, ReductionOrMapperIdScopeSpec,
15440                                        ReductionOrMapperId);
15441     break;
15442   case OMPC_linear:
15443     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
15444            "Unexpected linear modifier.");
15445     Res = ActOnOpenMPLinearClause(
15446         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15447         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15448         ColonLoc, EndLoc);
15449     break;
15450   case OMPC_aligned:
15451     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15452                                    LParenLoc, ColonLoc, EndLoc);
15453     break;
15454   case OMPC_copyin:
15455     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15456     break;
15457   case OMPC_copyprivate:
15458     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15459     break;
15460   case OMPC_flush:
15461     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15462     break;
15463   case OMPC_depend:
15464     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15465            "Unexpected depend modifier.");
15466     Res = ActOnOpenMPDependClause(
15467         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15468         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15469     break;
15470   case OMPC_map:
15471     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15472            "Unexpected map modifier.");
15473     Res = ActOnOpenMPMapClause(
15474         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15475         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15476         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15477     break;
15478   case OMPC_to:
15479     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15480                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15481                               ColonLoc, VarList, Locs);
15482     break;
15483   case OMPC_from:
15484     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15485                                 ReductionOrMapperIdScopeSpec,
15486                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15487     break;
15488   case OMPC_use_device_ptr:
15489     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15490     break;
15491   case OMPC_use_device_addr:
15492     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15493     break;
15494   case OMPC_is_device_ptr:
15495     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15496     break;
15497   case OMPC_allocate:
15498     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15499                                     LParenLoc, ColonLoc, EndLoc);
15500     break;
15501   case OMPC_nontemporal:
15502     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15503     break;
15504   case OMPC_inclusive:
15505     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15506     break;
15507   case OMPC_exclusive:
15508     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15509     break;
15510   case OMPC_affinity:
15511     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15512                                     DepModOrTailExpr, VarList);
15513     break;
15514   case OMPC_if:
15515   case OMPC_depobj:
15516   case OMPC_final:
15517   case OMPC_num_threads:
15518   case OMPC_safelen:
15519   case OMPC_simdlen:
15520   case OMPC_sizes:
15521   case OMPC_allocator:
15522   case OMPC_collapse:
15523   case OMPC_default:
15524   case OMPC_proc_bind:
15525   case OMPC_schedule:
15526   case OMPC_ordered:
15527   case OMPC_nowait:
15528   case OMPC_untied:
15529   case OMPC_mergeable:
15530   case OMPC_threadprivate:
15531   case OMPC_read:
15532   case OMPC_write:
15533   case OMPC_update:
15534   case OMPC_capture:
15535   case OMPC_seq_cst:
15536   case OMPC_acq_rel:
15537   case OMPC_acquire:
15538   case OMPC_release:
15539   case OMPC_relaxed:
15540   case OMPC_device:
15541   case OMPC_threads:
15542   case OMPC_simd:
15543   case OMPC_num_teams:
15544   case OMPC_thread_limit:
15545   case OMPC_priority:
15546   case OMPC_grainsize:
15547   case OMPC_nogroup:
15548   case OMPC_num_tasks:
15549   case OMPC_hint:
15550   case OMPC_dist_schedule:
15551   case OMPC_defaultmap:
15552   case OMPC_unknown:
15553   case OMPC_uniform:
15554   case OMPC_unified_address:
15555   case OMPC_unified_shared_memory:
15556   case OMPC_reverse_offload:
15557   case OMPC_dynamic_allocators:
15558   case OMPC_atomic_default_mem_order:
15559   case OMPC_device_type:
15560   case OMPC_match:
15561   case OMPC_order:
15562   case OMPC_destroy:
15563   case OMPC_novariants:
15564   case OMPC_nocontext:
15565   case OMPC_detach:
15566   case OMPC_uses_allocators:
15567   default:
15568     llvm_unreachable("Clause is not allowed.");
15569   }
15570   return Res;
15571 }
15572 
15573 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15574                                        ExprObjectKind OK, SourceLocation Loc) {
15575   ExprResult Res = BuildDeclRefExpr(
15576       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15577   if (!Res.isUsable())
15578     return ExprError();
15579   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15580     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15581     if (!Res.isUsable())
15582       return ExprError();
15583   }
15584   if (VK != VK_LValue && Res.get()->isGLValue()) {
15585     Res = DefaultLvalueConversion(Res.get());
15586     if (!Res.isUsable())
15587       return ExprError();
15588   }
15589   return Res;
15590 }
15591 
15592 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15593                                           SourceLocation StartLoc,
15594                                           SourceLocation LParenLoc,
15595                                           SourceLocation EndLoc) {
15596   SmallVector<Expr *, 8> Vars;
15597   SmallVector<Expr *, 8> PrivateCopies;
15598   for (Expr *RefExpr : VarList) {
15599     assert(RefExpr && "NULL expr in OpenMP private clause.");
15600     SourceLocation ELoc;
15601     SourceRange ERange;
15602     Expr *SimpleRefExpr = RefExpr;
15603     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15604     if (Res.second) {
15605       // It will be analyzed later.
15606       Vars.push_back(RefExpr);
15607       PrivateCopies.push_back(nullptr);
15608     }
15609     ValueDecl *D = Res.first;
15610     if (!D)
15611       continue;
15612 
15613     QualType Type = D->getType();
15614     auto *VD = dyn_cast<VarDecl>(D);
15615 
15616     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15617     //  A variable that appears in a private clause must not have an incomplete
15618     //  type or a reference type.
15619     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15620       continue;
15621     Type = Type.getNonReferenceType();
15622 
15623     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15624     // A variable that is privatized must not have a const-qualified type
15625     // unless it is of class type with a mutable member. This restriction does
15626     // not apply to the firstprivate clause.
15627     //
15628     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15629     // A variable that appears in a private clause must not have a
15630     // const-qualified type unless it is of class type with a mutable member.
15631     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15632       continue;
15633 
15634     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15635     // in a Construct]
15636     //  Variables with the predetermined data-sharing attributes may not be
15637     //  listed in data-sharing attributes clauses, except for the cases
15638     //  listed below. For these exceptions only, listing a predetermined
15639     //  variable in a data-sharing attribute clause is allowed and overrides
15640     //  the variable's predetermined data-sharing attributes.
15641     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15642     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15643       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15644                                           << getOpenMPClauseName(OMPC_private);
15645       reportOriginalDsa(*this, DSAStack, D, DVar);
15646       continue;
15647     }
15648 
15649     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15650     // Variably modified types are not supported for tasks.
15651     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15652         isOpenMPTaskingDirective(CurrDir)) {
15653       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15654           << getOpenMPClauseName(OMPC_private) << Type
15655           << getOpenMPDirectiveName(CurrDir);
15656       bool IsDecl =
15657           !VD ||
15658           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15659       Diag(D->getLocation(),
15660            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15661           << D;
15662       continue;
15663     }
15664 
15665     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15666     // A list item cannot appear in both a map clause and a data-sharing
15667     // attribute clause on the same construct
15668     //
15669     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15670     // A list item cannot appear in both a map clause and a data-sharing
15671     // attribute clause on the same construct unless the construct is a
15672     // combined construct.
15673     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
15674         CurrDir == OMPD_target) {
15675       OpenMPClauseKind ConflictKind;
15676       if (DSAStack->checkMappableExprComponentListsForDecl(
15677               VD, /*CurrentRegionOnly=*/true,
15678               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
15679                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
15680                 ConflictKind = WhereFoundClauseKind;
15681                 return true;
15682               })) {
15683         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15684             << getOpenMPClauseName(OMPC_private)
15685             << getOpenMPClauseName(ConflictKind)
15686             << getOpenMPDirectiveName(CurrDir);
15687         reportOriginalDsa(*this, DSAStack, D, DVar);
15688         continue;
15689       }
15690     }
15691 
15692     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
15693     //  A variable of class type (or array thereof) that appears in a private
15694     //  clause requires an accessible, unambiguous default constructor for the
15695     //  class type.
15696     // Generate helper private variable and initialize it with the default
15697     // value. The address of the original variable is replaced by the address of
15698     // the new private variable in CodeGen. This new variable is not added to
15699     // IdResolver, so the code in the OpenMP region uses original variable for
15700     // proper diagnostics.
15701     Type = Type.getUnqualifiedType();
15702     VarDecl *VDPrivate =
15703         buildVarDecl(*this, ELoc, Type, D->getName(),
15704                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15705                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15706     ActOnUninitializedDecl(VDPrivate);
15707     if (VDPrivate->isInvalidDecl())
15708       continue;
15709     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15710         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15711 
15712     DeclRefExpr *Ref = nullptr;
15713     if (!VD && !CurContext->isDependentContext())
15714       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15715     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
15716     Vars.push_back((VD || CurContext->isDependentContext())
15717                        ? RefExpr->IgnoreParens()
15718                        : Ref);
15719     PrivateCopies.push_back(VDPrivateRefExpr);
15720   }
15721 
15722   if (Vars.empty())
15723     return nullptr;
15724 
15725   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15726                                   PrivateCopies);
15727 }
15728 
15729 namespace {
15730 class DiagsUninitializedSeveretyRAII {
15731 private:
15732   DiagnosticsEngine &Diags;
15733   SourceLocation SavedLoc;
15734   bool IsIgnored = false;
15735 
15736 public:
15737   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
15738                                  bool IsIgnored)
15739       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
15740     if (!IsIgnored) {
15741       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
15742                         /*Map*/ diag::Severity::Ignored, Loc);
15743     }
15744   }
15745   ~DiagsUninitializedSeveretyRAII() {
15746     if (!IsIgnored)
15747       Diags.popMappings(SavedLoc);
15748   }
15749 };
15750 }
15751 
15752 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
15753                                                SourceLocation StartLoc,
15754                                                SourceLocation LParenLoc,
15755                                                SourceLocation EndLoc) {
15756   SmallVector<Expr *, 8> Vars;
15757   SmallVector<Expr *, 8> PrivateCopies;
15758   SmallVector<Expr *, 8> Inits;
15759   SmallVector<Decl *, 4> ExprCaptures;
15760   bool IsImplicitClause =
15761       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
15762   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
15763 
15764   for (Expr *RefExpr : VarList) {
15765     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
15766     SourceLocation ELoc;
15767     SourceRange ERange;
15768     Expr *SimpleRefExpr = RefExpr;
15769     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15770     if (Res.second) {
15771       // It will be analyzed later.
15772       Vars.push_back(RefExpr);
15773       PrivateCopies.push_back(nullptr);
15774       Inits.push_back(nullptr);
15775     }
15776     ValueDecl *D = Res.first;
15777     if (!D)
15778       continue;
15779 
15780     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
15781     QualType Type = D->getType();
15782     auto *VD = dyn_cast<VarDecl>(D);
15783 
15784     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15785     //  A variable that appears in a private clause must not have an incomplete
15786     //  type or a reference type.
15787     if (RequireCompleteType(ELoc, Type,
15788                             diag::err_omp_firstprivate_incomplete_type))
15789       continue;
15790     Type = Type.getNonReferenceType();
15791 
15792     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
15793     //  A variable of class type (or array thereof) that appears in a private
15794     //  clause requires an accessible, unambiguous copy constructor for the
15795     //  class type.
15796     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15797 
15798     // If an implicit firstprivate variable found it was checked already.
15799     DSAStackTy::DSAVarData TopDVar;
15800     if (!IsImplicitClause) {
15801       DSAStackTy::DSAVarData DVar =
15802           DSAStack->getTopDSA(D, /*FromParent=*/false);
15803       TopDVar = DVar;
15804       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15805       bool IsConstant = ElemType.isConstant(Context);
15806       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
15807       //  A list item that specifies a given variable may not appear in more
15808       // than one clause on the same directive, except that a variable may be
15809       //  specified in both firstprivate and lastprivate clauses.
15810       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15811       // A list item may appear in a firstprivate or lastprivate clause but not
15812       // both.
15813       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
15814           (isOpenMPDistributeDirective(CurrDir) ||
15815            DVar.CKind != OMPC_lastprivate) &&
15816           DVar.RefExpr) {
15817         Diag(ELoc, diag::err_omp_wrong_dsa)
15818             << getOpenMPClauseName(DVar.CKind)
15819             << getOpenMPClauseName(OMPC_firstprivate);
15820         reportOriginalDsa(*this, DSAStack, D, DVar);
15821         continue;
15822       }
15823 
15824       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15825       // in a Construct]
15826       //  Variables with the predetermined data-sharing attributes may not be
15827       //  listed in data-sharing attributes clauses, except for the cases
15828       //  listed below. For these exceptions only, listing a predetermined
15829       //  variable in a data-sharing attribute clause is allowed and overrides
15830       //  the variable's predetermined data-sharing attributes.
15831       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15832       // in a Construct, C/C++, p.2]
15833       //  Variables with const-qualified type having no mutable member may be
15834       //  listed in a firstprivate clause, even if they are static data members.
15835       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
15836           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
15837         Diag(ELoc, diag::err_omp_wrong_dsa)
15838             << getOpenMPClauseName(DVar.CKind)
15839             << getOpenMPClauseName(OMPC_firstprivate);
15840         reportOriginalDsa(*this, DSAStack, D, DVar);
15841         continue;
15842       }
15843 
15844       // OpenMP [2.9.3.4, Restrictions, p.2]
15845       //  A list item that is private within a parallel region must not appear
15846       //  in a firstprivate clause on a worksharing construct if any of the
15847       //  worksharing regions arising from the worksharing construct ever bind
15848       //  to any of the parallel regions arising from the parallel construct.
15849       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15850       // A list item that is private within a teams region must not appear in a
15851       // firstprivate clause on a distribute construct if any of the distribute
15852       // regions arising from the distribute construct ever bind to any of the
15853       // teams regions arising from the teams construct.
15854       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15855       // A list item that appears in a reduction clause of a teams construct
15856       // must not appear in a firstprivate clause on a distribute construct if
15857       // any of the distribute regions arising from the distribute construct
15858       // ever bind to any of the teams regions arising from the teams construct.
15859       if ((isOpenMPWorksharingDirective(CurrDir) ||
15860            isOpenMPDistributeDirective(CurrDir)) &&
15861           !isOpenMPParallelDirective(CurrDir) &&
15862           !isOpenMPTeamsDirective(CurrDir)) {
15863         DVar = DSAStack->getImplicitDSA(D, true);
15864         if (DVar.CKind != OMPC_shared &&
15865             (isOpenMPParallelDirective(DVar.DKind) ||
15866              isOpenMPTeamsDirective(DVar.DKind) ||
15867              DVar.DKind == OMPD_unknown)) {
15868           Diag(ELoc, diag::err_omp_required_access)
15869               << getOpenMPClauseName(OMPC_firstprivate)
15870               << getOpenMPClauseName(OMPC_shared);
15871           reportOriginalDsa(*this, DSAStack, D, DVar);
15872           continue;
15873         }
15874       }
15875       // OpenMP [2.9.3.4, Restrictions, p.3]
15876       //  A list item that appears in a reduction clause of a parallel construct
15877       //  must not appear in a firstprivate clause on a worksharing or task
15878       //  construct if any of the worksharing or task regions arising from the
15879       //  worksharing or task construct ever bind to any of the parallel regions
15880       //  arising from the parallel construct.
15881       // OpenMP [2.9.3.4, Restrictions, p.4]
15882       //  A list item that appears in a reduction clause in worksharing
15883       //  construct must not appear in a firstprivate clause in a task construct
15884       //  encountered during execution of any of the worksharing regions arising
15885       //  from the worksharing construct.
15886       if (isOpenMPTaskingDirective(CurrDir)) {
15887         DVar = DSAStack->hasInnermostDSA(
15888             D,
15889             [](OpenMPClauseKind C, bool AppliedToPointee) {
15890               return C == OMPC_reduction && !AppliedToPointee;
15891             },
15892             [](OpenMPDirectiveKind K) {
15893               return isOpenMPParallelDirective(K) ||
15894                      isOpenMPWorksharingDirective(K) ||
15895                      isOpenMPTeamsDirective(K);
15896             },
15897             /*FromParent=*/true);
15898         if (DVar.CKind == OMPC_reduction &&
15899             (isOpenMPParallelDirective(DVar.DKind) ||
15900              isOpenMPWorksharingDirective(DVar.DKind) ||
15901              isOpenMPTeamsDirective(DVar.DKind))) {
15902           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
15903               << getOpenMPDirectiveName(DVar.DKind);
15904           reportOriginalDsa(*this, DSAStack, D, DVar);
15905           continue;
15906         }
15907       }
15908 
15909       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15910       // A list item cannot appear in both a map clause and a data-sharing
15911       // attribute clause on the same construct
15912       //
15913       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15914       // A list item cannot appear in both a map clause and a data-sharing
15915       // attribute clause on the same construct unless the construct is a
15916       // combined construct.
15917       if ((LangOpts.OpenMP <= 45 &&
15918            isOpenMPTargetExecutionDirective(CurrDir)) ||
15919           CurrDir == OMPD_target) {
15920         OpenMPClauseKind ConflictKind;
15921         if (DSAStack->checkMappableExprComponentListsForDecl(
15922                 VD, /*CurrentRegionOnly=*/true,
15923                 [&ConflictKind](
15924                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
15925                     OpenMPClauseKind WhereFoundClauseKind) {
15926                   ConflictKind = WhereFoundClauseKind;
15927                   return true;
15928                 })) {
15929           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15930               << getOpenMPClauseName(OMPC_firstprivate)
15931               << getOpenMPClauseName(ConflictKind)
15932               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15933           reportOriginalDsa(*this, DSAStack, D, DVar);
15934           continue;
15935         }
15936       }
15937     }
15938 
15939     // Variably modified types are not supported for tasks.
15940     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15941         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
15942       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15943           << getOpenMPClauseName(OMPC_firstprivate) << Type
15944           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15945       bool IsDecl =
15946           !VD ||
15947           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15948       Diag(D->getLocation(),
15949            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15950           << D;
15951       continue;
15952     }
15953 
15954     Type = Type.getUnqualifiedType();
15955     VarDecl *VDPrivate =
15956         buildVarDecl(*this, ELoc, Type, D->getName(),
15957                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15958                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15959     // Generate helper private variable and initialize it with the value of the
15960     // original variable. The address of the original variable is replaced by
15961     // the address of the new private variable in the CodeGen. This new variable
15962     // is not added to IdResolver, so the code in the OpenMP region uses
15963     // original variable for proper diagnostics and variable capturing.
15964     Expr *VDInitRefExpr = nullptr;
15965     // For arrays generate initializer for single element and replace it by the
15966     // original array element in CodeGen.
15967     if (Type->isArrayType()) {
15968       VarDecl *VDInit =
15969           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
15970       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
15971       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
15972       ElemType = ElemType.getUnqualifiedType();
15973       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
15974                                          ".firstprivate.temp");
15975       InitializedEntity Entity =
15976           InitializedEntity::InitializeVariable(VDInitTemp);
15977       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
15978 
15979       InitializationSequence InitSeq(*this, Entity, Kind, Init);
15980       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
15981       if (Result.isInvalid())
15982         VDPrivate->setInvalidDecl();
15983       else
15984         VDPrivate->setInit(Result.getAs<Expr>());
15985       // Remove temp variable declaration.
15986       Context.Deallocate(VDInitTemp);
15987     } else {
15988       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
15989                                      ".firstprivate.temp");
15990       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
15991                                        RefExpr->getExprLoc());
15992       AddInitializerToDecl(VDPrivate,
15993                            DefaultLvalueConversion(VDInitRefExpr).get(),
15994                            /*DirectInit=*/false);
15995     }
15996     if (VDPrivate->isInvalidDecl()) {
15997       if (IsImplicitClause) {
15998         Diag(RefExpr->getExprLoc(),
15999              diag::note_omp_task_predetermined_firstprivate_here);
16000       }
16001       continue;
16002     }
16003     CurContext->addDecl(VDPrivate);
16004     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16005         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
16006         RefExpr->getExprLoc());
16007     DeclRefExpr *Ref = nullptr;
16008     if (!VD && !CurContext->isDependentContext()) {
16009       if (TopDVar.CKind == OMPC_lastprivate) {
16010         Ref = TopDVar.PrivateCopy;
16011       } else {
16012         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16013         if (!isOpenMPCapturedDecl(D))
16014           ExprCaptures.push_back(Ref->getDecl());
16015       }
16016     }
16017     if (!IsImplicitClause)
16018       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16019     Vars.push_back((VD || CurContext->isDependentContext())
16020                        ? RefExpr->IgnoreParens()
16021                        : Ref);
16022     PrivateCopies.push_back(VDPrivateRefExpr);
16023     Inits.push_back(VDInitRefExpr);
16024   }
16025 
16026   if (Vars.empty())
16027     return nullptr;
16028 
16029   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16030                                        Vars, PrivateCopies, Inits,
16031                                        buildPreInits(Context, ExprCaptures));
16032 }
16033 
16034 OMPClause *Sema::ActOnOpenMPLastprivateClause(
16035     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
16036     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
16037     SourceLocation LParenLoc, SourceLocation EndLoc) {
16038   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
16039     assert(ColonLoc.isValid() && "Colon location must be valid.");
16040     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
16041         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
16042                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
16043         << getOpenMPClauseName(OMPC_lastprivate);
16044     return nullptr;
16045   }
16046 
16047   SmallVector<Expr *, 8> Vars;
16048   SmallVector<Expr *, 8> SrcExprs;
16049   SmallVector<Expr *, 8> DstExprs;
16050   SmallVector<Expr *, 8> AssignmentOps;
16051   SmallVector<Decl *, 4> ExprCaptures;
16052   SmallVector<Expr *, 4> ExprPostUpdates;
16053   for (Expr *RefExpr : VarList) {
16054     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16055     SourceLocation ELoc;
16056     SourceRange ERange;
16057     Expr *SimpleRefExpr = RefExpr;
16058     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16059     if (Res.second) {
16060       // It will be analyzed later.
16061       Vars.push_back(RefExpr);
16062       SrcExprs.push_back(nullptr);
16063       DstExprs.push_back(nullptr);
16064       AssignmentOps.push_back(nullptr);
16065     }
16066     ValueDecl *D = Res.first;
16067     if (!D)
16068       continue;
16069 
16070     QualType Type = D->getType();
16071     auto *VD = dyn_cast<VarDecl>(D);
16072 
16073     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
16074     //  A variable that appears in a lastprivate clause must not have an
16075     //  incomplete type or a reference type.
16076     if (RequireCompleteType(ELoc, Type,
16077                             diag::err_omp_lastprivate_incomplete_type))
16078       continue;
16079     Type = Type.getNonReferenceType();
16080 
16081     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16082     // A variable that is privatized must not have a const-qualified type
16083     // unless it is of class type with a mutable member. This restriction does
16084     // not apply to the firstprivate clause.
16085     //
16086     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
16087     // A variable that appears in a lastprivate clause must not have a
16088     // const-qualified type unless it is of class type with a mutable member.
16089     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
16090       continue;
16091 
16092     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
16093     // A list item that appears in a lastprivate clause with the conditional
16094     // modifier must be a scalar variable.
16095     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
16096       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
16097       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16098                                VarDecl::DeclarationOnly;
16099       Diag(D->getLocation(),
16100            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16101           << D;
16102       continue;
16103     }
16104 
16105     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16106     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16107     // in a Construct]
16108     //  Variables with the predetermined data-sharing attributes may not be
16109     //  listed in data-sharing attributes clauses, except for the cases
16110     //  listed below.
16111     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16112     // A list item may appear in a firstprivate or lastprivate clause but not
16113     // both.
16114     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16115     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
16116         (isOpenMPDistributeDirective(CurrDir) ||
16117          DVar.CKind != OMPC_firstprivate) &&
16118         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
16119       Diag(ELoc, diag::err_omp_wrong_dsa)
16120           << getOpenMPClauseName(DVar.CKind)
16121           << getOpenMPClauseName(OMPC_lastprivate);
16122       reportOriginalDsa(*this, DSAStack, D, DVar);
16123       continue;
16124     }
16125 
16126     // OpenMP [2.14.3.5, Restrictions, p.2]
16127     // A list item that is private within a parallel region, or that appears in
16128     // the reduction clause of a parallel construct, must not appear in a
16129     // lastprivate clause on a worksharing construct if any of the corresponding
16130     // worksharing regions ever binds to any of the corresponding parallel
16131     // regions.
16132     DSAStackTy::DSAVarData TopDVar = DVar;
16133     if (isOpenMPWorksharingDirective(CurrDir) &&
16134         !isOpenMPParallelDirective(CurrDir) &&
16135         !isOpenMPTeamsDirective(CurrDir)) {
16136       DVar = DSAStack->getImplicitDSA(D, true);
16137       if (DVar.CKind != OMPC_shared) {
16138         Diag(ELoc, diag::err_omp_required_access)
16139             << getOpenMPClauseName(OMPC_lastprivate)
16140             << getOpenMPClauseName(OMPC_shared);
16141         reportOriginalDsa(*this, DSAStack, D, DVar);
16142         continue;
16143       }
16144     }
16145 
16146     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
16147     //  A variable of class type (or array thereof) that appears in a
16148     //  lastprivate clause requires an accessible, unambiguous default
16149     //  constructor for the class type, unless the list item is also specified
16150     //  in a firstprivate clause.
16151     //  A variable of class type (or array thereof) that appears in a
16152     //  lastprivate clause requires an accessible, unambiguous copy assignment
16153     //  operator for the class type.
16154     Type = Context.getBaseElementType(Type).getNonReferenceType();
16155     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
16156                                   Type.getUnqualifiedType(), ".lastprivate.src",
16157                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16158     DeclRefExpr *PseudoSrcExpr =
16159         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
16160     VarDecl *DstVD =
16161         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
16162                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16163     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16164     // For arrays generate assignment operation for single element and replace
16165     // it by the original array element in CodeGen.
16166     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
16167                                          PseudoDstExpr, PseudoSrcExpr);
16168     if (AssignmentOp.isInvalid())
16169       continue;
16170     AssignmentOp =
16171         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16172     if (AssignmentOp.isInvalid())
16173       continue;
16174 
16175     DeclRefExpr *Ref = nullptr;
16176     if (!VD && !CurContext->isDependentContext()) {
16177       if (TopDVar.CKind == OMPC_firstprivate) {
16178         Ref = TopDVar.PrivateCopy;
16179       } else {
16180         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16181         if (!isOpenMPCapturedDecl(D))
16182           ExprCaptures.push_back(Ref->getDecl());
16183       }
16184       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
16185           (!isOpenMPCapturedDecl(D) &&
16186            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
16187         ExprResult RefRes = DefaultLvalueConversion(Ref);
16188         if (!RefRes.isUsable())
16189           continue;
16190         ExprResult PostUpdateRes =
16191             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16192                        RefRes.get());
16193         if (!PostUpdateRes.isUsable())
16194           continue;
16195         ExprPostUpdates.push_back(
16196             IgnoredValueConversions(PostUpdateRes.get()).get());
16197       }
16198     }
16199     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
16200     Vars.push_back((VD || CurContext->isDependentContext())
16201                        ? RefExpr->IgnoreParens()
16202                        : Ref);
16203     SrcExprs.push_back(PseudoSrcExpr);
16204     DstExprs.push_back(PseudoDstExpr);
16205     AssignmentOps.push_back(AssignmentOp.get());
16206   }
16207 
16208   if (Vars.empty())
16209     return nullptr;
16210 
16211   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16212                                       Vars, SrcExprs, DstExprs, AssignmentOps,
16213                                       LPKind, LPKindLoc, ColonLoc,
16214                                       buildPreInits(Context, ExprCaptures),
16215                                       buildPostUpdate(*this, ExprPostUpdates));
16216 }
16217 
16218 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
16219                                          SourceLocation StartLoc,
16220                                          SourceLocation LParenLoc,
16221                                          SourceLocation EndLoc) {
16222   SmallVector<Expr *, 8> Vars;
16223   for (Expr *RefExpr : VarList) {
16224     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16225     SourceLocation ELoc;
16226     SourceRange ERange;
16227     Expr *SimpleRefExpr = RefExpr;
16228     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16229     if (Res.second) {
16230       // It will be analyzed later.
16231       Vars.push_back(RefExpr);
16232     }
16233     ValueDecl *D = Res.first;
16234     if (!D)
16235       continue;
16236 
16237     auto *VD = dyn_cast<VarDecl>(D);
16238     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16239     // in a Construct]
16240     //  Variables with the predetermined data-sharing attributes may not be
16241     //  listed in data-sharing attributes clauses, except for the cases
16242     //  listed below. For these exceptions only, listing a predetermined
16243     //  variable in a data-sharing attribute clause is allowed and overrides
16244     //  the variable's predetermined data-sharing attributes.
16245     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16246     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
16247         DVar.RefExpr) {
16248       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16249                                           << getOpenMPClauseName(OMPC_shared);
16250       reportOriginalDsa(*this, DSAStack, D, DVar);
16251       continue;
16252     }
16253 
16254     DeclRefExpr *Ref = nullptr;
16255     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
16256       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16257     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
16258     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
16259                        ? RefExpr->IgnoreParens()
16260                        : Ref);
16261   }
16262 
16263   if (Vars.empty())
16264     return nullptr;
16265 
16266   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
16267 }
16268 
16269 namespace {
16270 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
16271   DSAStackTy *Stack;
16272 
16273 public:
16274   bool VisitDeclRefExpr(DeclRefExpr *E) {
16275     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
16276       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
16277       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
16278         return false;
16279       if (DVar.CKind != OMPC_unknown)
16280         return true;
16281       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
16282           VD,
16283           [](OpenMPClauseKind C, bool AppliedToPointee) {
16284             return isOpenMPPrivate(C) && !AppliedToPointee;
16285           },
16286           [](OpenMPDirectiveKind) { return true; },
16287           /*FromParent=*/true);
16288       return DVarPrivate.CKind != OMPC_unknown;
16289     }
16290     return false;
16291   }
16292   bool VisitStmt(Stmt *S) {
16293     for (Stmt *Child : S->children()) {
16294       if (Child && Visit(Child))
16295         return true;
16296     }
16297     return false;
16298   }
16299   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
16300 };
16301 } // namespace
16302 
16303 namespace {
16304 // Transform MemberExpression for specified FieldDecl of current class to
16305 // DeclRefExpr to specified OMPCapturedExprDecl.
16306 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
16307   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
16308   ValueDecl *Field = nullptr;
16309   DeclRefExpr *CapturedExpr = nullptr;
16310 
16311 public:
16312   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
16313       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
16314 
16315   ExprResult TransformMemberExpr(MemberExpr *E) {
16316     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
16317         E->getMemberDecl() == Field) {
16318       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
16319       return CapturedExpr;
16320     }
16321     return BaseTransform::TransformMemberExpr(E);
16322   }
16323   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
16324 };
16325 } // namespace
16326 
16327 template <typename T, typename U>
16328 static T filterLookupForUDReductionAndMapper(
16329     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
16330   for (U &Set : Lookups) {
16331     for (auto *D : Set) {
16332       if (T Res = Gen(cast<ValueDecl>(D)))
16333         return Res;
16334     }
16335   }
16336   return T();
16337 }
16338 
16339 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
16340   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
16341 
16342   for (auto RD : D->redecls()) {
16343     // Don't bother with extra checks if we already know this one isn't visible.
16344     if (RD == D)
16345       continue;
16346 
16347     auto ND = cast<NamedDecl>(RD);
16348     if (LookupResult::isVisible(SemaRef, ND))
16349       return ND;
16350   }
16351 
16352   return nullptr;
16353 }
16354 
16355 static void
16356 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
16357                         SourceLocation Loc, QualType Ty,
16358                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
16359   // Find all of the associated namespaces and classes based on the
16360   // arguments we have.
16361   Sema::AssociatedNamespaceSet AssociatedNamespaces;
16362   Sema::AssociatedClassSet AssociatedClasses;
16363   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
16364   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
16365                                              AssociatedClasses);
16366 
16367   // C++ [basic.lookup.argdep]p3:
16368   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
16369   //   and let Y be the lookup set produced by argument dependent
16370   //   lookup (defined as follows). If X contains [...] then Y is
16371   //   empty. Otherwise Y is the set of declarations found in the
16372   //   namespaces associated with the argument types as described
16373   //   below. The set of declarations found by the lookup of the name
16374   //   is the union of X and Y.
16375   //
16376   // Here, we compute Y and add its members to the overloaded
16377   // candidate set.
16378   for (auto *NS : AssociatedNamespaces) {
16379     //   When considering an associated namespace, the lookup is the
16380     //   same as the lookup performed when the associated namespace is
16381     //   used as a qualifier (3.4.3.2) except that:
16382     //
16383     //     -- Any using-directives in the associated namespace are
16384     //        ignored.
16385     //
16386     //     -- Any namespace-scope friend functions declared in
16387     //        associated classes are visible within their respective
16388     //        namespaces even if they are not visible during an ordinary
16389     //        lookup (11.4).
16390     DeclContext::lookup_result R = NS->lookup(Id.getName());
16391     for (auto *D : R) {
16392       auto *Underlying = D;
16393       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16394         Underlying = USD->getTargetDecl();
16395 
16396       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
16397           !isa<OMPDeclareMapperDecl>(Underlying))
16398         continue;
16399 
16400       if (!SemaRef.isVisible(D)) {
16401         D = findAcceptableDecl(SemaRef, D);
16402         if (!D)
16403           continue;
16404         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16405           Underlying = USD->getTargetDecl();
16406       }
16407       Lookups.emplace_back();
16408       Lookups.back().addDecl(Underlying);
16409     }
16410   }
16411 }
16412 
16413 static ExprResult
16414 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
16415                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
16416                          const DeclarationNameInfo &ReductionId, QualType Ty,
16417                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
16418   if (ReductionIdScopeSpec.isInvalid())
16419     return ExprError();
16420   SmallVector<UnresolvedSet<8>, 4> Lookups;
16421   if (S) {
16422     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16423     Lookup.suppressDiagnostics();
16424     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
16425       NamedDecl *D = Lookup.getRepresentativeDecl();
16426       do {
16427         S = S->getParent();
16428       } while (S && !S->isDeclScope(D));
16429       if (S)
16430         S = S->getParent();
16431       Lookups.emplace_back();
16432       Lookups.back().append(Lookup.begin(), Lookup.end());
16433       Lookup.clear();
16434     }
16435   } else if (auto *ULE =
16436                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
16437     Lookups.push_back(UnresolvedSet<8>());
16438     Decl *PrevD = nullptr;
16439     for (NamedDecl *D : ULE->decls()) {
16440       if (D == PrevD)
16441         Lookups.push_back(UnresolvedSet<8>());
16442       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
16443         Lookups.back().addDecl(DRD);
16444       PrevD = D;
16445     }
16446   }
16447   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16448       Ty->isInstantiationDependentType() ||
16449       Ty->containsUnexpandedParameterPack() ||
16450       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16451         return !D->isInvalidDecl() &&
16452                (D->getType()->isDependentType() ||
16453                 D->getType()->isInstantiationDependentType() ||
16454                 D->getType()->containsUnexpandedParameterPack());
16455       })) {
16456     UnresolvedSet<8> ResSet;
16457     for (const UnresolvedSet<8> &Set : Lookups) {
16458       if (Set.empty())
16459         continue;
16460       ResSet.append(Set.begin(), Set.end());
16461       // The last item marks the end of all declarations at the specified scope.
16462       ResSet.addDecl(Set[Set.size() - 1]);
16463     }
16464     return UnresolvedLookupExpr::Create(
16465         SemaRef.Context, /*NamingClass=*/nullptr,
16466         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16467         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16468   }
16469   // Lookup inside the classes.
16470   // C++ [over.match.oper]p3:
16471   //   For a unary operator @ with an operand of a type whose
16472   //   cv-unqualified version is T1, and for a binary operator @ with
16473   //   a left operand of a type whose cv-unqualified version is T1 and
16474   //   a right operand of a type whose cv-unqualified version is T2,
16475   //   three sets of candidate functions, designated member
16476   //   candidates, non-member candidates and built-in candidates, are
16477   //   constructed as follows:
16478   //     -- If T1 is a complete class type or a class currently being
16479   //        defined, the set of member candidates is the result of the
16480   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16481   //        the set of member candidates is empty.
16482   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16483   Lookup.suppressDiagnostics();
16484   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16485     // Complete the type if it can be completed.
16486     // If the type is neither complete nor being defined, bail out now.
16487     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16488         TyRec->getDecl()->getDefinition()) {
16489       Lookup.clear();
16490       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16491       if (Lookup.empty()) {
16492         Lookups.emplace_back();
16493         Lookups.back().append(Lookup.begin(), Lookup.end());
16494       }
16495     }
16496   }
16497   // Perform ADL.
16498   if (SemaRef.getLangOpts().CPlusPlus)
16499     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16500   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16501           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16502             if (!D->isInvalidDecl() &&
16503                 SemaRef.Context.hasSameType(D->getType(), Ty))
16504               return D;
16505             return nullptr;
16506           }))
16507     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16508                                     VK_LValue, Loc);
16509   if (SemaRef.getLangOpts().CPlusPlus) {
16510     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16511             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16512               if (!D->isInvalidDecl() &&
16513                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16514                   !Ty.isMoreQualifiedThan(D->getType()))
16515                 return D;
16516               return nullptr;
16517             })) {
16518       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16519                          /*DetectVirtual=*/false);
16520       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16521         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16522                 VD->getType().getUnqualifiedType()))) {
16523           if (SemaRef.CheckBaseClassAccess(
16524                   Loc, VD->getType(), Ty, Paths.front(),
16525                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16526             SemaRef.BuildBasePathArray(Paths, BasePath);
16527             return SemaRef.BuildDeclRefExpr(
16528                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16529           }
16530         }
16531       }
16532     }
16533   }
16534   if (ReductionIdScopeSpec.isSet()) {
16535     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16536         << Ty << Range;
16537     return ExprError();
16538   }
16539   return ExprEmpty();
16540 }
16541 
16542 namespace {
16543 /// Data for the reduction-based clauses.
16544 struct ReductionData {
16545   /// List of original reduction items.
16546   SmallVector<Expr *, 8> Vars;
16547   /// List of private copies of the reduction items.
16548   SmallVector<Expr *, 8> Privates;
16549   /// LHS expressions for the reduction_op expressions.
16550   SmallVector<Expr *, 8> LHSs;
16551   /// RHS expressions for the reduction_op expressions.
16552   SmallVector<Expr *, 8> RHSs;
16553   /// Reduction operation expression.
16554   SmallVector<Expr *, 8> ReductionOps;
16555   /// inscan copy operation expressions.
16556   SmallVector<Expr *, 8> InscanCopyOps;
16557   /// inscan copy temp array expressions for prefix sums.
16558   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16559   /// inscan copy temp array element expressions for prefix sums.
16560   SmallVector<Expr *, 8> InscanCopyArrayElems;
16561   /// Taskgroup descriptors for the corresponding reduction items in
16562   /// in_reduction clauses.
16563   SmallVector<Expr *, 8> TaskgroupDescriptors;
16564   /// List of captures for clause.
16565   SmallVector<Decl *, 4> ExprCaptures;
16566   /// List of postupdate expressions.
16567   SmallVector<Expr *, 4> ExprPostUpdates;
16568   /// Reduction modifier.
16569   unsigned RedModifier = 0;
16570   ReductionData() = delete;
16571   /// Reserves required memory for the reduction data.
16572   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16573     Vars.reserve(Size);
16574     Privates.reserve(Size);
16575     LHSs.reserve(Size);
16576     RHSs.reserve(Size);
16577     ReductionOps.reserve(Size);
16578     if (RedModifier == OMPC_REDUCTION_inscan) {
16579       InscanCopyOps.reserve(Size);
16580       InscanCopyArrayTemps.reserve(Size);
16581       InscanCopyArrayElems.reserve(Size);
16582     }
16583     TaskgroupDescriptors.reserve(Size);
16584     ExprCaptures.reserve(Size);
16585     ExprPostUpdates.reserve(Size);
16586   }
16587   /// Stores reduction item and reduction operation only (required for dependent
16588   /// reduction item).
16589   void push(Expr *Item, Expr *ReductionOp) {
16590     Vars.emplace_back(Item);
16591     Privates.emplace_back(nullptr);
16592     LHSs.emplace_back(nullptr);
16593     RHSs.emplace_back(nullptr);
16594     ReductionOps.emplace_back(ReductionOp);
16595     TaskgroupDescriptors.emplace_back(nullptr);
16596     if (RedModifier == OMPC_REDUCTION_inscan) {
16597       InscanCopyOps.push_back(nullptr);
16598       InscanCopyArrayTemps.push_back(nullptr);
16599       InscanCopyArrayElems.push_back(nullptr);
16600     }
16601   }
16602   /// Stores reduction data.
16603   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16604             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16605             Expr *CopyArrayElem) {
16606     Vars.emplace_back(Item);
16607     Privates.emplace_back(Private);
16608     LHSs.emplace_back(LHS);
16609     RHSs.emplace_back(RHS);
16610     ReductionOps.emplace_back(ReductionOp);
16611     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16612     if (RedModifier == OMPC_REDUCTION_inscan) {
16613       InscanCopyOps.push_back(CopyOp);
16614       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16615       InscanCopyArrayElems.push_back(CopyArrayElem);
16616     } else {
16617       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16618              CopyArrayElem == nullptr &&
16619              "Copy operation must be used for inscan reductions only.");
16620     }
16621   }
16622 };
16623 } // namespace
16624 
16625 static bool checkOMPArraySectionConstantForReduction(
16626     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16627     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16628   const Expr *Length = OASE->getLength();
16629   if (Length == nullptr) {
16630     // For array sections of the form [1:] or [:], we would need to analyze
16631     // the lower bound...
16632     if (OASE->getColonLocFirst().isValid())
16633       return false;
16634 
16635     // This is an array subscript which has implicit length 1!
16636     SingleElement = true;
16637     ArraySizes.push_back(llvm::APSInt::get(1));
16638   } else {
16639     Expr::EvalResult Result;
16640     if (!Length->EvaluateAsInt(Result, Context))
16641       return false;
16642 
16643     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16644     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16645     ArraySizes.push_back(ConstantLengthValue);
16646   }
16647 
16648   // Get the base of this array section and walk up from there.
16649   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16650 
16651   // We require length = 1 for all array sections except the right-most to
16652   // guarantee that the memory region is contiguous and has no holes in it.
16653   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16654     Length = TempOASE->getLength();
16655     if (Length == nullptr) {
16656       // For array sections of the form [1:] or [:], we would need to analyze
16657       // the lower bound...
16658       if (OASE->getColonLocFirst().isValid())
16659         return false;
16660 
16661       // This is an array subscript which has implicit length 1!
16662       ArraySizes.push_back(llvm::APSInt::get(1));
16663     } else {
16664       Expr::EvalResult Result;
16665       if (!Length->EvaluateAsInt(Result, Context))
16666         return false;
16667 
16668       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16669       if (ConstantLengthValue.getSExtValue() != 1)
16670         return false;
16671 
16672       ArraySizes.push_back(ConstantLengthValue);
16673     }
16674     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16675   }
16676 
16677   // If we have a single element, we don't need to add the implicit lengths.
16678   if (!SingleElement) {
16679     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16680       // Has implicit length 1!
16681       ArraySizes.push_back(llvm::APSInt::get(1));
16682       Base = TempASE->getBase()->IgnoreParenImpCasts();
16683     }
16684   }
16685 
16686   // This array section can be privatized as a single value or as a constant
16687   // sized array.
16688   return true;
16689 }
16690 
16691 static BinaryOperatorKind
16692 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
16693   if (BOK == BO_Add)
16694     return BO_AddAssign;
16695   if (BOK == BO_Mul)
16696     return BO_MulAssign;
16697   if (BOK == BO_And)
16698     return BO_AndAssign;
16699   if (BOK == BO_Or)
16700     return BO_OrAssign;
16701   if (BOK == BO_Xor)
16702     return BO_XorAssign;
16703   return BOK;
16704 }
16705 
16706 static bool actOnOMPReductionKindClause(
16707     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
16708     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16709     SourceLocation ColonLoc, SourceLocation EndLoc,
16710     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16711     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
16712   DeclarationName DN = ReductionId.getName();
16713   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
16714   BinaryOperatorKind BOK = BO_Comma;
16715 
16716   ASTContext &Context = S.Context;
16717   // OpenMP [2.14.3.6, reduction clause]
16718   // C
16719   // reduction-identifier is either an identifier or one of the following
16720   // operators: +, -, *,  &, |, ^, && and ||
16721   // C++
16722   // reduction-identifier is either an id-expression or one of the following
16723   // operators: +, -, *, &, |, ^, && and ||
16724   switch (OOK) {
16725   case OO_Plus:
16726   case OO_Minus:
16727     BOK = BO_Add;
16728     break;
16729   case OO_Star:
16730     BOK = BO_Mul;
16731     break;
16732   case OO_Amp:
16733     BOK = BO_And;
16734     break;
16735   case OO_Pipe:
16736     BOK = BO_Or;
16737     break;
16738   case OO_Caret:
16739     BOK = BO_Xor;
16740     break;
16741   case OO_AmpAmp:
16742     BOK = BO_LAnd;
16743     break;
16744   case OO_PipePipe:
16745     BOK = BO_LOr;
16746     break;
16747   case OO_New:
16748   case OO_Delete:
16749   case OO_Array_New:
16750   case OO_Array_Delete:
16751   case OO_Slash:
16752   case OO_Percent:
16753   case OO_Tilde:
16754   case OO_Exclaim:
16755   case OO_Equal:
16756   case OO_Less:
16757   case OO_Greater:
16758   case OO_LessEqual:
16759   case OO_GreaterEqual:
16760   case OO_PlusEqual:
16761   case OO_MinusEqual:
16762   case OO_StarEqual:
16763   case OO_SlashEqual:
16764   case OO_PercentEqual:
16765   case OO_CaretEqual:
16766   case OO_AmpEqual:
16767   case OO_PipeEqual:
16768   case OO_LessLess:
16769   case OO_GreaterGreater:
16770   case OO_LessLessEqual:
16771   case OO_GreaterGreaterEqual:
16772   case OO_EqualEqual:
16773   case OO_ExclaimEqual:
16774   case OO_Spaceship:
16775   case OO_PlusPlus:
16776   case OO_MinusMinus:
16777   case OO_Comma:
16778   case OO_ArrowStar:
16779   case OO_Arrow:
16780   case OO_Call:
16781   case OO_Subscript:
16782   case OO_Conditional:
16783   case OO_Coawait:
16784   case NUM_OVERLOADED_OPERATORS:
16785     llvm_unreachable("Unexpected reduction identifier");
16786   case OO_None:
16787     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
16788       if (II->isStr("max"))
16789         BOK = BO_GT;
16790       else if (II->isStr("min"))
16791         BOK = BO_LT;
16792     }
16793     break;
16794   }
16795   SourceRange ReductionIdRange;
16796   if (ReductionIdScopeSpec.isValid())
16797     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
16798   else
16799     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
16800   ReductionIdRange.setEnd(ReductionId.getEndLoc());
16801 
16802   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
16803   bool FirstIter = true;
16804   for (Expr *RefExpr : VarList) {
16805     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
16806     // OpenMP [2.1, C/C++]
16807     //  A list item is a variable or array section, subject to the restrictions
16808     //  specified in Section 2.4 on page 42 and in each of the sections
16809     // describing clauses and directives for which a list appears.
16810     // OpenMP  [2.14.3.3, Restrictions, p.1]
16811     //  A variable that is part of another variable (as an array or
16812     //  structure element) cannot appear in a private clause.
16813     if (!FirstIter && IR != ER)
16814       ++IR;
16815     FirstIter = false;
16816     SourceLocation ELoc;
16817     SourceRange ERange;
16818     Expr *SimpleRefExpr = RefExpr;
16819     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
16820                               /*AllowArraySection=*/true);
16821     if (Res.second) {
16822       // Try to find 'declare reduction' corresponding construct before using
16823       // builtin/overloaded operators.
16824       QualType Type = Context.DependentTy;
16825       CXXCastPath BasePath;
16826       ExprResult DeclareReductionRef = buildDeclareReductionRef(
16827           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16828           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16829       Expr *ReductionOp = nullptr;
16830       if (S.CurContext->isDependentContext() &&
16831           (DeclareReductionRef.isUnset() ||
16832            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
16833         ReductionOp = DeclareReductionRef.get();
16834       // It will be analyzed later.
16835       RD.push(RefExpr, ReductionOp);
16836     }
16837     ValueDecl *D = Res.first;
16838     if (!D)
16839       continue;
16840 
16841     Expr *TaskgroupDescriptor = nullptr;
16842     QualType Type;
16843     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
16844     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
16845     if (ASE) {
16846       Type = ASE->getType().getNonReferenceType();
16847     } else if (OASE) {
16848       QualType BaseType =
16849           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16850       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16851         Type = ATy->getElementType();
16852       else
16853         Type = BaseType->getPointeeType();
16854       Type = Type.getNonReferenceType();
16855     } else {
16856       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
16857     }
16858     auto *VD = dyn_cast<VarDecl>(D);
16859 
16860     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16861     //  A variable that appears in a private clause must not have an incomplete
16862     //  type or a reference type.
16863     if (S.RequireCompleteType(ELoc, D->getType(),
16864                               diag::err_omp_reduction_incomplete_type))
16865       continue;
16866     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16867     // A list item that appears in a reduction clause must not be
16868     // const-qualified.
16869     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
16870                                   /*AcceptIfMutable*/ false, ASE || OASE))
16871       continue;
16872 
16873     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
16874     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
16875     //  If a list-item is a reference type then it must bind to the same object
16876     //  for all threads of the team.
16877     if (!ASE && !OASE) {
16878       if (VD) {
16879         VarDecl *VDDef = VD->getDefinition();
16880         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
16881           DSARefChecker Check(Stack);
16882           if (Check.Visit(VDDef->getInit())) {
16883             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
16884                 << getOpenMPClauseName(ClauseKind) << ERange;
16885             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
16886             continue;
16887           }
16888         }
16889       }
16890 
16891       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16892       // in a Construct]
16893       //  Variables with the predetermined data-sharing attributes may not be
16894       //  listed in data-sharing attributes clauses, except for the cases
16895       //  listed below. For these exceptions only, listing a predetermined
16896       //  variable in a data-sharing attribute clause is allowed and overrides
16897       //  the variable's predetermined data-sharing attributes.
16898       // OpenMP [2.14.3.6, Restrictions, p.3]
16899       //  Any number of reduction clauses can be specified on the directive,
16900       //  but a list item can appear only once in the reduction clauses for that
16901       //  directive.
16902       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16903       if (DVar.CKind == OMPC_reduction) {
16904         S.Diag(ELoc, diag::err_omp_once_referenced)
16905             << getOpenMPClauseName(ClauseKind);
16906         if (DVar.RefExpr)
16907           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
16908         continue;
16909       }
16910       if (DVar.CKind != OMPC_unknown) {
16911         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16912             << getOpenMPClauseName(DVar.CKind)
16913             << getOpenMPClauseName(OMPC_reduction);
16914         reportOriginalDsa(S, Stack, D, DVar);
16915         continue;
16916       }
16917 
16918       // OpenMP [2.14.3.6, Restrictions, p.1]
16919       //  A list item that appears in a reduction clause of a worksharing
16920       //  construct must be shared in the parallel regions to which any of the
16921       //  worksharing regions arising from the worksharing construct bind.
16922       if (isOpenMPWorksharingDirective(CurrDir) &&
16923           !isOpenMPParallelDirective(CurrDir) &&
16924           !isOpenMPTeamsDirective(CurrDir)) {
16925         DVar = Stack->getImplicitDSA(D, true);
16926         if (DVar.CKind != OMPC_shared) {
16927           S.Diag(ELoc, diag::err_omp_required_access)
16928               << getOpenMPClauseName(OMPC_reduction)
16929               << getOpenMPClauseName(OMPC_shared);
16930           reportOriginalDsa(S, Stack, D, DVar);
16931           continue;
16932         }
16933       }
16934     } else {
16935       // Threadprivates cannot be shared between threads, so dignose if the base
16936       // is a threadprivate variable.
16937       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16938       if (DVar.CKind == OMPC_threadprivate) {
16939         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16940             << getOpenMPClauseName(DVar.CKind)
16941             << getOpenMPClauseName(OMPC_reduction);
16942         reportOriginalDsa(S, Stack, D, DVar);
16943         continue;
16944       }
16945     }
16946 
16947     // Try to find 'declare reduction' corresponding construct before using
16948     // builtin/overloaded operators.
16949     CXXCastPath BasePath;
16950     ExprResult DeclareReductionRef = buildDeclareReductionRef(
16951         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16952         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16953     if (DeclareReductionRef.isInvalid())
16954       continue;
16955     if (S.CurContext->isDependentContext() &&
16956         (DeclareReductionRef.isUnset() ||
16957          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
16958       RD.push(RefExpr, DeclareReductionRef.get());
16959       continue;
16960     }
16961     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
16962       // Not allowed reduction identifier is found.
16963       S.Diag(ReductionId.getBeginLoc(),
16964              diag::err_omp_unknown_reduction_identifier)
16965           << Type << ReductionIdRange;
16966       continue;
16967     }
16968 
16969     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16970     // The type of a list item that appears in a reduction clause must be valid
16971     // for the reduction-identifier. For a max or min reduction in C, the type
16972     // of the list item must be an allowed arithmetic data type: char, int,
16973     // float, double, or _Bool, possibly modified with long, short, signed, or
16974     // unsigned. For a max or min reduction in C++, the type of the list item
16975     // must be an allowed arithmetic data type: char, wchar_t, int, float,
16976     // double, or bool, possibly modified with long, short, signed, or unsigned.
16977     if (DeclareReductionRef.isUnset()) {
16978       if ((BOK == BO_GT || BOK == BO_LT) &&
16979           !(Type->isScalarType() ||
16980             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
16981         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
16982             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
16983         if (!ASE && !OASE) {
16984           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16985                                    VarDecl::DeclarationOnly;
16986           S.Diag(D->getLocation(),
16987                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16988               << D;
16989         }
16990         continue;
16991       }
16992       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
16993           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
16994         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
16995             << getOpenMPClauseName(ClauseKind);
16996         if (!ASE && !OASE) {
16997           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16998                                    VarDecl::DeclarationOnly;
16999           S.Diag(D->getLocation(),
17000                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17001               << D;
17002         }
17003         continue;
17004       }
17005     }
17006 
17007     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
17008     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
17009                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17010     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
17011                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17012     QualType PrivateTy = Type;
17013 
17014     // Try if we can determine constant lengths for all array sections and avoid
17015     // the VLA.
17016     bool ConstantLengthOASE = false;
17017     if (OASE) {
17018       bool SingleElement;
17019       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
17020       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
17021           Context, OASE, SingleElement, ArraySizes);
17022 
17023       // If we don't have a single element, we must emit a constant array type.
17024       if (ConstantLengthOASE && !SingleElement) {
17025         for (llvm::APSInt &Size : ArraySizes)
17026           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
17027                                                    ArrayType::Normal,
17028                                                    /*IndexTypeQuals=*/0);
17029       }
17030     }
17031 
17032     if ((OASE && !ConstantLengthOASE) ||
17033         (!OASE && !ASE &&
17034          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
17035       if (!Context.getTargetInfo().isVLASupported()) {
17036         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
17037           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17038           S.Diag(ELoc, diag::note_vla_unsupported);
17039           continue;
17040         } else {
17041           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17042           S.targetDiag(ELoc, diag::note_vla_unsupported);
17043         }
17044       }
17045       // For arrays/array sections only:
17046       // Create pseudo array type for private copy. The size for this array will
17047       // be generated during codegen.
17048       // For array subscripts or single variables Private Ty is the same as Type
17049       // (type of the variable or single array element).
17050       PrivateTy = Context.getVariableArrayType(
17051           Type,
17052           new (Context)
17053               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
17054           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
17055     } else if (!ASE && !OASE &&
17056                Context.getAsArrayType(D->getType().getNonReferenceType())) {
17057       PrivateTy = D->getType().getNonReferenceType();
17058     }
17059     // Private copy.
17060     VarDecl *PrivateVD =
17061         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17062                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17063                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17064     // Add initializer for private variable.
17065     Expr *Init = nullptr;
17066     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
17067     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
17068     if (DeclareReductionRef.isUsable()) {
17069       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
17070       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
17071       if (DRD->getInitializer()) {
17072         S.ActOnUninitializedDecl(PrivateVD);
17073         Init = DRDRef;
17074         RHSVD->setInit(DRDRef);
17075         RHSVD->setInitStyle(VarDecl::CallInit);
17076       }
17077     } else {
17078       switch (BOK) {
17079       case BO_Add:
17080       case BO_Xor:
17081       case BO_Or:
17082       case BO_LOr:
17083         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
17084         if (Type->isScalarType() || Type->isAnyComplexType())
17085           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
17086         break;
17087       case BO_Mul:
17088       case BO_LAnd:
17089         if (Type->isScalarType() || Type->isAnyComplexType()) {
17090           // '*' and '&&' reduction ops - initializer is '1'.
17091           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
17092         }
17093         break;
17094       case BO_And: {
17095         // '&' reduction op - initializer is '~0'.
17096         QualType OrigType = Type;
17097         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
17098           Type = ComplexTy->getElementType();
17099         if (Type->isRealFloatingType()) {
17100           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
17101               Context.getFloatTypeSemantics(Type),
17102               Context.getTypeSize(Type));
17103           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17104                                          Type, ELoc);
17105         } else if (Type->isScalarType()) {
17106           uint64_t Size = Context.getTypeSize(Type);
17107           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
17108           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
17109           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17110         }
17111         if (Init && OrigType->isAnyComplexType()) {
17112           // Init = 0xFFFF + 0xFFFFi;
17113           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
17114           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
17115         }
17116         Type = OrigType;
17117         break;
17118       }
17119       case BO_LT:
17120       case BO_GT: {
17121         // 'min' reduction op - initializer is 'Largest representable number in
17122         // the reduction list item type'.
17123         // 'max' reduction op - initializer is 'Least representable number in
17124         // the reduction list item type'.
17125         if (Type->isIntegerType() || Type->isPointerType()) {
17126           bool IsSigned = Type->hasSignedIntegerRepresentation();
17127           uint64_t Size = Context.getTypeSize(Type);
17128           QualType IntTy =
17129               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
17130           llvm::APInt InitValue =
17131               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
17132                                         : llvm::APInt::getMinValue(Size)
17133                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
17134                                         : llvm::APInt::getMaxValue(Size);
17135           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17136           if (Type->isPointerType()) {
17137             // Cast to pointer type.
17138             ExprResult CastExpr = S.BuildCStyleCastExpr(
17139                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
17140             if (CastExpr.isInvalid())
17141               continue;
17142             Init = CastExpr.get();
17143           }
17144         } else if (Type->isRealFloatingType()) {
17145           llvm::APFloat InitValue = llvm::APFloat::getLargest(
17146               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
17147           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17148                                          Type, ELoc);
17149         }
17150         break;
17151       }
17152       case BO_PtrMemD:
17153       case BO_PtrMemI:
17154       case BO_MulAssign:
17155       case BO_Div:
17156       case BO_Rem:
17157       case BO_Sub:
17158       case BO_Shl:
17159       case BO_Shr:
17160       case BO_LE:
17161       case BO_GE:
17162       case BO_EQ:
17163       case BO_NE:
17164       case BO_Cmp:
17165       case BO_AndAssign:
17166       case BO_XorAssign:
17167       case BO_OrAssign:
17168       case BO_Assign:
17169       case BO_AddAssign:
17170       case BO_SubAssign:
17171       case BO_DivAssign:
17172       case BO_RemAssign:
17173       case BO_ShlAssign:
17174       case BO_ShrAssign:
17175       case BO_Comma:
17176         llvm_unreachable("Unexpected reduction operation");
17177       }
17178     }
17179     if (Init && DeclareReductionRef.isUnset()) {
17180       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
17181       // Store initializer for single element in private copy. Will be used
17182       // during codegen.
17183       PrivateVD->setInit(RHSVD->getInit());
17184       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17185     } else if (!Init) {
17186       S.ActOnUninitializedDecl(RHSVD);
17187       // Store initializer for single element in private copy. Will be used
17188       // during codegen.
17189       PrivateVD->setInit(RHSVD->getInit());
17190       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17191     }
17192     if (RHSVD->isInvalidDecl())
17193       continue;
17194     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
17195       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
17196           << Type << ReductionIdRange;
17197       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17198                                VarDecl::DeclarationOnly;
17199       S.Diag(D->getLocation(),
17200              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17201           << D;
17202       continue;
17203     }
17204     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
17205     ExprResult ReductionOp;
17206     if (DeclareReductionRef.isUsable()) {
17207       QualType RedTy = DeclareReductionRef.get()->getType();
17208       QualType PtrRedTy = Context.getPointerType(RedTy);
17209       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
17210       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
17211       if (!BasePath.empty()) {
17212         LHS = S.DefaultLvalueConversion(LHS.get());
17213         RHS = S.DefaultLvalueConversion(RHS.get());
17214         LHS = ImplicitCastExpr::Create(
17215             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
17216             LHS.get()->getValueKind(), FPOptionsOverride());
17217         RHS = ImplicitCastExpr::Create(
17218             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
17219             RHS.get()->getValueKind(), FPOptionsOverride());
17220       }
17221       FunctionProtoType::ExtProtoInfo EPI;
17222       QualType Params[] = {PtrRedTy, PtrRedTy};
17223       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
17224       auto *OVE = new (Context) OpaqueValueExpr(
17225           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
17226           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
17227       Expr *Args[] = {LHS.get(), RHS.get()};
17228       ReductionOp =
17229           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
17230                            S.CurFPFeatureOverrides());
17231     } else {
17232       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
17233       if (Type->isRecordType() && CombBOK != BOK) {
17234         Sema::TentativeAnalysisScope Trap(S);
17235         ReductionOp =
17236             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17237                          CombBOK, LHSDRE, RHSDRE);
17238       }
17239       if (!ReductionOp.isUsable()) {
17240         ReductionOp =
17241             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
17242                          LHSDRE, RHSDRE);
17243         if (ReductionOp.isUsable()) {
17244           if (BOK != BO_LT && BOK != BO_GT) {
17245             ReductionOp =
17246                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17247                              BO_Assign, LHSDRE, ReductionOp.get());
17248           } else {
17249             auto *ConditionalOp = new (Context)
17250                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
17251                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
17252             ReductionOp =
17253                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17254                              BO_Assign, LHSDRE, ConditionalOp);
17255           }
17256         }
17257       }
17258       if (ReductionOp.isUsable())
17259         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
17260                                             /*DiscardedValue*/ false);
17261       if (!ReductionOp.isUsable())
17262         continue;
17263     }
17264 
17265     // Add copy operations for inscan reductions.
17266     // LHS = RHS;
17267     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
17268     if (ClauseKind == OMPC_reduction &&
17269         RD.RedModifier == OMPC_REDUCTION_inscan) {
17270       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
17271       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
17272                                RHS.get());
17273       if (!CopyOpRes.isUsable())
17274         continue;
17275       CopyOpRes =
17276           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
17277       if (!CopyOpRes.isUsable())
17278         continue;
17279       // For simd directive and simd-based directives in simd mode no need to
17280       // construct temp array, need just a single temp element.
17281       if (Stack->getCurrentDirective() == OMPD_simd ||
17282           (S.getLangOpts().OpenMPSimd &&
17283            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
17284         VarDecl *TempArrayVD =
17285             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17286                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17287         // Add a constructor to the temp decl.
17288         S.ActOnUninitializedDecl(TempArrayVD);
17289         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
17290       } else {
17291         // Build temp array for prefix sum.
17292         auto *Dim = new (S.Context)
17293             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17294         QualType ArrayTy =
17295             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
17296                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
17297         VarDecl *TempArrayVD =
17298             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
17299                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17300         // Add a constructor to the temp decl.
17301         S.ActOnUninitializedDecl(TempArrayVD);
17302         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
17303         TempArrayElem =
17304             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
17305         auto *Idx = new (S.Context)
17306             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17307         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
17308                                                           ELoc, Idx, ELoc);
17309       }
17310     }
17311 
17312     // OpenMP [2.15.4.6, Restrictions, p.2]
17313     // A list item that appears in an in_reduction clause of a task construct
17314     // must appear in a task_reduction clause of a construct associated with a
17315     // taskgroup region that includes the participating task in its taskgroup
17316     // set. The construct associated with the innermost region that meets this
17317     // condition must specify the same reduction-identifier as the in_reduction
17318     // clause.
17319     if (ClauseKind == OMPC_in_reduction) {
17320       SourceRange ParentSR;
17321       BinaryOperatorKind ParentBOK;
17322       const Expr *ParentReductionOp = nullptr;
17323       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
17324       DSAStackTy::DSAVarData ParentBOKDSA =
17325           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
17326                                                   ParentBOKTD);
17327       DSAStackTy::DSAVarData ParentReductionOpDSA =
17328           Stack->getTopMostTaskgroupReductionData(
17329               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
17330       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
17331       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
17332       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
17333           (DeclareReductionRef.isUsable() && IsParentBOK) ||
17334           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
17335         bool EmitError = true;
17336         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
17337           llvm::FoldingSetNodeID RedId, ParentRedId;
17338           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
17339           DeclareReductionRef.get()->Profile(RedId, Context,
17340                                              /*Canonical=*/true);
17341           EmitError = RedId != ParentRedId;
17342         }
17343         if (EmitError) {
17344           S.Diag(ReductionId.getBeginLoc(),
17345                  diag::err_omp_reduction_identifier_mismatch)
17346               << ReductionIdRange << RefExpr->getSourceRange();
17347           S.Diag(ParentSR.getBegin(),
17348                  diag::note_omp_previous_reduction_identifier)
17349               << ParentSR
17350               << (IsParentBOK ? ParentBOKDSA.RefExpr
17351                               : ParentReductionOpDSA.RefExpr)
17352                      ->getSourceRange();
17353           continue;
17354         }
17355       }
17356       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
17357     }
17358 
17359     DeclRefExpr *Ref = nullptr;
17360     Expr *VarsExpr = RefExpr->IgnoreParens();
17361     if (!VD && !S.CurContext->isDependentContext()) {
17362       if (ASE || OASE) {
17363         TransformExprToCaptures RebuildToCapture(S, D);
17364         VarsExpr =
17365             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
17366         Ref = RebuildToCapture.getCapturedExpr();
17367       } else {
17368         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
17369       }
17370       if (!S.isOpenMPCapturedDecl(D)) {
17371         RD.ExprCaptures.emplace_back(Ref->getDecl());
17372         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17373           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
17374           if (!RefRes.isUsable())
17375             continue;
17376           ExprResult PostUpdateRes =
17377               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17378                            RefRes.get());
17379           if (!PostUpdateRes.isUsable())
17380             continue;
17381           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
17382               Stack->getCurrentDirective() == OMPD_taskgroup) {
17383             S.Diag(RefExpr->getExprLoc(),
17384                    diag::err_omp_reduction_non_addressable_expression)
17385                 << RefExpr->getSourceRange();
17386             continue;
17387           }
17388           RD.ExprPostUpdates.emplace_back(
17389               S.IgnoredValueConversions(PostUpdateRes.get()).get());
17390         }
17391       }
17392     }
17393     // All reduction items are still marked as reduction (to do not increase
17394     // code base size).
17395     unsigned Modifier = RD.RedModifier;
17396     // Consider task_reductions as reductions with task modifier. Required for
17397     // correct analysis of in_reduction clauses.
17398     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
17399       Modifier = OMPC_REDUCTION_task;
17400     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
17401                   ASE || OASE);
17402     if (Modifier == OMPC_REDUCTION_task &&
17403         (CurrDir == OMPD_taskgroup ||
17404          ((isOpenMPParallelDirective(CurrDir) ||
17405            isOpenMPWorksharingDirective(CurrDir)) &&
17406           !isOpenMPSimdDirective(CurrDir)))) {
17407       if (DeclareReductionRef.isUsable())
17408         Stack->addTaskgroupReductionData(D, ReductionIdRange,
17409                                          DeclareReductionRef.get());
17410       else
17411         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
17412     }
17413     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
17414             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
17415             TempArrayElem.get());
17416   }
17417   return RD.Vars.empty();
17418 }
17419 
17420 OMPClause *Sema::ActOnOpenMPReductionClause(
17421     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
17422     SourceLocation StartLoc, SourceLocation LParenLoc,
17423     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
17424     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17425     ArrayRef<Expr *> UnresolvedReductions) {
17426   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
17427     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
17428         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
17429                                    /*Last=*/OMPC_REDUCTION_unknown)
17430         << getOpenMPClauseName(OMPC_reduction);
17431     return nullptr;
17432   }
17433   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
17434   // A reduction clause with the inscan reduction-modifier may only appear on a
17435   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
17436   // construct, a parallel worksharing-loop construct or a parallel
17437   // worksharing-loop SIMD construct.
17438   if (Modifier == OMPC_REDUCTION_inscan &&
17439       (DSAStack->getCurrentDirective() != OMPD_for &&
17440        DSAStack->getCurrentDirective() != OMPD_for_simd &&
17441        DSAStack->getCurrentDirective() != OMPD_simd &&
17442        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
17443        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
17444     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
17445     return nullptr;
17446   }
17447 
17448   ReductionData RD(VarList.size(), Modifier);
17449   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
17450                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17451                                   ReductionIdScopeSpec, ReductionId,
17452                                   UnresolvedReductions, RD))
17453     return nullptr;
17454 
17455   return OMPReductionClause::Create(
17456       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
17457       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17458       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
17459       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
17460       buildPreInits(Context, RD.ExprCaptures),
17461       buildPostUpdate(*this, RD.ExprPostUpdates));
17462 }
17463 
17464 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
17465     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17466     SourceLocation ColonLoc, SourceLocation EndLoc,
17467     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17468     ArrayRef<Expr *> UnresolvedReductions) {
17469   ReductionData RD(VarList.size());
17470   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17471                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17472                                   ReductionIdScopeSpec, ReductionId,
17473                                   UnresolvedReductions, RD))
17474     return nullptr;
17475 
17476   return OMPTaskReductionClause::Create(
17477       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17478       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17479       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17480       buildPreInits(Context, RD.ExprCaptures),
17481       buildPostUpdate(*this, RD.ExprPostUpdates));
17482 }
17483 
17484 OMPClause *Sema::ActOnOpenMPInReductionClause(
17485     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17486     SourceLocation ColonLoc, SourceLocation EndLoc,
17487     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17488     ArrayRef<Expr *> UnresolvedReductions) {
17489   ReductionData RD(VarList.size());
17490   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17491                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17492                                   ReductionIdScopeSpec, ReductionId,
17493                                   UnresolvedReductions, RD))
17494     return nullptr;
17495 
17496   return OMPInReductionClause::Create(
17497       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17498       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17499       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17500       buildPreInits(Context, RD.ExprCaptures),
17501       buildPostUpdate(*this, RD.ExprPostUpdates));
17502 }
17503 
17504 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17505                                      SourceLocation LinLoc) {
17506   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17507       LinKind == OMPC_LINEAR_unknown) {
17508     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17509     return true;
17510   }
17511   return false;
17512 }
17513 
17514 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17515                                  OpenMPLinearClauseKind LinKind, QualType Type,
17516                                  bool IsDeclareSimd) {
17517   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17518   // A variable must not have an incomplete type or a reference type.
17519   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17520     return true;
17521   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17522       !Type->isReferenceType()) {
17523     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17524         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17525     return true;
17526   }
17527   Type = Type.getNonReferenceType();
17528 
17529   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17530   // A variable that is privatized must not have a const-qualified type
17531   // unless it is of class type with a mutable member. This restriction does
17532   // not apply to the firstprivate clause, nor to the linear clause on
17533   // declarative directives (like declare simd).
17534   if (!IsDeclareSimd &&
17535       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17536     return true;
17537 
17538   // A list item must be of integral or pointer type.
17539   Type = Type.getUnqualifiedType().getCanonicalType();
17540   const auto *Ty = Type.getTypePtrOrNull();
17541   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17542               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17543     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17544     if (D) {
17545       bool IsDecl =
17546           !VD ||
17547           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17548       Diag(D->getLocation(),
17549            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17550           << D;
17551     }
17552     return true;
17553   }
17554   return false;
17555 }
17556 
17557 OMPClause *Sema::ActOnOpenMPLinearClause(
17558     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17559     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17560     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17561   SmallVector<Expr *, 8> Vars;
17562   SmallVector<Expr *, 8> Privates;
17563   SmallVector<Expr *, 8> Inits;
17564   SmallVector<Decl *, 4> ExprCaptures;
17565   SmallVector<Expr *, 4> ExprPostUpdates;
17566   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17567     LinKind = OMPC_LINEAR_val;
17568   for (Expr *RefExpr : VarList) {
17569     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17570     SourceLocation ELoc;
17571     SourceRange ERange;
17572     Expr *SimpleRefExpr = RefExpr;
17573     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17574     if (Res.second) {
17575       // It will be analyzed later.
17576       Vars.push_back(RefExpr);
17577       Privates.push_back(nullptr);
17578       Inits.push_back(nullptr);
17579     }
17580     ValueDecl *D = Res.first;
17581     if (!D)
17582       continue;
17583 
17584     QualType Type = D->getType();
17585     auto *VD = dyn_cast<VarDecl>(D);
17586 
17587     // OpenMP [2.14.3.7, linear clause]
17588     //  A list-item cannot appear in more than one linear clause.
17589     //  A list-item that appears in a linear clause cannot appear in any
17590     //  other data-sharing attribute clause.
17591     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17592     if (DVar.RefExpr) {
17593       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17594                                           << getOpenMPClauseName(OMPC_linear);
17595       reportOriginalDsa(*this, DSAStack, D, DVar);
17596       continue;
17597     }
17598 
17599     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17600       continue;
17601     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17602 
17603     // Build private copy of original var.
17604     VarDecl *Private =
17605         buildVarDecl(*this, ELoc, Type, D->getName(),
17606                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17607                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17608     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17609     // Build var to save initial value.
17610     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17611     Expr *InitExpr;
17612     DeclRefExpr *Ref = nullptr;
17613     if (!VD && !CurContext->isDependentContext()) {
17614       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17615       if (!isOpenMPCapturedDecl(D)) {
17616         ExprCaptures.push_back(Ref->getDecl());
17617         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17618           ExprResult RefRes = DefaultLvalueConversion(Ref);
17619           if (!RefRes.isUsable())
17620             continue;
17621           ExprResult PostUpdateRes =
17622               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17623                          SimpleRefExpr, RefRes.get());
17624           if (!PostUpdateRes.isUsable())
17625             continue;
17626           ExprPostUpdates.push_back(
17627               IgnoredValueConversions(PostUpdateRes.get()).get());
17628         }
17629       }
17630     }
17631     if (LinKind == OMPC_LINEAR_uval)
17632       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17633     else
17634       InitExpr = VD ? SimpleRefExpr : Ref;
17635     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17636                          /*DirectInit=*/false);
17637     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17638 
17639     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17640     Vars.push_back((VD || CurContext->isDependentContext())
17641                        ? RefExpr->IgnoreParens()
17642                        : Ref);
17643     Privates.push_back(PrivateRef);
17644     Inits.push_back(InitRef);
17645   }
17646 
17647   if (Vars.empty())
17648     return nullptr;
17649 
17650   Expr *StepExpr = Step;
17651   Expr *CalcStepExpr = nullptr;
17652   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17653       !Step->isInstantiationDependent() &&
17654       !Step->containsUnexpandedParameterPack()) {
17655     SourceLocation StepLoc = Step->getBeginLoc();
17656     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17657     if (Val.isInvalid())
17658       return nullptr;
17659     StepExpr = Val.get();
17660 
17661     // Build var to save the step value.
17662     VarDecl *SaveVar =
17663         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17664     ExprResult SaveRef =
17665         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17666     ExprResult CalcStep =
17667         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17668     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17669 
17670     // Warn about zero linear step (it would be probably better specified as
17671     // making corresponding variables 'const').
17672     if (Optional<llvm::APSInt> Result =
17673             StepExpr->getIntegerConstantExpr(Context)) {
17674       if (!Result->isNegative() && !Result->isStrictlyPositive())
17675         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17676             << Vars[0] << (Vars.size() > 1);
17677     } else if (CalcStep.isUsable()) {
17678       // Calculate the step beforehand instead of doing this on each iteration.
17679       // (This is not used if the number of iterations may be kfold-ed).
17680       CalcStepExpr = CalcStep.get();
17681     }
17682   }
17683 
17684   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17685                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17686                                  StepExpr, CalcStepExpr,
17687                                  buildPreInits(Context, ExprCaptures),
17688                                  buildPostUpdate(*this, ExprPostUpdates));
17689 }
17690 
17691 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
17692                                      Expr *NumIterations, Sema &SemaRef,
17693                                      Scope *S, DSAStackTy *Stack) {
17694   // Walk the vars and build update/final expressions for the CodeGen.
17695   SmallVector<Expr *, 8> Updates;
17696   SmallVector<Expr *, 8> Finals;
17697   SmallVector<Expr *, 8> UsedExprs;
17698   Expr *Step = Clause.getStep();
17699   Expr *CalcStep = Clause.getCalcStep();
17700   // OpenMP [2.14.3.7, linear clause]
17701   // If linear-step is not specified it is assumed to be 1.
17702   if (!Step)
17703     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
17704   else if (CalcStep)
17705     Step = cast<BinaryOperator>(CalcStep)->getLHS();
17706   bool HasErrors = false;
17707   auto CurInit = Clause.inits().begin();
17708   auto CurPrivate = Clause.privates().begin();
17709   OpenMPLinearClauseKind LinKind = Clause.getModifier();
17710   for (Expr *RefExpr : Clause.varlists()) {
17711     SourceLocation ELoc;
17712     SourceRange ERange;
17713     Expr *SimpleRefExpr = RefExpr;
17714     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
17715     ValueDecl *D = Res.first;
17716     if (Res.second || !D) {
17717       Updates.push_back(nullptr);
17718       Finals.push_back(nullptr);
17719       HasErrors = true;
17720       continue;
17721     }
17722     auto &&Info = Stack->isLoopControlVariable(D);
17723     // OpenMP [2.15.11, distribute simd Construct]
17724     // A list item may not appear in a linear clause, unless it is the loop
17725     // iteration variable.
17726     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
17727         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
17728       SemaRef.Diag(ELoc,
17729                    diag::err_omp_linear_distribute_var_non_loop_iteration);
17730       Updates.push_back(nullptr);
17731       Finals.push_back(nullptr);
17732       HasErrors = true;
17733       continue;
17734     }
17735     Expr *InitExpr = *CurInit;
17736 
17737     // Build privatized reference to the current linear var.
17738     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
17739     Expr *CapturedRef;
17740     if (LinKind == OMPC_LINEAR_uval)
17741       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
17742     else
17743       CapturedRef =
17744           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
17745                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
17746                            /*RefersToCapture=*/true);
17747 
17748     // Build update: Var = InitExpr + IV * Step
17749     ExprResult Update;
17750     if (!Info.first)
17751       Update = buildCounterUpdate(
17752           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
17753           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
17754     else
17755       Update = *CurPrivate;
17756     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
17757                                          /*DiscardedValue*/ false);
17758 
17759     // Build final: Var = InitExpr + NumIterations * Step
17760     ExprResult Final;
17761     if (!Info.first)
17762       Final =
17763           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
17764                              InitExpr, NumIterations, Step, /*Subtract=*/false,
17765                              /*IsNonRectangularLB=*/false);
17766     else
17767       Final = *CurPrivate;
17768     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
17769                                         /*DiscardedValue*/ false);
17770 
17771     if (!Update.isUsable() || !Final.isUsable()) {
17772       Updates.push_back(nullptr);
17773       Finals.push_back(nullptr);
17774       UsedExprs.push_back(nullptr);
17775       HasErrors = true;
17776     } else {
17777       Updates.push_back(Update.get());
17778       Finals.push_back(Final.get());
17779       if (!Info.first)
17780         UsedExprs.push_back(SimpleRefExpr);
17781     }
17782     ++CurInit;
17783     ++CurPrivate;
17784   }
17785   if (Expr *S = Clause.getStep())
17786     UsedExprs.push_back(S);
17787   // Fill the remaining part with the nullptr.
17788   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
17789   Clause.setUpdates(Updates);
17790   Clause.setFinals(Finals);
17791   Clause.setUsedExprs(UsedExprs);
17792   return HasErrors;
17793 }
17794 
17795 OMPClause *Sema::ActOnOpenMPAlignedClause(
17796     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
17797     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17798   SmallVector<Expr *, 8> Vars;
17799   for (Expr *RefExpr : VarList) {
17800     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17801     SourceLocation ELoc;
17802     SourceRange ERange;
17803     Expr *SimpleRefExpr = RefExpr;
17804     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17805     if (Res.second) {
17806       // It will be analyzed later.
17807       Vars.push_back(RefExpr);
17808     }
17809     ValueDecl *D = Res.first;
17810     if (!D)
17811       continue;
17812 
17813     QualType QType = D->getType();
17814     auto *VD = dyn_cast<VarDecl>(D);
17815 
17816     // OpenMP  [2.8.1, simd construct, Restrictions]
17817     // The type of list items appearing in the aligned clause must be
17818     // array, pointer, reference to array, or reference to pointer.
17819     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17820     const Type *Ty = QType.getTypePtrOrNull();
17821     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
17822       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
17823           << QType << getLangOpts().CPlusPlus << ERange;
17824       bool IsDecl =
17825           !VD ||
17826           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17827       Diag(D->getLocation(),
17828            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17829           << D;
17830       continue;
17831     }
17832 
17833     // OpenMP  [2.8.1, simd construct, Restrictions]
17834     // A list-item cannot appear in more than one aligned clause.
17835     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
17836       Diag(ELoc, diag::err_omp_used_in_clause_twice)
17837           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
17838       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17839           << getOpenMPClauseName(OMPC_aligned);
17840       continue;
17841     }
17842 
17843     DeclRefExpr *Ref = nullptr;
17844     if (!VD && isOpenMPCapturedDecl(D))
17845       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17846     Vars.push_back(DefaultFunctionArrayConversion(
17847                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
17848                        .get());
17849   }
17850 
17851   // OpenMP [2.8.1, simd construct, Description]
17852   // The parameter of the aligned clause, alignment, must be a constant
17853   // positive integer expression.
17854   // If no optional parameter is specified, implementation-defined default
17855   // alignments for SIMD instructions on the target platforms are assumed.
17856   if (Alignment != nullptr) {
17857     ExprResult AlignResult =
17858         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
17859     if (AlignResult.isInvalid())
17860       return nullptr;
17861     Alignment = AlignResult.get();
17862   }
17863   if (Vars.empty())
17864     return nullptr;
17865 
17866   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
17867                                   EndLoc, Vars, Alignment);
17868 }
17869 
17870 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
17871                                          SourceLocation StartLoc,
17872                                          SourceLocation LParenLoc,
17873                                          SourceLocation EndLoc) {
17874   SmallVector<Expr *, 8> Vars;
17875   SmallVector<Expr *, 8> SrcExprs;
17876   SmallVector<Expr *, 8> DstExprs;
17877   SmallVector<Expr *, 8> AssignmentOps;
17878   for (Expr *RefExpr : VarList) {
17879     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
17880     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17881       // It will be analyzed later.
17882       Vars.push_back(RefExpr);
17883       SrcExprs.push_back(nullptr);
17884       DstExprs.push_back(nullptr);
17885       AssignmentOps.push_back(nullptr);
17886       continue;
17887     }
17888 
17889     SourceLocation ELoc = RefExpr->getExprLoc();
17890     // OpenMP [2.1, C/C++]
17891     //  A list item is a variable name.
17892     // OpenMP  [2.14.4.1, Restrictions, p.1]
17893     //  A list item that appears in a copyin clause must be threadprivate.
17894     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
17895     if (!DE || !isa<VarDecl>(DE->getDecl())) {
17896       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
17897           << 0 << RefExpr->getSourceRange();
17898       continue;
17899     }
17900 
17901     Decl *D = DE->getDecl();
17902     auto *VD = cast<VarDecl>(D);
17903 
17904     QualType Type = VD->getType();
17905     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
17906       // It will be analyzed later.
17907       Vars.push_back(DE);
17908       SrcExprs.push_back(nullptr);
17909       DstExprs.push_back(nullptr);
17910       AssignmentOps.push_back(nullptr);
17911       continue;
17912     }
17913 
17914     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
17915     //  A list item that appears in a copyin clause must be threadprivate.
17916     if (!DSAStack->isThreadPrivate(VD)) {
17917       Diag(ELoc, diag::err_omp_required_access)
17918           << getOpenMPClauseName(OMPC_copyin)
17919           << getOpenMPDirectiveName(OMPD_threadprivate);
17920       continue;
17921     }
17922 
17923     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17924     //  A variable of class type (or array thereof) that appears in a
17925     //  copyin clause requires an accessible, unambiguous copy assignment
17926     //  operator for the class type.
17927     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17928     VarDecl *SrcVD =
17929         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
17930                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17931     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
17932         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
17933     VarDecl *DstVD =
17934         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
17935                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17936     DeclRefExpr *PseudoDstExpr =
17937         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
17938     // For arrays generate assignment operation for single element and replace
17939     // it by the original array element in CodeGen.
17940     ExprResult AssignmentOp =
17941         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
17942                    PseudoSrcExpr);
17943     if (AssignmentOp.isInvalid())
17944       continue;
17945     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
17946                                        /*DiscardedValue*/ false);
17947     if (AssignmentOp.isInvalid())
17948       continue;
17949 
17950     DSAStack->addDSA(VD, DE, OMPC_copyin);
17951     Vars.push_back(DE);
17952     SrcExprs.push_back(PseudoSrcExpr);
17953     DstExprs.push_back(PseudoDstExpr);
17954     AssignmentOps.push_back(AssignmentOp.get());
17955   }
17956 
17957   if (Vars.empty())
17958     return nullptr;
17959 
17960   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17961                                  SrcExprs, DstExprs, AssignmentOps);
17962 }
17963 
17964 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
17965                                               SourceLocation StartLoc,
17966                                               SourceLocation LParenLoc,
17967                                               SourceLocation EndLoc) {
17968   SmallVector<Expr *, 8> Vars;
17969   SmallVector<Expr *, 8> SrcExprs;
17970   SmallVector<Expr *, 8> DstExprs;
17971   SmallVector<Expr *, 8> AssignmentOps;
17972   for (Expr *RefExpr : VarList) {
17973     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17974     SourceLocation ELoc;
17975     SourceRange ERange;
17976     Expr *SimpleRefExpr = RefExpr;
17977     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17978     if (Res.second) {
17979       // It will be analyzed later.
17980       Vars.push_back(RefExpr);
17981       SrcExprs.push_back(nullptr);
17982       DstExprs.push_back(nullptr);
17983       AssignmentOps.push_back(nullptr);
17984     }
17985     ValueDecl *D = Res.first;
17986     if (!D)
17987       continue;
17988 
17989     QualType Type = D->getType();
17990     auto *VD = dyn_cast<VarDecl>(D);
17991 
17992     // OpenMP [2.14.4.2, Restrictions, p.2]
17993     //  A list item that appears in a copyprivate clause may not appear in a
17994     //  private or firstprivate clause on the single construct.
17995     if (!VD || !DSAStack->isThreadPrivate(VD)) {
17996       DSAStackTy::DSAVarData DVar =
17997           DSAStack->getTopDSA(D, /*FromParent=*/false);
17998       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
17999           DVar.RefExpr) {
18000         Diag(ELoc, diag::err_omp_wrong_dsa)
18001             << getOpenMPClauseName(DVar.CKind)
18002             << getOpenMPClauseName(OMPC_copyprivate);
18003         reportOriginalDsa(*this, DSAStack, D, DVar);
18004         continue;
18005       }
18006 
18007       // OpenMP [2.11.4.2, Restrictions, p.1]
18008       //  All list items that appear in a copyprivate clause must be either
18009       //  threadprivate or private in the enclosing context.
18010       if (DVar.CKind == OMPC_unknown) {
18011         DVar = DSAStack->getImplicitDSA(D, false);
18012         if (DVar.CKind == OMPC_shared) {
18013           Diag(ELoc, diag::err_omp_required_access)
18014               << getOpenMPClauseName(OMPC_copyprivate)
18015               << "threadprivate or private in the enclosing context";
18016           reportOriginalDsa(*this, DSAStack, D, DVar);
18017           continue;
18018         }
18019       }
18020     }
18021 
18022     // Variably modified types are not supported.
18023     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
18024       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
18025           << getOpenMPClauseName(OMPC_copyprivate) << Type
18026           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18027       bool IsDecl =
18028           !VD ||
18029           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
18030       Diag(D->getLocation(),
18031            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18032           << D;
18033       continue;
18034     }
18035 
18036     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18037     //  A variable of class type (or array thereof) that appears in a
18038     //  copyin clause requires an accessible, unambiguous copy assignment
18039     //  operator for the class type.
18040     Type = Context.getBaseElementType(Type.getNonReferenceType())
18041                .getUnqualifiedType();
18042     VarDecl *SrcVD =
18043         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
18044                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18045     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
18046     VarDecl *DstVD =
18047         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
18048                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18049     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
18050     ExprResult AssignmentOp = BuildBinOp(
18051         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
18052     if (AssignmentOp.isInvalid())
18053       continue;
18054     AssignmentOp =
18055         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
18056     if (AssignmentOp.isInvalid())
18057       continue;
18058 
18059     // No need to mark vars as copyprivate, they are already threadprivate or
18060     // implicitly private.
18061     assert(VD || isOpenMPCapturedDecl(D));
18062     Vars.push_back(
18063         VD ? RefExpr->IgnoreParens()
18064            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
18065     SrcExprs.push_back(PseudoSrcExpr);
18066     DstExprs.push_back(PseudoDstExpr);
18067     AssignmentOps.push_back(AssignmentOp.get());
18068   }
18069 
18070   if (Vars.empty())
18071     return nullptr;
18072 
18073   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18074                                       Vars, SrcExprs, DstExprs, AssignmentOps);
18075 }
18076 
18077 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
18078                                         SourceLocation StartLoc,
18079                                         SourceLocation LParenLoc,
18080                                         SourceLocation EndLoc) {
18081   if (VarList.empty())
18082     return nullptr;
18083 
18084   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
18085 }
18086 
18087 /// Tries to find omp_depend_t. type.
18088 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
18089                            bool Diagnose = true) {
18090   QualType OMPDependT = Stack->getOMPDependT();
18091   if (!OMPDependT.isNull())
18092     return true;
18093   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
18094   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18095   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18096     if (Diagnose)
18097       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
18098     return false;
18099   }
18100   Stack->setOMPDependT(PT.get());
18101   return true;
18102 }
18103 
18104 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
18105                                          SourceLocation LParenLoc,
18106                                          SourceLocation EndLoc) {
18107   if (!Depobj)
18108     return nullptr;
18109 
18110   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
18111 
18112   // OpenMP 5.0, 2.17.10.1 depobj Construct
18113   // depobj is an lvalue expression of type omp_depend_t.
18114   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
18115       !Depobj->isInstantiationDependent() &&
18116       !Depobj->containsUnexpandedParameterPack() &&
18117       (OMPDependTFound &&
18118        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
18119                                    /*CompareUnqualified=*/true))) {
18120     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18121         << 0 << Depobj->getType() << Depobj->getSourceRange();
18122   }
18123 
18124   if (!Depobj->isLValue()) {
18125     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18126         << 1 << Depobj->getSourceRange();
18127   }
18128 
18129   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
18130 }
18131 
18132 OMPClause *
18133 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
18134                               SourceLocation DepLoc, SourceLocation ColonLoc,
18135                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18136                               SourceLocation LParenLoc, SourceLocation EndLoc) {
18137   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
18138       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
18139     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18140         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
18141     return nullptr;
18142   }
18143   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
18144        DSAStack->getCurrentDirective() == OMPD_depobj) &&
18145       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
18146        DepKind == OMPC_DEPEND_sink ||
18147        ((LangOpts.OpenMP < 50 ||
18148          DSAStack->getCurrentDirective() == OMPD_depobj) &&
18149         DepKind == OMPC_DEPEND_depobj))) {
18150     SmallVector<unsigned, 3> Except;
18151     Except.push_back(OMPC_DEPEND_source);
18152     Except.push_back(OMPC_DEPEND_sink);
18153     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
18154       Except.push_back(OMPC_DEPEND_depobj);
18155     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
18156                                ? "depend modifier(iterator) or "
18157                                : "";
18158     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18159         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
18160                                               /*Last=*/OMPC_DEPEND_unknown,
18161                                               Except)
18162         << getOpenMPClauseName(OMPC_depend);
18163     return nullptr;
18164   }
18165   if (DepModifier &&
18166       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
18167     Diag(DepModifier->getExprLoc(),
18168          diag::err_omp_depend_sink_source_with_modifier);
18169     return nullptr;
18170   }
18171   if (DepModifier &&
18172       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
18173     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
18174 
18175   SmallVector<Expr *, 8> Vars;
18176   DSAStackTy::OperatorOffsetTy OpsOffs;
18177   llvm::APSInt DepCounter(/*BitWidth=*/32);
18178   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
18179   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
18180     if (const Expr *OrderedCountExpr =
18181             DSAStack->getParentOrderedRegionParam().first) {
18182       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
18183       TotalDepCount.setIsUnsigned(/*Val=*/true);
18184     }
18185   }
18186   for (Expr *RefExpr : VarList) {
18187     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18188     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18189       // It will be analyzed later.
18190       Vars.push_back(RefExpr);
18191       continue;
18192     }
18193 
18194     SourceLocation ELoc = RefExpr->getExprLoc();
18195     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
18196     if (DepKind == OMPC_DEPEND_sink) {
18197       if (DSAStack->getParentOrderedRegionParam().first &&
18198           DepCounter >= TotalDepCount) {
18199         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
18200         continue;
18201       }
18202       ++DepCounter;
18203       // OpenMP  [2.13.9, Summary]
18204       // depend(dependence-type : vec), where dependence-type is:
18205       // 'sink' and where vec is the iteration vector, which has the form:
18206       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
18207       // where n is the value specified by the ordered clause in the loop
18208       // directive, xi denotes the loop iteration variable of the i-th nested
18209       // loop associated with the loop directive, and di is a constant
18210       // non-negative integer.
18211       if (CurContext->isDependentContext()) {
18212         // It will be analyzed later.
18213         Vars.push_back(RefExpr);
18214         continue;
18215       }
18216       SimpleExpr = SimpleExpr->IgnoreImplicit();
18217       OverloadedOperatorKind OOK = OO_None;
18218       SourceLocation OOLoc;
18219       Expr *LHS = SimpleExpr;
18220       Expr *RHS = nullptr;
18221       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
18222         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
18223         OOLoc = BO->getOperatorLoc();
18224         LHS = BO->getLHS()->IgnoreParenImpCasts();
18225         RHS = BO->getRHS()->IgnoreParenImpCasts();
18226       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
18227         OOK = OCE->getOperator();
18228         OOLoc = OCE->getOperatorLoc();
18229         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18230         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
18231       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
18232         OOK = MCE->getMethodDecl()
18233                   ->getNameInfo()
18234                   .getName()
18235                   .getCXXOverloadedOperator();
18236         OOLoc = MCE->getCallee()->getExprLoc();
18237         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
18238         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18239       }
18240       SourceLocation ELoc;
18241       SourceRange ERange;
18242       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
18243       if (Res.second) {
18244         // It will be analyzed later.
18245         Vars.push_back(RefExpr);
18246       }
18247       ValueDecl *D = Res.first;
18248       if (!D)
18249         continue;
18250 
18251       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
18252         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
18253         continue;
18254       }
18255       if (RHS) {
18256         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
18257             RHS, OMPC_depend, /*StrictlyPositive=*/false);
18258         if (RHSRes.isInvalid())
18259           continue;
18260       }
18261       if (!CurContext->isDependentContext() &&
18262           DSAStack->getParentOrderedRegionParam().first &&
18263           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
18264         const ValueDecl *VD =
18265             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
18266         if (VD)
18267           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
18268               << 1 << VD;
18269         else
18270           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
18271         continue;
18272       }
18273       OpsOffs.emplace_back(RHS, OOK);
18274     } else {
18275       bool OMPDependTFound = LangOpts.OpenMP >= 50;
18276       if (OMPDependTFound)
18277         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
18278                                          DepKind == OMPC_DEPEND_depobj);
18279       if (DepKind == OMPC_DEPEND_depobj) {
18280         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18281         // List items used in depend clauses with the depobj dependence type
18282         // must be expressions of the omp_depend_t type.
18283         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18284             !RefExpr->isInstantiationDependent() &&
18285             !RefExpr->containsUnexpandedParameterPack() &&
18286             (OMPDependTFound &&
18287              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
18288                                              RefExpr->getType()))) {
18289           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18290               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
18291           continue;
18292         }
18293         if (!RefExpr->isLValue()) {
18294           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18295               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
18296           continue;
18297         }
18298       } else {
18299         // OpenMP 5.0 [2.17.11, Restrictions]
18300         // List items used in depend clauses cannot be zero-length array
18301         // sections.
18302         QualType ExprTy = RefExpr->getType().getNonReferenceType();
18303         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
18304         if (OASE) {
18305           QualType BaseType =
18306               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18307           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18308             ExprTy = ATy->getElementType();
18309           else
18310             ExprTy = BaseType->getPointeeType();
18311           ExprTy = ExprTy.getNonReferenceType();
18312           const Expr *Length = OASE->getLength();
18313           Expr::EvalResult Result;
18314           if (Length && !Length->isValueDependent() &&
18315               Length->EvaluateAsInt(Result, Context) &&
18316               Result.Val.getInt().isNullValue()) {
18317             Diag(ELoc,
18318                  diag::err_omp_depend_zero_length_array_section_not_allowed)
18319                 << SimpleExpr->getSourceRange();
18320             continue;
18321           }
18322         }
18323 
18324         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18325         // List items used in depend clauses with the in, out, inout or
18326         // mutexinoutset dependence types cannot be expressions of the
18327         // omp_depend_t type.
18328         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18329             !RefExpr->isInstantiationDependent() &&
18330             !RefExpr->containsUnexpandedParameterPack() &&
18331             (OMPDependTFound &&
18332              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
18333           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18334               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
18335               << RefExpr->getSourceRange();
18336           continue;
18337         }
18338 
18339         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
18340         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
18341             (ASE && !ASE->getBase()->isTypeDependent() &&
18342              !ASE->getBase()
18343                   ->getType()
18344                   .getNonReferenceType()
18345                   ->isPointerType() &&
18346              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
18347           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18348               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18349               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18350           continue;
18351         }
18352 
18353         ExprResult Res;
18354         {
18355           Sema::TentativeAnalysisScope Trap(*this);
18356           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
18357                                      RefExpr->IgnoreParenImpCasts());
18358         }
18359         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18360             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18361           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18362               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18363               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18364           continue;
18365         }
18366       }
18367     }
18368     Vars.push_back(RefExpr->IgnoreParenImpCasts());
18369   }
18370 
18371   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
18372       TotalDepCount > VarList.size() &&
18373       DSAStack->getParentOrderedRegionParam().first &&
18374       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
18375     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
18376         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
18377   }
18378   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
18379       Vars.empty())
18380     return nullptr;
18381 
18382   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18383                                     DepModifier, DepKind, DepLoc, ColonLoc,
18384                                     Vars, TotalDepCount.getZExtValue());
18385   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
18386       DSAStack->isParentOrderedRegion())
18387     DSAStack->addDoacrossDependClause(C, OpsOffs);
18388   return C;
18389 }
18390 
18391 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
18392                                          Expr *Device, SourceLocation StartLoc,
18393                                          SourceLocation LParenLoc,
18394                                          SourceLocation ModifierLoc,
18395                                          SourceLocation EndLoc) {
18396   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
18397          "Unexpected device modifier in OpenMP < 50.");
18398 
18399   bool ErrorFound = false;
18400   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
18401     std::string Values =
18402         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
18403     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
18404         << Values << getOpenMPClauseName(OMPC_device);
18405     ErrorFound = true;
18406   }
18407 
18408   Expr *ValExpr = Device;
18409   Stmt *HelperValStmt = nullptr;
18410 
18411   // OpenMP [2.9.1, Restrictions]
18412   // The device expression must evaluate to a non-negative integer value.
18413   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
18414                                           /*StrictlyPositive=*/false) ||
18415                ErrorFound;
18416   if (ErrorFound)
18417     return nullptr;
18418 
18419   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18420   OpenMPDirectiveKind CaptureRegion =
18421       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
18422   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18423     ValExpr = MakeFullExpr(ValExpr).get();
18424     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18425     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18426     HelperValStmt = buildPreInits(Context, Captures);
18427   }
18428 
18429   return new (Context)
18430       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18431                       LParenLoc, ModifierLoc, EndLoc);
18432 }
18433 
18434 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
18435                               DSAStackTy *Stack, QualType QTy,
18436                               bool FullCheck = true) {
18437   NamedDecl *ND;
18438   if (QTy->isIncompleteType(&ND)) {
18439     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
18440     return false;
18441   }
18442   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
18443       !QTy.isTriviallyCopyableType(SemaRef.Context))
18444     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
18445   return true;
18446 }
18447 
18448 /// Return true if it can be proven that the provided array expression
18449 /// (array section or array subscript) does NOT specify the whole size of the
18450 /// array whose base type is \a BaseQTy.
18451 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
18452                                                         const Expr *E,
18453                                                         QualType BaseQTy) {
18454   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18455 
18456   // If this is an array subscript, it refers to the whole size if the size of
18457   // the dimension is constant and equals 1. Also, an array section assumes the
18458   // format of an array subscript if no colon is used.
18459   if (isa<ArraySubscriptExpr>(E) ||
18460       (OASE && OASE->getColonLocFirst().isInvalid())) {
18461     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18462       return ATy->getSize().getSExtValue() != 1;
18463     // Size can't be evaluated statically.
18464     return false;
18465   }
18466 
18467   assert(OASE && "Expecting array section if not an array subscript.");
18468   const Expr *LowerBound = OASE->getLowerBound();
18469   const Expr *Length = OASE->getLength();
18470 
18471   // If there is a lower bound that does not evaluates to zero, we are not
18472   // covering the whole dimension.
18473   if (LowerBound) {
18474     Expr::EvalResult Result;
18475     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18476       return false; // Can't get the integer value as a constant.
18477 
18478     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18479     if (ConstLowerBound.getSExtValue())
18480       return true;
18481   }
18482 
18483   // If we don't have a length we covering the whole dimension.
18484   if (!Length)
18485     return false;
18486 
18487   // If the base is a pointer, we don't have a way to get the size of the
18488   // pointee.
18489   if (BaseQTy->isPointerType())
18490     return false;
18491 
18492   // We can only check if the length is the same as the size of the dimension
18493   // if we have a constant array.
18494   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18495   if (!CATy)
18496     return false;
18497 
18498   Expr::EvalResult Result;
18499   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18500     return false; // Can't get the integer value as a constant.
18501 
18502   llvm::APSInt ConstLength = Result.Val.getInt();
18503   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18504 }
18505 
18506 // Return true if it can be proven that the provided array expression (array
18507 // section or array subscript) does NOT specify a single element of the array
18508 // whose base type is \a BaseQTy.
18509 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18510                                                         const Expr *E,
18511                                                         QualType BaseQTy) {
18512   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18513 
18514   // An array subscript always refer to a single element. Also, an array section
18515   // assumes the format of an array subscript if no colon is used.
18516   if (isa<ArraySubscriptExpr>(E) ||
18517       (OASE && OASE->getColonLocFirst().isInvalid()))
18518     return false;
18519 
18520   assert(OASE && "Expecting array section if not an array subscript.");
18521   const Expr *Length = OASE->getLength();
18522 
18523   // If we don't have a length we have to check if the array has unitary size
18524   // for this dimension. Also, we should always expect a length if the base type
18525   // is pointer.
18526   if (!Length) {
18527     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18528       return ATy->getSize().getSExtValue() != 1;
18529     // We cannot assume anything.
18530     return false;
18531   }
18532 
18533   // Check if the length evaluates to 1.
18534   Expr::EvalResult Result;
18535   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18536     return false; // Can't get the integer value as a constant.
18537 
18538   llvm::APSInt ConstLength = Result.Val.getInt();
18539   return ConstLength.getSExtValue() != 1;
18540 }
18541 
18542 // The base of elements of list in a map clause have to be either:
18543 //  - a reference to variable or field.
18544 //  - a member expression.
18545 //  - an array expression.
18546 //
18547 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18548 // reference to 'r'.
18549 //
18550 // If we have:
18551 //
18552 // struct SS {
18553 //   Bla S;
18554 //   foo() {
18555 //     #pragma omp target map (S.Arr[:12]);
18556 //   }
18557 // }
18558 //
18559 // We want to retrieve the member expression 'this->S';
18560 
18561 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18562 //  If a list item is an array section, it must specify contiguous storage.
18563 //
18564 // For this restriction it is sufficient that we make sure only references
18565 // to variables or fields and array expressions, and that no array sections
18566 // exist except in the rightmost expression (unless they cover the whole
18567 // dimension of the array). E.g. these would be invalid:
18568 //
18569 //   r.ArrS[3:5].Arr[6:7]
18570 //
18571 //   r.ArrS[3:5].x
18572 //
18573 // but these would be valid:
18574 //   r.ArrS[3].Arr[6:7]
18575 //
18576 //   r.ArrS[3].x
18577 namespace {
18578 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18579   Sema &SemaRef;
18580   OpenMPClauseKind CKind = OMPC_unknown;
18581   OpenMPDirectiveKind DKind = OMPD_unknown;
18582   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18583   bool IsNonContiguous = false;
18584   bool NoDiagnose = false;
18585   const Expr *RelevantExpr = nullptr;
18586   bool AllowUnitySizeArraySection = true;
18587   bool AllowWholeSizeArraySection = true;
18588   bool AllowAnotherPtr = true;
18589   SourceLocation ELoc;
18590   SourceRange ERange;
18591 
18592   void emitErrorMsg() {
18593     // If nothing else worked, this is not a valid map clause expression.
18594     if (SemaRef.getLangOpts().OpenMP < 50) {
18595       SemaRef.Diag(ELoc,
18596                    diag::err_omp_expected_named_var_member_or_array_expression)
18597           << ERange;
18598     } else {
18599       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18600           << getOpenMPClauseName(CKind) << ERange;
18601     }
18602   }
18603 
18604 public:
18605   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18606     if (!isa<VarDecl>(DRE->getDecl())) {
18607       emitErrorMsg();
18608       return false;
18609     }
18610     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18611     RelevantExpr = DRE;
18612     // Record the component.
18613     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18614     return true;
18615   }
18616 
18617   bool VisitMemberExpr(MemberExpr *ME) {
18618     Expr *E = ME;
18619     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18620 
18621     if (isa<CXXThisExpr>(BaseE)) {
18622       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18623       // We found a base expression: this->Val.
18624       RelevantExpr = ME;
18625     } else {
18626       E = BaseE;
18627     }
18628 
18629     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18630       if (!NoDiagnose) {
18631         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18632           << ME->getSourceRange();
18633         return false;
18634       }
18635       if (RelevantExpr)
18636         return false;
18637       return Visit(E);
18638     }
18639 
18640     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18641 
18642     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18643     //  A bit-field cannot appear in a map clause.
18644     //
18645     if (FD->isBitField()) {
18646       if (!NoDiagnose) {
18647         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18648           << ME->getSourceRange() << getOpenMPClauseName(CKind);
18649         return false;
18650       }
18651       if (RelevantExpr)
18652         return false;
18653       return Visit(E);
18654     }
18655 
18656     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18657     //  If the type of a list item is a reference to a type T then the type
18658     //  will be considered to be T for all purposes of this clause.
18659     QualType CurType = BaseE->getType().getNonReferenceType();
18660 
18661     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18662     //  A list item cannot be a variable that is a member of a structure with
18663     //  a union type.
18664     //
18665     if (CurType->isUnionType()) {
18666       if (!NoDiagnose) {
18667         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18668           << ME->getSourceRange();
18669         return false;
18670       }
18671       return RelevantExpr || Visit(E);
18672     }
18673 
18674     // If we got a member expression, we should not expect any array section
18675     // before that:
18676     //
18677     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18678     //  If a list item is an element of a structure, only the rightmost symbol
18679     //  of the variable reference can be an array section.
18680     //
18681     AllowUnitySizeArraySection = false;
18682     AllowWholeSizeArraySection = false;
18683 
18684     // Record the component.
18685     Components.emplace_back(ME, FD, IsNonContiguous);
18686     return RelevantExpr || Visit(E);
18687   }
18688 
18689   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18690     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18691 
18692     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
18693       if (!NoDiagnose) {
18694         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18695           << 0 << AE->getSourceRange();
18696         return false;
18697       }
18698       return RelevantExpr || Visit(E);
18699     }
18700 
18701     // If we got an array subscript that express the whole dimension we
18702     // can have any array expressions before. If it only expressing part of
18703     // the dimension, we can only have unitary-size array expressions.
18704     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
18705                                                     E->getType()))
18706       AllowWholeSizeArraySection = false;
18707 
18708     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
18709       Expr::EvalResult Result;
18710       if (!AE->getIdx()->isValueDependent() &&
18711           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
18712           !Result.Val.getInt().isNullValue()) {
18713         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18714                      diag::err_omp_invalid_map_this_expr);
18715         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18716                      diag::note_omp_invalid_subscript_on_this_ptr_map);
18717       }
18718       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18719       RelevantExpr = TE;
18720     }
18721 
18722     // Record the component - we don't have any declaration associated.
18723     Components.emplace_back(AE, nullptr, IsNonContiguous);
18724 
18725     return RelevantExpr || Visit(E);
18726   }
18727 
18728   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
18729     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
18730     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18731     QualType CurType =
18732       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18733 
18734     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18735     //  If the type of a list item is a reference to a type T then the type
18736     //  will be considered to be T for all purposes of this clause.
18737     if (CurType->isReferenceType())
18738       CurType = CurType->getPointeeType();
18739 
18740     bool IsPointer = CurType->isAnyPointerType();
18741 
18742     if (!IsPointer && !CurType->isArrayType()) {
18743       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18744         << 0 << OASE->getSourceRange();
18745       return false;
18746     }
18747 
18748     bool NotWhole =
18749       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
18750     bool NotUnity =
18751       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
18752 
18753     if (AllowWholeSizeArraySection) {
18754       // Any array section is currently allowed. Allowing a whole size array
18755       // section implies allowing a unity array section as well.
18756       //
18757       // If this array section refers to the whole dimension we can still
18758       // accept other array sections before this one, except if the base is a
18759       // pointer. Otherwise, only unitary sections are accepted.
18760       if (NotWhole || IsPointer)
18761         AllowWholeSizeArraySection = false;
18762     } else if (DKind == OMPD_target_update &&
18763                SemaRef.getLangOpts().OpenMP >= 50) {
18764       if (IsPointer && !AllowAnotherPtr)
18765         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
18766             << /*array of unknown bound */ 1;
18767       else
18768         IsNonContiguous = true;
18769     } else if (AllowUnitySizeArraySection && NotUnity) {
18770       // A unity or whole array section is not allowed and that is not
18771       // compatible with the properties of the current array section.
18772       SemaRef.Diag(
18773         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
18774         << OASE->getSourceRange();
18775       return false;
18776     }
18777 
18778     if (IsPointer)
18779       AllowAnotherPtr = false;
18780 
18781     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
18782       Expr::EvalResult ResultR;
18783       Expr::EvalResult ResultL;
18784       if (!OASE->getLength()->isValueDependent() &&
18785           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
18786           !ResultR.Val.getInt().isOneValue()) {
18787         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18788                      diag::err_omp_invalid_map_this_expr);
18789         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18790                      diag::note_omp_invalid_length_on_this_ptr_mapping);
18791       }
18792       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
18793           OASE->getLowerBound()->EvaluateAsInt(ResultL,
18794                                                SemaRef.getASTContext()) &&
18795           !ResultL.Val.getInt().isNullValue()) {
18796         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18797                      diag::err_omp_invalid_map_this_expr);
18798         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18799                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
18800       }
18801       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18802       RelevantExpr = TE;
18803     }
18804 
18805     // Record the component - we don't have any declaration associated.
18806     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
18807     return RelevantExpr || Visit(E);
18808   }
18809   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
18810     Expr *Base = E->getBase();
18811 
18812     // Record the component - we don't have any declaration associated.
18813     Components.emplace_back(E, nullptr, IsNonContiguous);
18814 
18815     return Visit(Base->IgnoreParenImpCasts());
18816   }
18817 
18818   bool VisitUnaryOperator(UnaryOperator *UO) {
18819     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
18820         UO->getOpcode() != UO_Deref) {
18821       emitErrorMsg();
18822       return false;
18823     }
18824     if (!RelevantExpr) {
18825       // Record the component if haven't found base decl.
18826       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
18827     }
18828     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
18829   }
18830   bool VisitBinaryOperator(BinaryOperator *BO) {
18831     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
18832       emitErrorMsg();
18833       return false;
18834     }
18835 
18836     // Pointer arithmetic is the only thing we expect to happen here so after we
18837     // make sure the binary operator is a pointer type, the we only thing need
18838     // to to is to visit the subtree that has the same type as root (so that we
18839     // know the other subtree is just an offset)
18840     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
18841     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
18842     Components.emplace_back(BO, nullptr, false);
18843     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
18844             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
18845            "Either LHS or RHS have base decl inside");
18846     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
18847       return RelevantExpr || Visit(LE);
18848     return RelevantExpr || Visit(RE);
18849   }
18850   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
18851     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18852     RelevantExpr = CTE;
18853     Components.emplace_back(CTE, nullptr, IsNonContiguous);
18854     return true;
18855   }
18856   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
18857     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18858     Components.emplace_back(COCE, nullptr, IsNonContiguous);
18859     return true;
18860   }
18861   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
18862     Expr *Source = E->getSourceExpr();
18863     if (!Source) {
18864       emitErrorMsg();
18865       return false;
18866     }
18867     return Visit(Source);
18868   }
18869   bool VisitStmt(Stmt *) {
18870     emitErrorMsg();
18871     return false;
18872   }
18873   const Expr *getFoundBase() const {
18874     return RelevantExpr;
18875   }
18876   explicit MapBaseChecker(
18877       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
18878       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
18879       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
18880       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
18881         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
18882 };
18883 } // namespace
18884 
18885 /// Return the expression of the base of the mappable expression or null if it
18886 /// cannot be determined and do all the necessary checks to see if the expression
18887 /// is valid as a standalone mappable expression. In the process, record all the
18888 /// components of the expression.
18889 static const Expr *checkMapClauseExpressionBase(
18890     Sema &SemaRef, Expr *E,
18891     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
18892     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
18893   SourceLocation ELoc = E->getExprLoc();
18894   SourceRange ERange = E->getSourceRange();
18895   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
18896                          ERange);
18897   if (Checker.Visit(E->IgnoreParens())) {
18898     // Check if the highest dimension array section has length specified
18899     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
18900         (CKind == OMPC_to || CKind == OMPC_from)) {
18901       auto CI = CurComponents.rbegin();
18902       auto CE = CurComponents.rend();
18903       for (; CI != CE; ++CI) {
18904         const auto *OASE =
18905             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
18906         if (!OASE)
18907           continue;
18908         if (OASE && OASE->getLength())
18909           break;
18910         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
18911             << ERange;
18912       }
18913     }
18914     return Checker.getFoundBase();
18915   }
18916   return nullptr;
18917 }
18918 
18919 // Return true if expression E associated with value VD has conflicts with other
18920 // map information.
18921 static bool checkMapConflicts(
18922     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
18923     bool CurrentRegionOnly,
18924     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
18925     OpenMPClauseKind CKind) {
18926   assert(VD && E);
18927   SourceLocation ELoc = E->getExprLoc();
18928   SourceRange ERange = E->getSourceRange();
18929 
18930   // In order to easily check the conflicts we need to match each component of
18931   // the expression under test with the components of the expressions that are
18932   // already in the stack.
18933 
18934   assert(!CurComponents.empty() && "Map clause expression with no components!");
18935   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
18936          "Map clause expression with unexpected base!");
18937 
18938   // Variables to help detecting enclosing problems in data environment nests.
18939   bool IsEnclosedByDataEnvironmentExpr = false;
18940   const Expr *EnclosingExpr = nullptr;
18941 
18942   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
18943       VD, CurrentRegionOnly,
18944       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
18945        ERange, CKind, &EnclosingExpr,
18946        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
18947                           StackComponents,
18948                       OpenMPClauseKind Kind) {
18949         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
18950           return false;
18951         assert(!StackComponents.empty() &&
18952                "Map clause expression with no components!");
18953         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
18954                "Map clause expression with unexpected base!");
18955         (void)VD;
18956 
18957         // The whole expression in the stack.
18958         const Expr *RE = StackComponents.front().getAssociatedExpression();
18959 
18960         // Expressions must start from the same base. Here we detect at which
18961         // point both expressions diverge from each other and see if we can
18962         // detect if the memory referred to both expressions is contiguous and
18963         // do not overlap.
18964         auto CI = CurComponents.rbegin();
18965         auto CE = CurComponents.rend();
18966         auto SI = StackComponents.rbegin();
18967         auto SE = StackComponents.rend();
18968         for (; CI != CE && SI != SE; ++CI, ++SI) {
18969 
18970           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
18971           //  At most one list item can be an array item derived from a given
18972           //  variable in map clauses of the same construct.
18973           if (CurrentRegionOnly &&
18974               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
18975                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
18976                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
18977               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
18978                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
18979                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
18980             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
18981                          diag::err_omp_multiple_array_items_in_map_clause)
18982                 << CI->getAssociatedExpression()->getSourceRange();
18983             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
18984                          diag::note_used_here)
18985                 << SI->getAssociatedExpression()->getSourceRange();
18986             return true;
18987           }
18988 
18989           // Do both expressions have the same kind?
18990           if (CI->getAssociatedExpression()->getStmtClass() !=
18991               SI->getAssociatedExpression()->getStmtClass())
18992             break;
18993 
18994           // Are we dealing with different variables/fields?
18995           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
18996             break;
18997         }
18998         // Check if the extra components of the expressions in the enclosing
18999         // data environment are redundant for the current base declaration.
19000         // If they are, the maps completely overlap, which is legal.
19001         for (; SI != SE; ++SI) {
19002           QualType Type;
19003           if (const auto *ASE =
19004                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
19005             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
19006           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
19007                          SI->getAssociatedExpression())) {
19008             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19009             Type =
19010                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19011           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
19012                          SI->getAssociatedExpression())) {
19013             Type = OASE->getBase()->getType()->getPointeeType();
19014           }
19015           if (Type.isNull() || Type->isAnyPointerType() ||
19016               checkArrayExpressionDoesNotReferToWholeSize(
19017                   SemaRef, SI->getAssociatedExpression(), Type))
19018             break;
19019         }
19020 
19021         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19022         //  List items of map clauses in the same construct must not share
19023         //  original storage.
19024         //
19025         // If the expressions are exactly the same or one is a subset of the
19026         // other, it means they are sharing storage.
19027         if (CI == CE && SI == SE) {
19028           if (CurrentRegionOnly) {
19029             if (CKind == OMPC_map) {
19030               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19031             } else {
19032               assert(CKind == OMPC_to || CKind == OMPC_from);
19033               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19034                   << ERange;
19035             }
19036             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19037                 << RE->getSourceRange();
19038             return true;
19039           }
19040           // If we find the same expression in the enclosing data environment,
19041           // that is legal.
19042           IsEnclosedByDataEnvironmentExpr = true;
19043           return false;
19044         }
19045 
19046         QualType DerivedType =
19047             std::prev(CI)->getAssociatedDeclaration()->getType();
19048         SourceLocation DerivedLoc =
19049             std::prev(CI)->getAssociatedExpression()->getExprLoc();
19050 
19051         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19052         //  If the type of a list item is a reference to a type T then the type
19053         //  will be considered to be T for all purposes of this clause.
19054         DerivedType = DerivedType.getNonReferenceType();
19055 
19056         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
19057         //  A variable for which the type is pointer and an array section
19058         //  derived from that variable must not appear as list items of map
19059         //  clauses of the same construct.
19060         //
19061         // Also, cover one of the cases in:
19062         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19063         //  If any part of the original storage of a list item has corresponding
19064         //  storage in the device data environment, all of the original storage
19065         //  must have corresponding storage in the device data environment.
19066         //
19067         if (DerivedType->isAnyPointerType()) {
19068           if (CI == CE || SI == SE) {
19069             SemaRef.Diag(
19070                 DerivedLoc,
19071                 diag::err_omp_pointer_mapped_along_with_derived_section)
19072                 << DerivedLoc;
19073             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19074                 << RE->getSourceRange();
19075             return true;
19076           }
19077           if (CI->getAssociatedExpression()->getStmtClass() !=
19078                          SI->getAssociatedExpression()->getStmtClass() ||
19079                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
19080                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
19081             assert(CI != CE && SI != SE);
19082             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
19083                 << DerivedLoc;
19084             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19085                 << RE->getSourceRange();
19086             return true;
19087           }
19088         }
19089 
19090         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19091         //  List items of map clauses in the same construct must not share
19092         //  original storage.
19093         //
19094         // An expression is a subset of the other.
19095         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
19096           if (CKind == OMPC_map) {
19097             if (CI != CE || SI != SE) {
19098               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
19099               // a pointer.
19100               auto Begin =
19101                   CI != CE ? CurComponents.begin() : StackComponents.begin();
19102               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
19103               auto It = Begin;
19104               while (It != End && !It->getAssociatedDeclaration())
19105                 std::advance(It, 1);
19106               assert(It != End &&
19107                      "Expected at least one component with the declaration.");
19108               if (It != Begin && It->getAssociatedDeclaration()
19109                                      ->getType()
19110                                      .getCanonicalType()
19111                                      ->isAnyPointerType()) {
19112                 IsEnclosedByDataEnvironmentExpr = false;
19113                 EnclosingExpr = nullptr;
19114                 return false;
19115               }
19116             }
19117             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19118           } else {
19119             assert(CKind == OMPC_to || CKind == OMPC_from);
19120             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19121                 << ERange;
19122           }
19123           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19124               << RE->getSourceRange();
19125           return true;
19126         }
19127 
19128         // The current expression uses the same base as other expression in the
19129         // data environment but does not contain it completely.
19130         if (!CurrentRegionOnly && SI != SE)
19131           EnclosingExpr = RE;
19132 
19133         // The current expression is a subset of the expression in the data
19134         // environment.
19135         IsEnclosedByDataEnvironmentExpr |=
19136             (!CurrentRegionOnly && CI != CE && SI == SE);
19137 
19138         return false;
19139       });
19140 
19141   if (CurrentRegionOnly)
19142     return FoundError;
19143 
19144   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19145   //  If any part of the original storage of a list item has corresponding
19146   //  storage in the device data environment, all of the original storage must
19147   //  have corresponding storage in the device data environment.
19148   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
19149   //  If a list item is an element of a structure, and a different element of
19150   //  the structure has a corresponding list item in the device data environment
19151   //  prior to a task encountering the construct associated with the map clause,
19152   //  then the list item must also have a corresponding list item in the device
19153   //  data environment prior to the task encountering the construct.
19154   //
19155   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
19156     SemaRef.Diag(ELoc,
19157                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
19158         << ERange;
19159     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
19160         << EnclosingExpr->getSourceRange();
19161     return true;
19162   }
19163 
19164   return FoundError;
19165 }
19166 
19167 // Look up the user-defined mapper given the mapper name and mapped type, and
19168 // build a reference to it.
19169 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
19170                                             CXXScopeSpec &MapperIdScopeSpec,
19171                                             const DeclarationNameInfo &MapperId,
19172                                             QualType Type,
19173                                             Expr *UnresolvedMapper) {
19174   if (MapperIdScopeSpec.isInvalid())
19175     return ExprError();
19176   // Get the actual type for the array type.
19177   if (Type->isArrayType()) {
19178     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
19179     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
19180   }
19181   // Find all user-defined mappers with the given MapperId.
19182   SmallVector<UnresolvedSet<8>, 4> Lookups;
19183   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
19184   Lookup.suppressDiagnostics();
19185   if (S) {
19186     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
19187       NamedDecl *D = Lookup.getRepresentativeDecl();
19188       while (S && !S->isDeclScope(D))
19189         S = S->getParent();
19190       if (S)
19191         S = S->getParent();
19192       Lookups.emplace_back();
19193       Lookups.back().append(Lookup.begin(), Lookup.end());
19194       Lookup.clear();
19195     }
19196   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
19197     // Extract the user-defined mappers with the given MapperId.
19198     Lookups.push_back(UnresolvedSet<8>());
19199     for (NamedDecl *D : ULE->decls()) {
19200       auto *DMD = cast<OMPDeclareMapperDecl>(D);
19201       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
19202       Lookups.back().addDecl(DMD);
19203     }
19204   }
19205   // Defer the lookup for dependent types. The results will be passed through
19206   // UnresolvedMapper on instantiation.
19207   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
19208       Type->isInstantiationDependentType() ||
19209       Type->containsUnexpandedParameterPack() ||
19210       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
19211         return !D->isInvalidDecl() &&
19212                (D->getType()->isDependentType() ||
19213                 D->getType()->isInstantiationDependentType() ||
19214                 D->getType()->containsUnexpandedParameterPack());
19215       })) {
19216     UnresolvedSet<8> URS;
19217     for (const UnresolvedSet<8> &Set : Lookups) {
19218       if (Set.empty())
19219         continue;
19220       URS.append(Set.begin(), Set.end());
19221     }
19222     return UnresolvedLookupExpr::Create(
19223         SemaRef.Context, /*NamingClass=*/nullptr,
19224         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
19225         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
19226   }
19227   SourceLocation Loc = MapperId.getLoc();
19228   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19229   //  The type must be of struct, union or class type in C and C++
19230   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
19231       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
19232     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
19233     return ExprError();
19234   }
19235   // Perform argument dependent lookup.
19236   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
19237     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
19238   // Return the first user-defined mapper with the desired type.
19239   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19240           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
19241             if (!D->isInvalidDecl() &&
19242                 SemaRef.Context.hasSameType(D->getType(), Type))
19243               return D;
19244             return nullptr;
19245           }))
19246     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19247   // Find the first user-defined mapper with a type derived from the desired
19248   // type.
19249   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19250           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
19251             if (!D->isInvalidDecl() &&
19252                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
19253                 !Type.isMoreQualifiedThan(D->getType()))
19254               return D;
19255             return nullptr;
19256           })) {
19257     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
19258                        /*DetectVirtual=*/false);
19259     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
19260       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
19261               VD->getType().getUnqualifiedType()))) {
19262         if (SemaRef.CheckBaseClassAccess(
19263                 Loc, VD->getType(), Type, Paths.front(),
19264                 /*DiagID=*/0) != Sema::AR_inaccessible) {
19265           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19266         }
19267       }
19268     }
19269   }
19270   // Report error if a mapper is specified, but cannot be found.
19271   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
19272     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
19273         << Type << MapperId.getName();
19274     return ExprError();
19275   }
19276   return ExprEmpty();
19277 }
19278 
19279 namespace {
19280 // Utility struct that gathers all the related lists associated with a mappable
19281 // expression.
19282 struct MappableVarListInfo {
19283   // The list of expressions.
19284   ArrayRef<Expr *> VarList;
19285   // The list of processed expressions.
19286   SmallVector<Expr *, 16> ProcessedVarList;
19287   // The mappble components for each expression.
19288   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
19289   // The base declaration of the variable.
19290   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
19291   // The reference to the user-defined mapper associated with every expression.
19292   SmallVector<Expr *, 16> UDMapperList;
19293 
19294   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
19295     // We have a list of components and base declarations for each entry in the
19296     // variable list.
19297     VarComponents.reserve(VarList.size());
19298     VarBaseDeclarations.reserve(VarList.size());
19299   }
19300 };
19301 }
19302 
19303 // Check the validity of the provided variable list for the provided clause kind
19304 // \a CKind. In the check process the valid expressions, mappable expression
19305 // components, variables, and user-defined mappers are extracted and used to
19306 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
19307 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
19308 // and \a MapperId are expected to be valid if the clause kind is 'map'.
19309 static void checkMappableExpressionList(
19310     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
19311     MappableVarListInfo &MVLI, SourceLocation StartLoc,
19312     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
19313     ArrayRef<Expr *> UnresolvedMappers,
19314     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
19315     bool IsMapTypeImplicit = false) {
19316   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
19317   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
19318          "Unexpected clause kind with mappable expressions!");
19319 
19320   // If the identifier of user-defined mapper is not specified, it is "default".
19321   // We do not change the actual name in this clause to distinguish whether a
19322   // mapper is specified explicitly, i.e., it is not explicitly specified when
19323   // MapperId.getName() is empty.
19324   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
19325     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
19326     MapperId.setName(DeclNames.getIdentifier(
19327         &SemaRef.getASTContext().Idents.get("default")));
19328     MapperId.setLoc(StartLoc);
19329   }
19330 
19331   // Iterators to find the current unresolved mapper expression.
19332   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
19333   bool UpdateUMIt = false;
19334   Expr *UnresolvedMapper = nullptr;
19335 
19336   // Keep track of the mappable components and base declarations in this clause.
19337   // Each entry in the list is going to have a list of components associated. We
19338   // record each set of the components so that we can build the clause later on.
19339   // In the end we should have the same amount of declarations and component
19340   // lists.
19341 
19342   for (Expr *RE : MVLI.VarList) {
19343     assert(RE && "Null expr in omp to/from/map clause");
19344     SourceLocation ELoc = RE->getExprLoc();
19345 
19346     // Find the current unresolved mapper expression.
19347     if (UpdateUMIt && UMIt != UMEnd) {
19348       UMIt++;
19349       assert(
19350           UMIt != UMEnd &&
19351           "Expect the size of UnresolvedMappers to match with that of VarList");
19352     }
19353     UpdateUMIt = true;
19354     if (UMIt != UMEnd)
19355       UnresolvedMapper = *UMIt;
19356 
19357     const Expr *VE = RE->IgnoreParenLValueCasts();
19358 
19359     if (VE->isValueDependent() || VE->isTypeDependent() ||
19360         VE->isInstantiationDependent() ||
19361         VE->containsUnexpandedParameterPack()) {
19362       // Try to find the associated user-defined mapper.
19363       ExprResult ER = buildUserDefinedMapperRef(
19364           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19365           VE->getType().getCanonicalType(), UnresolvedMapper);
19366       if (ER.isInvalid())
19367         continue;
19368       MVLI.UDMapperList.push_back(ER.get());
19369       // We can only analyze this information once the missing information is
19370       // resolved.
19371       MVLI.ProcessedVarList.push_back(RE);
19372       continue;
19373     }
19374 
19375     Expr *SimpleExpr = RE->IgnoreParenCasts();
19376 
19377     if (!RE->isLValue()) {
19378       if (SemaRef.getLangOpts().OpenMP < 50) {
19379         SemaRef.Diag(
19380             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
19381             << RE->getSourceRange();
19382       } else {
19383         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19384             << getOpenMPClauseName(CKind) << RE->getSourceRange();
19385       }
19386       continue;
19387     }
19388 
19389     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
19390     ValueDecl *CurDeclaration = nullptr;
19391 
19392     // Obtain the array or member expression bases if required. Also, fill the
19393     // components array with all the components identified in the process.
19394     const Expr *BE = checkMapClauseExpressionBase(
19395         SemaRef, SimpleExpr, CurComponents, CKind, DSAS->getCurrentDirective(),
19396         /*NoDiagnose=*/false);
19397     if (!BE)
19398       continue;
19399 
19400     assert(!CurComponents.empty() &&
19401            "Invalid mappable expression information.");
19402 
19403     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
19404       // Add store "this" pointer to class in DSAStackTy for future checking
19405       DSAS->addMappedClassesQualTypes(TE->getType());
19406       // Try to find the associated user-defined mapper.
19407       ExprResult ER = buildUserDefinedMapperRef(
19408           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19409           VE->getType().getCanonicalType(), UnresolvedMapper);
19410       if (ER.isInvalid())
19411         continue;
19412       MVLI.UDMapperList.push_back(ER.get());
19413       // Skip restriction checking for variable or field declarations
19414       MVLI.ProcessedVarList.push_back(RE);
19415       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19416       MVLI.VarComponents.back().append(CurComponents.begin(),
19417                                        CurComponents.end());
19418       MVLI.VarBaseDeclarations.push_back(nullptr);
19419       continue;
19420     }
19421 
19422     // For the following checks, we rely on the base declaration which is
19423     // expected to be associated with the last component. The declaration is
19424     // expected to be a variable or a field (if 'this' is being mapped).
19425     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
19426     assert(CurDeclaration && "Null decl on map clause.");
19427     assert(
19428         CurDeclaration->isCanonicalDecl() &&
19429         "Expecting components to have associated only canonical declarations.");
19430 
19431     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
19432     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
19433 
19434     assert((VD || FD) && "Only variables or fields are expected here!");
19435     (void)FD;
19436 
19437     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
19438     // threadprivate variables cannot appear in a map clause.
19439     // OpenMP 4.5 [2.10.5, target update Construct]
19440     // threadprivate variables cannot appear in a from clause.
19441     if (VD && DSAS->isThreadPrivate(VD)) {
19442       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19443       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
19444           << getOpenMPClauseName(CKind);
19445       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
19446       continue;
19447     }
19448 
19449     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19450     //  A list item cannot appear in both a map clause and a data-sharing
19451     //  attribute clause on the same construct.
19452 
19453     // Check conflicts with other map clause expressions. We check the conflicts
19454     // with the current construct separately from the enclosing data
19455     // environment, because the restrictions are different. We only have to
19456     // check conflicts across regions for the map clauses.
19457     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19458                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
19459       break;
19460     if (CKind == OMPC_map &&
19461         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
19462         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19463                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
19464       break;
19465 
19466     // OpenMP 4.5 [2.10.5, target update Construct]
19467     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19468     //  If the type of a list item is a reference to a type T then the type will
19469     //  be considered to be T for all purposes of this clause.
19470     auto I = llvm::find_if(
19471         CurComponents,
19472         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19473           return MC.getAssociatedDeclaration();
19474         });
19475     assert(I != CurComponents.end() && "Null decl on map clause.");
19476     (void)I;
19477     QualType Type;
19478     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19479     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19480     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19481     if (ASE) {
19482       Type = ASE->getType().getNonReferenceType();
19483     } else if (OASE) {
19484       QualType BaseType =
19485           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19486       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19487         Type = ATy->getElementType();
19488       else
19489         Type = BaseType->getPointeeType();
19490       Type = Type.getNonReferenceType();
19491     } else if (OAShE) {
19492       Type = OAShE->getBase()->getType()->getPointeeType();
19493     } else {
19494       Type = VE->getType();
19495     }
19496 
19497     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19498     // A list item in a to or from clause must have a mappable type.
19499     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19500     //  A list item must have a mappable type.
19501     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19502                            DSAS, Type))
19503       continue;
19504 
19505     if (CKind == OMPC_map) {
19506       // target enter data
19507       // OpenMP [2.10.2, Restrictions, p. 99]
19508       // A map-type must be specified in all map clauses and must be either
19509       // to or alloc.
19510       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19511       if (DKind == OMPD_target_enter_data &&
19512           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19513         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19514             << (IsMapTypeImplicit ? 1 : 0)
19515             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19516             << getOpenMPDirectiveName(DKind);
19517         continue;
19518       }
19519 
19520       // target exit_data
19521       // OpenMP [2.10.3, Restrictions, p. 102]
19522       // A map-type must be specified in all map clauses and must be either
19523       // from, release, or delete.
19524       if (DKind == OMPD_target_exit_data &&
19525           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19526             MapType == OMPC_MAP_delete)) {
19527         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19528             << (IsMapTypeImplicit ? 1 : 0)
19529             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19530             << getOpenMPDirectiveName(DKind);
19531         continue;
19532       }
19533 
19534       // target, target data
19535       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19536       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19537       // A map-type in a map clause must be to, from, tofrom or alloc
19538       if ((DKind == OMPD_target_data ||
19539            isOpenMPTargetExecutionDirective(DKind)) &&
19540           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19541             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19542         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19543             << (IsMapTypeImplicit ? 1 : 0)
19544             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19545             << getOpenMPDirectiveName(DKind);
19546         continue;
19547       }
19548 
19549       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19550       // A list item cannot appear in both a map clause and a data-sharing
19551       // attribute clause on the same construct
19552       //
19553       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19554       // A list item cannot appear in both a map clause and a data-sharing
19555       // attribute clause on the same construct unless the construct is a
19556       // combined construct.
19557       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19558                   isOpenMPTargetExecutionDirective(DKind)) ||
19559                  DKind == OMPD_target)) {
19560         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19561         if (isOpenMPPrivate(DVar.CKind)) {
19562           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19563               << getOpenMPClauseName(DVar.CKind)
19564               << getOpenMPClauseName(OMPC_map)
19565               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19566           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19567           continue;
19568         }
19569       }
19570     }
19571 
19572     // Try to find the associated user-defined mapper.
19573     ExprResult ER = buildUserDefinedMapperRef(
19574         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19575         Type.getCanonicalType(), UnresolvedMapper);
19576     if (ER.isInvalid())
19577       continue;
19578     MVLI.UDMapperList.push_back(ER.get());
19579 
19580     // Save the current expression.
19581     MVLI.ProcessedVarList.push_back(RE);
19582 
19583     // Store the components in the stack so that they can be used to check
19584     // against other clauses later on.
19585     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19586                                           /*WhereFoundClauseKind=*/OMPC_map);
19587 
19588     // Save the components and declaration to create the clause. For purposes of
19589     // the clause creation, any component list that has has base 'this' uses
19590     // null as base declaration.
19591     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19592     MVLI.VarComponents.back().append(CurComponents.begin(),
19593                                      CurComponents.end());
19594     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19595                                                            : CurDeclaration);
19596   }
19597 }
19598 
19599 OMPClause *Sema::ActOnOpenMPMapClause(
19600     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19601     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19602     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19603     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19604     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19605     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
19606   OpenMPMapModifierKind Modifiers[] = {
19607       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19608       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
19609   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19610 
19611   // Process map-type-modifiers, flag errors for duplicate modifiers.
19612   unsigned Count = 0;
19613   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19614     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19615         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
19616       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19617       continue;
19618     }
19619     assert(Count < NumberOfOMPMapClauseModifiers &&
19620            "Modifiers exceed the allowed number of map type modifiers");
19621     Modifiers[Count] = MapTypeModifiers[I];
19622     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19623     ++Count;
19624   }
19625 
19626   MappableVarListInfo MVLI(VarList);
19627   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19628                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19629                               MapType, IsMapTypeImplicit);
19630 
19631   // We need to produce a map clause even if we don't have variables so that
19632   // other diagnostics related with non-existing map clauses are accurate.
19633   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19634                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19635                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19636                               MapperIdScopeSpec.getWithLocInContext(Context),
19637                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19638 }
19639 
19640 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19641                                                TypeResult ParsedType) {
19642   assert(ParsedType.isUsable());
19643 
19644   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19645   if (ReductionType.isNull())
19646     return QualType();
19647 
19648   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19649   // A type name in a declare reduction directive cannot be a function type, an
19650   // array type, a reference type, or a type qualified with const, volatile or
19651   // restrict.
19652   if (ReductionType.hasQualifiers()) {
19653     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19654     return QualType();
19655   }
19656 
19657   if (ReductionType->isFunctionType()) {
19658     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19659     return QualType();
19660   }
19661   if (ReductionType->isReferenceType()) {
19662     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19663     return QualType();
19664   }
19665   if (ReductionType->isArrayType()) {
19666     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
19667     return QualType();
19668   }
19669   return ReductionType;
19670 }
19671 
19672 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
19673     Scope *S, DeclContext *DC, DeclarationName Name,
19674     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
19675     AccessSpecifier AS, Decl *PrevDeclInScope) {
19676   SmallVector<Decl *, 8> Decls;
19677   Decls.reserve(ReductionTypes.size());
19678 
19679   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
19680                       forRedeclarationInCurContext());
19681   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
19682   // A reduction-identifier may not be re-declared in the current scope for the
19683   // same type or for a type that is compatible according to the base language
19684   // rules.
19685   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19686   OMPDeclareReductionDecl *PrevDRD = nullptr;
19687   bool InCompoundScope = true;
19688   if (S != nullptr) {
19689     // Find previous declaration with the same name not referenced in other
19690     // declarations.
19691     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19692     InCompoundScope =
19693         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19694     LookupName(Lookup, S);
19695     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19696                          /*AllowInlineNamespace=*/false);
19697     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
19698     LookupResult::Filter Filter = Lookup.makeFilter();
19699     while (Filter.hasNext()) {
19700       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
19701       if (InCompoundScope) {
19702         auto I = UsedAsPrevious.find(PrevDecl);
19703         if (I == UsedAsPrevious.end())
19704           UsedAsPrevious[PrevDecl] = false;
19705         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
19706           UsedAsPrevious[D] = true;
19707       }
19708       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19709           PrevDecl->getLocation();
19710     }
19711     Filter.done();
19712     if (InCompoundScope) {
19713       for (const auto &PrevData : UsedAsPrevious) {
19714         if (!PrevData.second) {
19715           PrevDRD = PrevData.first;
19716           break;
19717         }
19718       }
19719     }
19720   } else if (PrevDeclInScope != nullptr) {
19721     auto *PrevDRDInScope = PrevDRD =
19722         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
19723     do {
19724       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
19725           PrevDRDInScope->getLocation();
19726       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
19727     } while (PrevDRDInScope != nullptr);
19728   }
19729   for (const auto &TyData : ReductionTypes) {
19730     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
19731     bool Invalid = false;
19732     if (I != PreviousRedeclTypes.end()) {
19733       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
19734           << TyData.first;
19735       Diag(I->second, diag::note_previous_definition);
19736       Invalid = true;
19737     }
19738     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
19739     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
19740                                                 Name, TyData.first, PrevDRD);
19741     DC->addDecl(DRD);
19742     DRD->setAccess(AS);
19743     Decls.push_back(DRD);
19744     if (Invalid)
19745       DRD->setInvalidDecl();
19746     else
19747       PrevDRD = DRD;
19748   }
19749 
19750   return DeclGroupPtrTy::make(
19751       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
19752 }
19753 
19754 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
19755   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19756 
19757   // Enter new function scope.
19758   PushFunctionScope();
19759   setFunctionHasBranchProtectedScope();
19760   getCurFunction()->setHasOMPDeclareReductionCombiner();
19761 
19762   if (S != nullptr)
19763     PushDeclContext(S, DRD);
19764   else
19765     CurContext = DRD;
19766 
19767   PushExpressionEvaluationContext(
19768       ExpressionEvaluationContext::PotentiallyEvaluated);
19769 
19770   QualType ReductionType = DRD->getType();
19771   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
19772   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
19773   // uses semantics of argument handles by value, but it should be passed by
19774   // reference. C lang does not support references, so pass all parameters as
19775   // pointers.
19776   // Create 'T omp_in;' variable.
19777   VarDecl *OmpInParm =
19778       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
19779   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
19780   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
19781   // uses semantics of argument handles by value, but it should be passed by
19782   // reference. C lang does not support references, so pass all parameters as
19783   // pointers.
19784   // Create 'T omp_out;' variable.
19785   VarDecl *OmpOutParm =
19786       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
19787   if (S != nullptr) {
19788     PushOnScopeChains(OmpInParm, S);
19789     PushOnScopeChains(OmpOutParm, S);
19790   } else {
19791     DRD->addDecl(OmpInParm);
19792     DRD->addDecl(OmpOutParm);
19793   }
19794   Expr *InE =
19795       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
19796   Expr *OutE =
19797       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
19798   DRD->setCombinerData(InE, OutE);
19799 }
19800 
19801 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
19802   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19803   DiscardCleanupsInEvaluationContext();
19804   PopExpressionEvaluationContext();
19805 
19806   PopDeclContext();
19807   PopFunctionScopeInfo();
19808 
19809   if (Combiner != nullptr)
19810     DRD->setCombiner(Combiner);
19811   else
19812     DRD->setInvalidDecl();
19813 }
19814 
19815 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
19816   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19817 
19818   // Enter new function scope.
19819   PushFunctionScope();
19820   setFunctionHasBranchProtectedScope();
19821 
19822   if (S != nullptr)
19823     PushDeclContext(S, DRD);
19824   else
19825     CurContext = DRD;
19826 
19827   PushExpressionEvaluationContext(
19828       ExpressionEvaluationContext::PotentiallyEvaluated);
19829 
19830   QualType ReductionType = DRD->getType();
19831   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
19832   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
19833   // uses semantics of argument handles by value, but it should be passed by
19834   // reference. C lang does not support references, so pass all parameters as
19835   // pointers.
19836   // Create 'T omp_priv;' variable.
19837   VarDecl *OmpPrivParm =
19838       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
19839   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
19840   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
19841   // uses semantics of argument handles by value, but it should be passed by
19842   // reference. C lang does not support references, so pass all parameters as
19843   // pointers.
19844   // Create 'T omp_orig;' variable.
19845   VarDecl *OmpOrigParm =
19846       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
19847   if (S != nullptr) {
19848     PushOnScopeChains(OmpPrivParm, S);
19849     PushOnScopeChains(OmpOrigParm, S);
19850   } else {
19851     DRD->addDecl(OmpPrivParm);
19852     DRD->addDecl(OmpOrigParm);
19853   }
19854   Expr *OrigE =
19855       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
19856   Expr *PrivE =
19857       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
19858   DRD->setInitializerData(OrigE, PrivE);
19859   return OmpPrivParm;
19860 }
19861 
19862 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
19863                                                      VarDecl *OmpPrivParm) {
19864   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19865   DiscardCleanupsInEvaluationContext();
19866   PopExpressionEvaluationContext();
19867 
19868   PopDeclContext();
19869   PopFunctionScopeInfo();
19870 
19871   if (Initializer != nullptr) {
19872     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
19873   } else if (OmpPrivParm->hasInit()) {
19874     DRD->setInitializer(OmpPrivParm->getInit(),
19875                         OmpPrivParm->isDirectInit()
19876                             ? OMPDeclareReductionDecl::DirectInit
19877                             : OMPDeclareReductionDecl::CopyInit);
19878   } else {
19879     DRD->setInvalidDecl();
19880   }
19881 }
19882 
19883 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
19884     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
19885   for (Decl *D : DeclReductions.get()) {
19886     if (IsValid) {
19887       if (S)
19888         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
19889                           /*AddToContext=*/false);
19890     } else {
19891       D->setInvalidDecl();
19892     }
19893   }
19894   return DeclReductions;
19895 }
19896 
19897 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
19898   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
19899   QualType T = TInfo->getType();
19900   if (D.isInvalidType())
19901     return true;
19902 
19903   if (getLangOpts().CPlusPlus) {
19904     // Check that there are no default arguments (C++ only).
19905     CheckExtraCXXDefaultArguments(D);
19906   }
19907 
19908   return CreateParsedType(T, TInfo);
19909 }
19910 
19911 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
19912                                             TypeResult ParsedType) {
19913   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
19914 
19915   QualType MapperType = GetTypeFromParser(ParsedType.get());
19916   assert(!MapperType.isNull() && "Expect valid mapper type");
19917 
19918   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19919   //  The type must be of struct, union or class type in C and C++
19920   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
19921     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
19922     return QualType();
19923   }
19924   return MapperType;
19925 }
19926 
19927 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
19928     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
19929     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
19930     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
19931   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
19932                       forRedeclarationInCurContext());
19933   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19934   //  A mapper-identifier may not be redeclared in the current scope for the
19935   //  same type or for a type that is compatible according to the base language
19936   //  rules.
19937   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19938   OMPDeclareMapperDecl *PrevDMD = nullptr;
19939   bool InCompoundScope = true;
19940   if (S != nullptr) {
19941     // Find previous declaration with the same name not referenced in other
19942     // declarations.
19943     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19944     InCompoundScope =
19945         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19946     LookupName(Lookup, S);
19947     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19948                          /*AllowInlineNamespace=*/false);
19949     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
19950     LookupResult::Filter Filter = Lookup.makeFilter();
19951     while (Filter.hasNext()) {
19952       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
19953       if (InCompoundScope) {
19954         auto I = UsedAsPrevious.find(PrevDecl);
19955         if (I == UsedAsPrevious.end())
19956           UsedAsPrevious[PrevDecl] = false;
19957         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
19958           UsedAsPrevious[D] = true;
19959       }
19960       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19961           PrevDecl->getLocation();
19962     }
19963     Filter.done();
19964     if (InCompoundScope) {
19965       for (const auto &PrevData : UsedAsPrevious) {
19966         if (!PrevData.second) {
19967           PrevDMD = PrevData.first;
19968           break;
19969         }
19970       }
19971     }
19972   } else if (PrevDeclInScope) {
19973     auto *PrevDMDInScope = PrevDMD =
19974         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
19975     do {
19976       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
19977           PrevDMDInScope->getLocation();
19978       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
19979     } while (PrevDMDInScope != nullptr);
19980   }
19981   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
19982   bool Invalid = false;
19983   if (I != PreviousRedeclTypes.end()) {
19984     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
19985         << MapperType << Name;
19986     Diag(I->second, diag::note_previous_definition);
19987     Invalid = true;
19988   }
19989   // Build expressions for implicit maps of data members with 'default'
19990   // mappers.
19991   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
19992                                                   Clauses.end());
19993   if (LangOpts.OpenMP >= 50)
19994     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
19995   auto *DMD =
19996       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
19997                                    ClausesWithImplicit, PrevDMD);
19998   if (S)
19999     PushOnScopeChains(DMD, S);
20000   else
20001     DC->addDecl(DMD);
20002   DMD->setAccess(AS);
20003   if (Invalid)
20004     DMD->setInvalidDecl();
20005 
20006   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
20007   VD->setDeclContext(DMD);
20008   VD->setLexicalDeclContext(DMD);
20009   DMD->addDecl(VD);
20010   DMD->setMapperVarRef(MapperVarRef);
20011 
20012   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
20013 }
20014 
20015 ExprResult
20016 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
20017                                                SourceLocation StartLoc,
20018                                                DeclarationName VN) {
20019   TypeSourceInfo *TInfo =
20020       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
20021   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
20022                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
20023                              MapperType, TInfo, SC_None);
20024   if (S)
20025     PushOnScopeChains(VD, S, /*AddToContext=*/false);
20026   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
20027   DSAStack->addDeclareMapperVarRef(E);
20028   return E;
20029 }
20030 
20031 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
20032   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20033   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
20034   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
20035     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
20036       return true;
20037     if (VD->isUsableInConstantExpressions(Context))
20038       return true;
20039     return false;
20040   }
20041   return true;
20042 }
20043 
20044 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
20045   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20046   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
20047 }
20048 
20049 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
20050                                            SourceLocation StartLoc,
20051                                            SourceLocation LParenLoc,
20052                                            SourceLocation EndLoc) {
20053   Expr *ValExpr = NumTeams;
20054   Stmt *HelperValStmt = nullptr;
20055 
20056   // OpenMP [teams Constrcut, Restrictions]
20057   // The num_teams expression must evaluate to a positive integer value.
20058   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
20059                                  /*StrictlyPositive=*/true))
20060     return nullptr;
20061 
20062   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20063   OpenMPDirectiveKind CaptureRegion =
20064       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
20065   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20066     ValExpr = MakeFullExpr(ValExpr).get();
20067     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20068     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20069     HelperValStmt = buildPreInits(Context, Captures);
20070   }
20071 
20072   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
20073                                          StartLoc, LParenLoc, EndLoc);
20074 }
20075 
20076 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
20077                                               SourceLocation StartLoc,
20078                                               SourceLocation LParenLoc,
20079                                               SourceLocation EndLoc) {
20080   Expr *ValExpr = ThreadLimit;
20081   Stmt *HelperValStmt = nullptr;
20082 
20083   // OpenMP [teams Constrcut, Restrictions]
20084   // The thread_limit expression must evaluate to a positive integer value.
20085   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
20086                                  /*StrictlyPositive=*/true))
20087     return nullptr;
20088 
20089   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20090   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
20091       DKind, OMPC_thread_limit, LangOpts.OpenMP);
20092   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20093     ValExpr = MakeFullExpr(ValExpr).get();
20094     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20095     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20096     HelperValStmt = buildPreInits(Context, Captures);
20097   }
20098 
20099   return new (Context) OMPThreadLimitClause(
20100       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20101 }
20102 
20103 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
20104                                            SourceLocation StartLoc,
20105                                            SourceLocation LParenLoc,
20106                                            SourceLocation EndLoc) {
20107   Expr *ValExpr = Priority;
20108   Stmt *HelperValStmt = nullptr;
20109   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20110 
20111   // OpenMP [2.9.1, task Constrcut]
20112   // The priority-value is a non-negative numerical scalar expression.
20113   if (!isNonNegativeIntegerValue(
20114           ValExpr, *this, OMPC_priority,
20115           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
20116           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20117     return nullptr;
20118 
20119   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
20120                                          StartLoc, LParenLoc, EndLoc);
20121 }
20122 
20123 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
20124                                             SourceLocation StartLoc,
20125                                             SourceLocation LParenLoc,
20126                                             SourceLocation EndLoc) {
20127   Expr *ValExpr = Grainsize;
20128   Stmt *HelperValStmt = nullptr;
20129   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20130 
20131   // OpenMP [2.9.2, taskloop Constrcut]
20132   // The parameter of the grainsize clause must be a positive integer
20133   // expression.
20134   if (!isNonNegativeIntegerValue(
20135           ValExpr, *this, OMPC_grainsize,
20136           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20137           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20138     return nullptr;
20139 
20140   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
20141                                           StartLoc, LParenLoc, EndLoc);
20142 }
20143 
20144 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
20145                                            SourceLocation StartLoc,
20146                                            SourceLocation LParenLoc,
20147                                            SourceLocation EndLoc) {
20148   Expr *ValExpr = NumTasks;
20149   Stmt *HelperValStmt = nullptr;
20150   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20151 
20152   // OpenMP [2.9.2, taskloop Constrcut]
20153   // The parameter of the num_tasks clause must be a positive integer
20154   // expression.
20155   if (!isNonNegativeIntegerValue(
20156           ValExpr, *this, OMPC_num_tasks,
20157           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20158           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20159     return nullptr;
20160 
20161   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
20162                                          StartLoc, LParenLoc, EndLoc);
20163 }
20164 
20165 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
20166                                        SourceLocation LParenLoc,
20167                                        SourceLocation EndLoc) {
20168   // OpenMP [2.13.2, critical construct, Description]
20169   // ... where hint-expression is an integer constant expression that evaluates
20170   // to a valid lock hint.
20171   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
20172   if (HintExpr.isInvalid())
20173     return nullptr;
20174   return new (Context)
20175       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
20176 }
20177 
20178 /// Tries to find omp_event_handle_t type.
20179 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
20180                                 DSAStackTy *Stack) {
20181   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
20182   if (!OMPEventHandleT.isNull())
20183     return true;
20184   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
20185   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
20186   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20187     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
20188     return false;
20189   }
20190   Stack->setOMPEventHandleT(PT.get());
20191   return true;
20192 }
20193 
20194 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
20195                                          SourceLocation LParenLoc,
20196                                          SourceLocation EndLoc) {
20197   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
20198       !Evt->isInstantiationDependent() &&
20199       !Evt->containsUnexpandedParameterPack()) {
20200     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
20201       return nullptr;
20202     // OpenMP 5.0, 2.10.1 task Construct.
20203     // event-handle is a variable of the omp_event_handle_t type.
20204     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
20205     if (!Ref) {
20206       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20207           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20208       return nullptr;
20209     }
20210     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
20211     if (!VD) {
20212       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20213           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20214       return nullptr;
20215     }
20216     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
20217                                         VD->getType()) ||
20218         VD->getType().isConstant(Context)) {
20219       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20220           << "omp_event_handle_t" << 1 << VD->getType()
20221           << Evt->getSourceRange();
20222       return nullptr;
20223     }
20224     // OpenMP 5.0, 2.10.1 task Construct
20225     // [detach clause]... The event-handle will be considered as if it was
20226     // specified on a firstprivate clause.
20227     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
20228     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
20229         DVar.RefExpr) {
20230       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
20231           << getOpenMPClauseName(DVar.CKind)
20232           << getOpenMPClauseName(OMPC_firstprivate);
20233       reportOriginalDsa(*this, DSAStack, VD, DVar);
20234       return nullptr;
20235     }
20236   }
20237 
20238   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
20239 }
20240 
20241 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
20242     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
20243     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
20244     SourceLocation EndLoc) {
20245   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
20246     std::string Values;
20247     Values += "'";
20248     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
20249     Values += "'";
20250     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20251         << Values << getOpenMPClauseName(OMPC_dist_schedule);
20252     return nullptr;
20253   }
20254   Expr *ValExpr = ChunkSize;
20255   Stmt *HelperValStmt = nullptr;
20256   if (ChunkSize) {
20257     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
20258         !ChunkSize->isInstantiationDependent() &&
20259         !ChunkSize->containsUnexpandedParameterPack()) {
20260       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
20261       ExprResult Val =
20262           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
20263       if (Val.isInvalid())
20264         return nullptr;
20265 
20266       ValExpr = Val.get();
20267 
20268       // OpenMP [2.7.1, Restrictions]
20269       //  chunk_size must be a loop invariant integer expression with a positive
20270       //  value.
20271       if (Optional<llvm::APSInt> Result =
20272               ValExpr->getIntegerConstantExpr(Context)) {
20273         if (Result->isSigned() && !Result->isStrictlyPositive()) {
20274           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
20275               << "dist_schedule" << ChunkSize->getSourceRange();
20276           return nullptr;
20277         }
20278       } else if (getOpenMPCaptureRegionForClause(
20279                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
20280                      LangOpts.OpenMP) != OMPD_unknown &&
20281                  !CurContext->isDependentContext()) {
20282         ValExpr = MakeFullExpr(ValExpr).get();
20283         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20284         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20285         HelperValStmt = buildPreInits(Context, Captures);
20286       }
20287     }
20288   }
20289 
20290   return new (Context)
20291       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
20292                             Kind, ValExpr, HelperValStmt);
20293 }
20294 
20295 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
20296     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
20297     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
20298     SourceLocation KindLoc, SourceLocation EndLoc) {
20299   if (getLangOpts().OpenMP < 50) {
20300     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
20301         Kind != OMPC_DEFAULTMAP_scalar) {
20302       std::string Value;
20303       SourceLocation Loc;
20304       Value += "'";
20305       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
20306         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20307                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
20308         Loc = MLoc;
20309       } else {
20310         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20311                                                OMPC_DEFAULTMAP_scalar);
20312         Loc = KindLoc;
20313       }
20314       Value += "'";
20315       Diag(Loc, diag::err_omp_unexpected_clause_value)
20316           << Value << getOpenMPClauseName(OMPC_defaultmap);
20317       return nullptr;
20318     }
20319   } else {
20320     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
20321     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
20322                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
20323     if (!isDefaultmapKind || !isDefaultmapModifier) {
20324       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
20325       if (LangOpts.OpenMP == 50) {
20326         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
20327                                   "'firstprivate', 'none', 'default'";
20328         if (!isDefaultmapKind && isDefaultmapModifier) {
20329           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20330               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20331         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20332           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20333               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20334         } else {
20335           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20336               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20337           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20338               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20339         }
20340       } else {
20341         StringRef ModifierValue =
20342             "'alloc', 'from', 'to', 'tofrom', "
20343             "'firstprivate', 'none', 'default', 'present'";
20344         if (!isDefaultmapKind && isDefaultmapModifier) {
20345           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20346               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20347         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20348           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20349               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20350         } else {
20351           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20352               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20353           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20354               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20355         }
20356       }
20357       return nullptr;
20358     }
20359 
20360     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
20361     //  At most one defaultmap clause for each category can appear on the
20362     //  directive.
20363     if (DSAStack->checkDefaultmapCategory(Kind)) {
20364       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
20365       return nullptr;
20366     }
20367   }
20368   if (Kind == OMPC_DEFAULTMAP_unknown) {
20369     // Variable category is not specified - mark all categories.
20370     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
20371     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
20372     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
20373   } else {
20374     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
20375   }
20376 
20377   return new (Context)
20378       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
20379 }
20380 
20381 bool Sema::ActOnStartOpenMPDeclareTargetContext(
20382     DeclareTargetContextInfo &DTCI) {
20383   DeclContext *CurLexicalContext = getCurLexicalContext();
20384   if (!CurLexicalContext->isFileContext() &&
20385       !CurLexicalContext->isExternCContext() &&
20386       !CurLexicalContext->isExternCXXContext() &&
20387       !isa<CXXRecordDecl>(CurLexicalContext) &&
20388       !isa<ClassTemplateDecl>(CurLexicalContext) &&
20389       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
20390       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
20391     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
20392     return false;
20393   }
20394   DeclareTargetNesting.push_back(DTCI);
20395   return true;
20396 }
20397 
20398 const Sema::DeclareTargetContextInfo
20399 Sema::ActOnOpenMPEndDeclareTargetDirective() {
20400   assert(!DeclareTargetNesting.empty() &&
20401          "check isInOpenMPDeclareTargetContext() first!");
20402   return DeclareTargetNesting.pop_back_val();
20403 }
20404 
20405 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
20406     DeclareTargetContextInfo &DTCI) {
20407   for (auto &It : DTCI.ExplicitlyMapped)
20408     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT,
20409                                  DTCI.DT);
20410 }
20411 
20412 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
20413                                                CXXScopeSpec &ScopeSpec,
20414                                                const DeclarationNameInfo &Id) {
20415   LookupResult Lookup(*this, Id, LookupOrdinaryName);
20416   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
20417 
20418   if (Lookup.isAmbiguous())
20419     return nullptr;
20420   Lookup.suppressDiagnostics();
20421 
20422   if (!Lookup.isSingleResult()) {
20423     VarOrFuncDeclFilterCCC CCC(*this);
20424     if (TypoCorrection Corrected =
20425             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
20426                         CTK_ErrorRecovery)) {
20427       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
20428                                   << Id.getName());
20429       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
20430       return nullptr;
20431     }
20432 
20433     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
20434     return nullptr;
20435   }
20436 
20437   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
20438   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
20439       !isa<FunctionTemplateDecl>(ND)) {
20440     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
20441     return nullptr;
20442   }
20443   return ND;
20444 }
20445 
20446 void Sema::ActOnOpenMPDeclareTargetName(
20447     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
20448     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
20449   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
20450           isa<FunctionTemplateDecl>(ND)) &&
20451          "Expected variable, function or function template.");
20452 
20453   // Diagnose marking after use as it may lead to incorrect diagnosis and
20454   // codegen.
20455   if (LangOpts.OpenMP >= 50 &&
20456       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
20457     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
20458 
20459   // Explicit declare target lists have precedence.
20460   const unsigned Level = -1;
20461 
20462   auto *VD = cast<ValueDecl>(ND);
20463   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20464       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20465   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT &&
20466       ActiveAttr.getValue()->getLevel() == Level) {
20467     Diag(Loc, diag::err_omp_device_type_mismatch)
20468         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
20469         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
20470                ActiveAttr.getValue()->getDevType());
20471     return;
20472   }
20473   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
20474       ActiveAttr.getValue()->getLevel() == Level) {
20475     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20476     return;
20477   }
20478 
20479   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
20480     return;
20481 
20482   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level,
20483                                                      SourceRange(Loc, Loc));
20484   ND->addAttr(A);
20485   if (ASTMutationListener *ML = Context.getASTMutationListener())
20486     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
20487   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20488 }
20489 
20490 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20491                                      Sema &SemaRef, Decl *D) {
20492   if (!D || !isa<VarDecl>(D))
20493     return;
20494   auto *VD = cast<VarDecl>(D);
20495   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20496       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20497   if (SemaRef.LangOpts.OpenMP >= 50 &&
20498       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20499        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20500       VD->hasGlobalStorage()) {
20501     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20502       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20503       // If a lambda declaration and definition appears between a
20504       // declare target directive and the matching end declare target
20505       // directive, all variables that are captured by the lambda
20506       // expression must also appear in a to clause.
20507       SemaRef.Diag(VD->getLocation(),
20508                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20509       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20510           << VD << 0 << SR;
20511       return;
20512     }
20513   }
20514   if (MapTy.hasValue())
20515     return;
20516   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20517   SemaRef.Diag(SL, diag::note_used_here) << SR;
20518 }
20519 
20520 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20521                                    Sema &SemaRef, DSAStackTy *Stack,
20522                                    ValueDecl *VD) {
20523   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20524          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20525                            /*FullCheck=*/false);
20526 }
20527 
20528 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20529                                             SourceLocation IdLoc) {
20530   if (!D || D->isInvalidDecl())
20531     return;
20532   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20533   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20534   if (auto *VD = dyn_cast<VarDecl>(D)) {
20535     // Only global variables can be marked as declare target.
20536     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20537         !VD->isStaticDataMember())
20538       return;
20539     // 2.10.6: threadprivate variable cannot appear in a declare target
20540     // directive.
20541     if (DSAStack->isThreadPrivate(VD)) {
20542       Diag(SL, diag::err_omp_threadprivate_in_target);
20543       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20544       return;
20545     }
20546   }
20547   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20548     D = FTD->getTemplatedDecl();
20549   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20550     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20551         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20552     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20553       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20554       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20555       return;
20556     }
20557   }
20558   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20559     // Problem if any with var declared with incomplete type will be reported
20560     // as normal, so no need to check it here.
20561     if ((E || !VD->getType()->isIncompleteType()) &&
20562         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20563       return;
20564     if (!E && isInOpenMPDeclareTargetContext()) {
20565       // Checking declaration inside declare target region.
20566       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20567           isa<FunctionTemplateDecl>(D)) {
20568         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20569             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20570         unsigned Level = DeclareTargetNesting.size();
20571         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
20572           return;
20573         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
20574         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20575             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level,
20576             SourceRange(DTCI.Loc, DTCI.Loc));
20577         D->addAttr(A);
20578         if (ASTMutationListener *ML = Context.getASTMutationListener())
20579           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20580       }
20581       return;
20582     }
20583   }
20584   if (!E)
20585     return;
20586   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20587 }
20588 
20589 OMPClause *Sema::ActOnOpenMPToClause(
20590     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20591     ArrayRef<SourceLocation> MotionModifiersLoc,
20592     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20593     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20594     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20595   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20596                                           OMPC_MOTION_MODIFIER_unknown};
20597   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20598 
20599   // Process motion-modifiers, flag errors for duplicate modifiers.
20600   unsigned Count = 0;
20601   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20602     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20603         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20604       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20605       continue;
20606     }
20607     assert(Count < NumberOfOMPMotionModifiers &&
20608            "Modifiers exceed the allowed number of motion modifiers");
20609     Modifiers[Count] = MotionModifiers[I];
20610     ModifiersLoc[Count] = MotionModifiersLoc[I];
20611     ++Count;
20612   }
20613 
20614   MappableVarListInfo MVLI(VarList);
20615   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20616                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20617   if (MVLI.ProcessedVarList.empty())
20618     return nullptr;
20619 
20620   return OMPToClause::Create(
20621       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20622       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20623       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20624 }
20625 
20626 OMPClause *Sema::ActOnOpenMPFromClause(
20627     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20628     ArrayRef<SourceLocation> MotionModifiersLoc,
20629     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20630     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20631     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20632   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20633                                           OMPC_MOTION_MODIFIER_unknown};
20634   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20635 
20636   // Process motion-modifiers, flag errors for duplicate modifiers.
20637   unsigned Count = 0;
20638   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20639     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20640         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20641       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20642       continue;
20643     }
20644     assert(Count < NumberOfOMPMotionModifiers &&
20645            "Modifiers exceed the allowed number of motion modifiers");
20646     Modifiers[Count] = MotionModifiers[I];
20647     ModifiersLoc[Count] = MotionModifiersLoc[I];
20648     ++Count;
20649   }
20650 
20651   MappableVarListInfo MVLI(VarList);
20652   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20653                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20654   if (MVLI.ProcessedVarList.empty())
20655     return nullptr;
20656 
20657   return OMPFromClause::Create(
20658       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20659       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20660       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20661 }
20662 
20663 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20664                                                const OMPVarListLocTy &Locs) {
20665   MappableVarListInfo MVLI(VarList);
20666   SmallVector<Expr *, 8> PrivateCopies;
20667   SmallVector<Expr *, 8> Inits;
20668 
20669   for (Expr *RefExpr : VarList) {
20670     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
20671     SourceLocation ELoc;
20672     SourceRange ERange;
20673     Expr *SimpleRefExpr = RefExpr;
20674     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20675     if (Res.second) {
20676       // It will be analyzed later.
20677       MVLI.ProcessedVarList.push_back(RefExpr);
20678       PrivateCopies.push_back(nullptr);
20679       Inits.push_back(nullptr);
20680     }
20681     ValueDecl *D = Res.first;
20682     if (!D)
20683       continue;
20684 
20685     QualType Type = D->getType();
20686     Type = Type.getNonReferenceType().getUnqualifiedType();
20687 
20688     auto *VD = dyn_cast<VarDecl>(D);
20689 
20690     // Item should be a pointer or reference to pointer.
20691     if (!Type->isPointerType()) {
20692       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
20693           << 0 << RefExpr->getSourceRange();
20694       continue;
20695     }
20696 
20697     // Build the private variable and the expression that refers to it.
20698     auto VDPrivate =
20699         buildVarDecl(*this, ELoc, Type, D->getName(),
20700                      D->hasAttrs() ? &D->getAttrs() : nullptr,
20701                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
20702     if (VDPrivate->isInvalidDecl())
20703       continue;
20704 
20705     CurContext->addDecl(VDPrivate);
20706     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
20707         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
20708 
20709     // Add temporary variable to initialize the private copy of the pointer.
20710     VarDecl *VDInit =
20711         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
20712     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
20713         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
20714     AddInitializerToDecl(VDPrivate,
20715                          DefaultLvalueConversion(VDInitRefExpr).get(),
20716                          /*DirectInit=*/false);
20717 
20718     // If required, build a capture to implement the privatization initialized
20719     // with the current list item value.
20720     DeclRefExpr *Ref = nullptr;
20721     if (!VD)
20722       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20723     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20724     PrivateCopies.push_back(VDPrivateRefExpr);
20725     Inits.push_back(VDInitRefExpr);
20726 
20727     // We need to add a data sharing attribute for this variable to make sure it
20728     // is correctly captured. A variable that shows up in a use_device_ptr has
20729     // similar properties of a first private variable.
20730     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20731 
20732     // Create a mappable component for the list item. List items in this clause
20733     // only need a component.
20734     MVLI.VarBaseDeclarations.push_back(D);
20735     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20736     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
20737                                            /*IsNonContiguous=*/false);
20738   }
20739 
20740   if (MVLI.ProcessedVarList.empty())
20741     return nullptr;
20742 
20743   return OMPUseDevicePtrClause::Create(
20744       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
20745       MVLI.VarBaseDeclarations, MVLI.VarComponents);
20746 }
20747 
20748 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
20749                                                 const OMPVarListLocTy &Locs) {
20750   MappableVarListInfo MVLI(VarList);
20751 
20752   for (Expr *RefExpr : VarList) {
20753     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
20754     SourceLocation ELoc;
20755     SourceRange ERange;
20756     Expr *SimpleRefExpr = RefExpr;
20757     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20758                               /*AllowArraySection=*/true);
20759     if (Res.second) {
20760       // It will be analyzed later.
20761       MVLI.ProcessedVarList.push_back(RefExpr);
20762     }
20763     ValueDecl *D = Res.first;
20764     if (!D)
20765       continue;
20766     auto *VD = dyn_cast<VarDecl>(D);
20767 
20768     // If required, build a capture to implement the privatization initialized
20769     // with the current list item value.
20770     DeclRefExpr *Ref = nullptr;
20771     if (!VD)
20772       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20773     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20774 
20775     // We need to add a data sharing attribute for this variable to make sure it
20776     // is correctly captured. A variable that shows up in a use_device_addr has
20777     // similar properties of a first private variable.
20778     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20779 
20780     // Create a mappable component for the list item. List items in this clause
20781     // only need a component.
20782     MVLI.VarBaseDeclarations.push_back(D);
20783     MVLI.VarComponents.emplace_back();
20784     Expr *Component = SimpleRefExpr;
20785     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
20786                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
20787       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
20788     MVLI.VarComponents.back().emplace_back(Component, D,
20789                                            /*IsNonContiguous=*/false);
20790   }
20791 
20792   if (MVLI.ProcessedVarList.empty())
20793     return nullptr;
20794 
20795   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20796                                         MVLI.VarBaseDeclarations,
20797                                         MVLI.VarComponents);
20798 }
20799 
20800 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
20801                                               const OMPVarListLocTy &Locs) {
20802   MappableVarListInfo MVLI(VarList);
20803   for (Expr *RefExpr : VarList) {
20804     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
20805     SourceLocation ELoc;
20806     SourceRange ERange;
20807     Expr *SimpleRefExpr = RefExpr;
20808     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20809     if (Res.second) {
20810       // It will be analyzed later.
20811       MVLI.ProcessedVarList.push_back(RefExpr);
20812     }
20813     ValueDecl *D = Res.first;
20814     if (!D)
20815       continue;
20816 
20817     QualType Type = D->getType();
20818     // item should be a pointer or array or reference to pointer or array
20819     if (!Type.getNonReferenceType()->isPointerType() &&
20820         !Type.getNonReferenceType()->isArrayType()) {
20821       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
20822           << 0 << RefExpr->getSourceRange();
20823       continue;
20824     }
20825 
20826     // Check if the declaration in the clause does not show up in any data
20827     // sharing attribute.
20828     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
20829     if (isOpenMPPrivate(DVar.CKind)) {
20830       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
20831           << getOpenMPClauseName(DVar.CKind)
20832           << getOpenMPClauseName(OMPC_is_device_ptr)
20833           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
20834       reportOriginalDsa(*this, DSAStack, D, DVar);
20835       continue;
20836     }
20837 
20838     const Expr *ConflictExpr;
20839     if (DSAStack->checkMappableExprComponentListsForDecl(
20840             D, /*CurrentRegionOnly=*/true,
20841             [&ConflictExpr](
20842                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
20843                 OpenMPClauseKind) -> bool {
20844               ConflictExpr = R.front().getAssociatedExpression();
20845               return true;
20846             })) {
20847       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
20848       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
20849           << ConflictExpr->getSourceRange();
20850       continue;
20851     }
20852 
20853     // Store the components in the stack so that they can be used to check
20854     // against other clauses later on.
20855     OMPClauseMappableExprCommon::MappableComponent MC(
20856         SimpleRefExpr, D, /*IsNonContiguous=*/false);
20857     DSAStack->addMappableExpressionComponents(
20858         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
20859 
20860     // Record the expression we've just processed.
20861     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
20862 
20863     // Create a mappable component for the list item. List items in this clause
20864     // only need a component. We use a null declaration to signal fields in
20865     // 'this'.
20866     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
20867             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
20868            "Unexpected device pointer expression!");
20869     MVLI.VarBaseDeclarations.push_back(
20870         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
20871     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20872     MVLI.VarComponents.back().push_back(MC);
20873   }
20874 
20875   if (MVLI.ProcessedVarList.empty())
20876     return nullptr;
20877 
20878   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20879                                       MVLI.VarBaseDeclarations,
20880                                       MVLI.VarComponents);
20881 }
20882 
20883 OMPClause *Sema::ActOnOpenMPAllocateClause(
20884     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
20885     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
20886   if (Allocator) {
20887     // OpenMP [2.11.4 allocate Clause, Description]
20888     // allocator is an expression of omp_allocator_handle_t type.
20889     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
20890       return nullptr;
20891 
20892     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
20893     if (AllocatorRes.isInvalid())
20894       return nullptr;
20895     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
20896                                              DSAStack->getOMPAllocatorHandleT(),
20897                                              Sema::AA_Initializing,
20898                                              /*AllowExplicit=*/true);
20899     if (AllocatorRes.isInvalid())
20900       return nullptr;
20901     Allocator = AllocatorRes.get();
20902   } else {
20903     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
20904     // allocate clauses that appear on a target construct or on constructs in a
20905     // target region must specify an allocator expression unless a requires
20906     // directive with the dynamic_allocators clause is present in the same
20907     // compilation unit.
20908     if (LangOpts.OpenMPIsDevice &&
20909         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
20910       targetDiag(StartLoc, diag::err_expected_allocator_expression);
20911   }
20912   // Analyze and build list of variables.
20913   SmallVector<Expr *, 8> Vars;
20914   for (Expr *RefExpr : VarList) {
20915     assert(RefExpr && "NULL expr in OpenMP private clause.");
20916     SourceLocation ELoc;
20917     SourceRange ERange;
20918     Expr *SimpleRefExpr = RefExpr;
20919     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20920     if (Res.second) {
20921       // It will be analyzed later.
20922       Vars.push_back(RefExpr);
20923     }
20924     ValueDecl *D = Res.first;
20925     if (!D)
20926       continue;
20927 
20928     auto *VD = dyn_cast<VarDecl>(D);
20929     DeclRefExpr *Ref = nullptr;
20930     if (!VD && !CurContext->isDependentContext())
20931       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
20932     Vars.push_back((VD || CurContext->isDependentContext())
20933                        ? RefExpr->IgnoreParens()
20934                        : Ref);
20935   }
20936 
20937   if (Vars.empty())
20938     return nullptr;
20939 
20940   if (Allocator)
20941     DSAStack->addInnerAllocatorExpr(Allocator);
20942   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
20943                                    ColonLoc, EndLoc, Vars);
20944 }
20945 
20946 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
20947                                               SourceLocation StartLoc,
20948                                               SourceLocation LParenLoc,
20949                                               SourceLocation EndLoc) {
20950   SmallVector<Expr *, 8> Vars;
20951   for (Expr *RefExpr : VarList) {
20952     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20953     SourceLocation ELoc;
20954     SourceRange ERange;
20955     Expr *SimpleRefExpr = RefExpr;
20956     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20957     if (Res.second)
20958       // It will be analyzed later.
20959       Vars.push_back(RefExpr);
20960     ValueDecl *D = Res.first;
20961     if (!D)
20962       continue;
20963 
20964     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
20965     // A list-item cannot appear in more than one nontemporal clause.
20966     if (const Expr *PrevRef =
20967             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
20968       Diag(ELoc, diag::err_omp_used_in_clause_twice)
20969           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
20970       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
20971           << getOpenMPClauseName(OMPC_nontemporal);
20972       continue;
20973     }
20974 
20975     Vars.push_back(RefExpr);
20976   }
20977 
20978   if (Vars.empty())
20979     return nullptr;
20980 
20981   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20982                                       Vars);
20983 }
20984 
20985 OMPClause *Sema::ActOnOpenMPInclusiveClause(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                               /*AllowArraySection=*/true);
20997     if (Res.second)
20998       // It will be analyzed later.
20999       Vars.push_back(RefExpr);
21000     ValueDecl *D = Res.first;
21001     if (!D)
21002       continue;
21003 
21004     const DSAStackTy::DSAVarData DVar =
21005         DSAStack->getTopDSA(D, /*FromParent=*/true);
21006     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21007     // A list item that appears in the inclusive or exclusive clause must appear
21008     // in a reduction clause with the inscan modifier on the enclosing
21009     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21010     if (DVar.CKind != OMPC_reduction ||
21011         DVar.Modifier != OMPC_REDUCTION_inscan)
21012       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21013           << RefExpr->getSourceRange();
21014 
21015     if (DSAStack->getParentDirective() != OMPD_unknown)
21016       DSAStack->markDeclAsUsedInScanDirective(D);
21017     Vars.push_back(RefExpr);
21018   }
21019 
21020   if (Vars.empty())
21021     return nullptr;
21022 
21023   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21024 }
21025 
21026 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
21027                                             SourceLocation StartLoc,
21028                                             SourceLocation LParenLoc,
21029                                             SourceLocation EndLoc) {
21030   SmallVector<Expr *, 8> Vars;
21031   for (Expr *RefExpr : VarList) {
21032     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21033     SourceLocation ELoc;
21034     SourceRange ERange;
21035     Expr *SimpleRefExpr = RefExpr;
21036     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21037                               /*AllowArraySection=*/true);
21038     if (Res.second)
21039       // It will be analyzed later.
21040       Vars.push_back(RefExpr);
21041     ValueDecl *D = Res.first;
21042     if (!D)
21043       continue;
21044 
21045     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
21046     DSAStackTy::DSAVarData DVar;
21047     if (ParentDirective != OMPD_unknown)
21048       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
21049     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21050     // A list item that appears in the inclusive or exclusive clause must appear
21051     // in a reduction clause with the inscan modifier on the enclosing
21052     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21053     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
21054         DVar.Modifier != OMPC_REDUCTION_inscan) {
21055       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21056           << RefExpr->getSourceRange();
21057     } else {
21058       DSAStack->markDeclAsUsedInScanDirective(D);
21059     }
21060     Vars.push_back(RefExpr);
21061   }
21062 
21063   if (Vars.empty())
21064     return nullptr;
21065 
21066   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21067 }
21068 
21069 /// Tries to find omp_alloctrait_t type.
21070 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
21071   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
21072   if (!OMPAlloctraitT.isNull())
21073     return true;
21074   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
21075   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
21076   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21077     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
21078     return false;
21079   }
21080   Stack->setOMPAlloctraitT(PT.get());
21081   return true;
21082 }
21083 
21084 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
21085     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
21086     ArrayRef<UsesAllocatorsData> Data) {
21087   // OpenMP [2.12.5, target Construct]
21088   // allocator is an identifier of omp_allocator_handle_t type.
21089   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
21090     return nullptr;
21091   // OpenMP [2.12.5, target Construct]
21092   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
21093   if (llvm::any_of(
21094           Data,
21095           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
21096       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
21097     return nullptr;
21098   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
21099   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
21100     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
21101     StringRef Allocator =
21102         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
21103     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
21104     PredefinedAllocators.insert(LookupSingleName(
21105         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
21106   }
21107 
21108   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
21109   for (const UsesAllocatorsData &D : Data) {
21110     Expr *AllocatorExpr = nullptr;
21111     // Check allocator expression.
21112     if (D.Allocator->isTypeDependent()) {
21113       AllocatorExpr = D.Allocator;
21114     } else {
21115       // Traits were specified - need to assign new allocator to the specified
21116       // allocator, so it must be an lvalue.
21117       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
21118       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
21119       bool IsPredefinedAllocator = false;
21120       if (DRE)
21121         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
21122       if (!DRE ||
21123           !(Context.hasSameUnqualifiedType(
21124                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
21125             Context.typesAreCompatible(AllocatorExpr->getType(),
21126                                        DSAStack->getOMPAllocatorHandleT(),
21127                                        /*CompareUnqualified=*/true)) ||
21128           (!IsPredefinedAllocator &&
21129            (AllocatorExpr->getType().isConstant(Context) ||
21130             !AllocatorExpr->isLValue()))) {
21131         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
21132             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
21133             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
21134         continue;
21135       }
21136       // OpenMP [2.12.5, target Construct]
21137       // Predefined allocators appearing in a uses_allocators clause cannot have
21138       // traits specified.
21139       if (IsPredefinedAllocator && D.AllocatorTraits) {
21140         Diag(D.AllocatorTraits->getExprLoc(),
21141              diag::err_omp_predefined_allocator_with_traits)
21142             << D.AllocatorTraits->getSourceRange();
21143         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
21144             << cast<NamedDecl>(DRE->getDecl())->getName()
21145             << D.Allocator->getSourceRange();
21146         continue;
21147       }
21148       // OpenMP [2.12.5, target Construct]
21149       // Non-predefined allocators appearing in a uses_allocators clause must
21150       // have traits specified.
21151       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
21152         Diag(D.Allocator->getExprLoc(),
21153              diag::err_omp_nonpredefined_allocator_without_traits);
21154         continue;
21155       }
21156       // No allocator traits - just convert it to rvalue.
21157       if (!D.AllocatorTraits)
21158         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
21159       DSAStack->addUsesAllocatorsDecl(
21160           DRE->getDecl(),
21161           IsPredefinedAllocator
21162               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
21163               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
21164     }
21165     Expr *AllocatorTraitsExpr = nullptr;
21166     if (D.AllocatorTraits) {
21167       if (D.AllocatorTraits->isTypeDependent()) {
21168         AllocatorTraitsExpr = D.AllocatorTraits;
21169       } else {
21170         // OpenMP [2.12.5, target Construct]
21171         // Arrays that contain allocator traits that appear in a uses_allocators
21172         // clause must be constant arrays, have constant values and be defined
21173         // in the same scope as the construct in which the clause appears.
21174         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
21175         // Check that traits expr is a constant array.
21176         QualType TraitTy;
21177         if (const ArrayType *Ty =
21178                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
21179           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
21180             TraitTy = ConstArrayTy->getElementType();
21181         if (TraitTy.isNull() ||
21182             !(Context.hasSameUnqualifiedType(TraitTy,
21183                                              DSAStack->getOMPAlloctraitT()) ||
21184               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
21185                                          /*CompareUnqualified=*/true))) {
21186           Diag(D.AllocatorTraits->getExprLoc(),
21187                diag::err_omp_expected_array_alloctraits)
21188               << AllocatorTraitsExpr->getType();
21189           continue;
21190         }
21191         // Do not map by default allocator traits if it is a standalone
21192         // variable.
21193         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
21194           DSAStack->addUsesAllocatorsDecl(
21195               DRE->getDecl(),
21196               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
21197       }
21198     }
21199     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
21200     NewD.Allocator = AllocatorExpr;
21201     NewD.AllocatorTraits = AllocatorTraitsExpr;
21202     NewD.LParenLoc = D.LParenLoc;
21203     NewD.RParenLoc = D.RParenLoc;
21204   }
21205   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21206                                          NewData);
21207 }
21208 
21209 OMPClause *Sema::ActOnOpenMPAffinityClause(
21210     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
21211     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
21212   SmallVector<Expr *, 8> Vars;
21213   for (Expr *RefExpr : Locators) {
21214     assert(RefExpr && "NULL expr in OpenMP shared clause.");
21215     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
21216       // It will be analyzed later.
21217       Vars.push_back(RefExpr);
21218       continue;
21219     }
21220 
21221     SourceLocation ELoc = RefExpr->getExprLoc();
21222     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
21223 
21224     if (!SimpleExpr->isLValue()) {
21225       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21226           << 1 << 0 << RefExpr->getSourceRange();
21227       continue;
21228     }
21229 
21230     ExprResult Res;
21231     {
21232       Sema::TentativeAnalysisScope Trap(*this);
21233       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
21234     }
21235     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
21236         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
21237       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21238           << 1 << 0 << RefExpr->getSourceRange();
21239       continue;
21240     }
21241     Vars.push_back(SimpleExpr);
21242   }
21243 
21244   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
21245                                    EndLoc, Modifier, Vars);
21246 }
21247