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 VisitStmt(Stmt *S) {
3814     for (Stmt *C : S->children()) {
3815       if (C) {
3816         // Check implicitly captured variables in the task-based directives to
3817         // check if they must be firstprivatized.
3818         Visit(C);
3819       }
3820     }
3821   }
3822 
3823   void visitSubCaptures(CapturedStmt *S) {
3824     for (const CapturedStmt::Capture &Cap : S->captures()) {
3825       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3826         continue;
3827       VarDecl *VD = Cap.getCapturedVar();
3828       // Do not try to map the variable if it or its sub-component was mapped
3829       // already.
3830       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3831           Stack->checkMappableExprComponentListsForDecl(
3832               VD, /*CurrentRegionOnly=*/true,
3833               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3834                  OpenMPClauseKind) { return true; }))
3835         continue;
3836       DeclRefExpr *DRE = buildDeclRefExpr(
3837           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3838           Cap.getLocation(), /*RefersToCapture=*/true);
3839       Visit(DRE);
3840     }
3841   }
3842   bool isErrorFound() const { return ErrorFound; }
3843   ArrayRef<Expr *> getImplicitFirstprivate() const {
3844     return ImplicitFirstprivate;
3845   }
3846   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3847                                   OpenMPMapClauseKind MK) const {
3848     return ImplicitMap[DK][MK];
3849   }
3850   ArrayRef<OpenMPMapModifierKind>
3851   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3852     return ImplicitMapModifier[Kind];
3853   }
3854   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3855     return VarsWithInheritedDSA;
3856   }
3857 
3858   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3859       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3860     // Process declare target link variables for the target directives.
3861     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3862       for (DeclRefExpr *E : Stack->getLinkGlobals())
3863         Visit(E);
3864     }
3865   }
3866 };
3867 } // namespace
3868 
3869 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3870   switch (DKind) {
3871   case OMPD_parallel:
3872   case OMPD_parallel_for:
3873   case OMPD_parallel_for_simd:
3874   case OMPD_parallel_sections:
3875   case OMPD_parallel_master:
3876   case OMPD_teams:
3877   case OMPD_teams_distribute:
3878   case OMPD_teams_distribute_simd: {
3879     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3880     QualType KmpInt32PtrTy =
3881         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3882     Sema::CapturedParamNameType Params[] = {
3883         std::make_pair(".global_tid.", KmpInt32PtrTy),
3884         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3885         std::make_pair(StringRef(), QualType()) // __context with shared vars
3886     };
3887     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3888                              Params);
3889     break;
3890   }
3891   case OMPD_target_teams:
3892   case OMPD_target_parallel:
3893   case OMPD_target_parallel_for:
3894   case OMPD_target_parallel_for_simd:
3895   case OMPD_target_teams_distribute:
3896   case OMPD_target_teams_distribute_simd: {
3897     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3898     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3899     QualType KmpInt32PtrTy =
3900         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3901     QualType Args[] = {VoidPtrTy};
3902     FunctionProtoType::ExtProtoInfo EPI;
3903     EPI.Variadic = true;
3904     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3905     Sema::CapturedParamNameType Params[] = {
3906         std::make_pair(".global_tid.", KmpInt32Ty),
3907         std::make_pair(".part_id.", KmpInt32PtrTy),
3908         std::make_pair(".privates.", VoidPtrTy),
3909         std::make_pair(
3910             ".copy_fn.",
3911             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3912         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3913         std::make_pair(StringRef(), QualType()) // __context with shared vars
3914     };
3915     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3916                              Params, /*OpenMPCaptureLevel=*/0);
3917     // Mark this captured region as inlined, because we don't use outlined
3918     // function directly.
3919     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3920         AlwaysInlineAttr::CreateImplicit(
3921             Context, {}, AttributeCommonInfo::AS_Keyword,
3922             AlwaysInlineAttr::Keyword_forceinline));
3923     Sema::CapturedParamNameType ParamsTarget[] = {
3924         std::make_pair(StringRef(), QualType()) // __context with shared vars
3925     };
3926     // Start a captured region for 'target' with no implicit parameters.
3927     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3928                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3929     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3930         std::make_pair(".global_tid.", KmpInt32PtrTy),
3931         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3932         std::make_pair(StringRef(), QualType()) // __context with shared vars
3933     };
3934     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3935     // the same implicit parameters.
3936     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3937                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3938     break;
3939   }
3940   case OMPD_target:
3941   case OMPD_target_simd: {
3942     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3943     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3944     QualType KmpInt32PtrTy =
3945         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3946     QualType Args[] = {VoidPtrTy};
3947     FunctionProtoType::ExtProtoInfo EPI;
3948     EPI.Variadic = true;
3949     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3950     Sema::CapturedParamNameType Params[] = {
3951         std::make_pair(".global_tid.", KmpInt32Ty),
3952         std::make_pair(".part_id.", KmpInt32PtrTy),
3953         std::make_pair(".privates.", VoidPtrTy),
3954         std::make_pair(
3955             ".copy_fn.",
3956             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3957         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3958         std::make_pair(StringRef(), QualType()) // __context with shared vars
3959     };
3960     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3961                              Params, /*OpenMPCaptureLevel=*/0);
3962     // Mark this captured region as inlined, because we don't use outlined
3963     // function directly.
3964     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3965         AlwaysInlineAttr::CreateImplicit(
3966             Context, {}, AttributeCommonInfo::AS_Keyword,
3967             AlwaysInlineAttr::Keyword_forceinline));
3968     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3969                              std::make_pair(StringRef(), QualType()),
3970                              /*OpenMPCaptureLevel=*/1);
3971     break;
3972   }
3973   case OMPD_atomic:
3974   case OMPD_critical:
3975   case OMPD_section:
3976   case OMPD_master:
3977   case OMPD_masked:
3978   case OMPD_tile:
3979     break;
3980   case OMPD_simd:
3981   case OMPD_for:
3982   case OMPD_for_simd:
3983   case OMPD_sections:
3984   case OMPD_single:
3985   case OMPD_taskgroup:
3986   case OMPD_distribute:
3987   case OMPD_distribute_simd:
3988   case OMPD_ordered:
3989   case OMPD_target_data:
3990   case OMPD_dispatch: {
3991     Sema::CapturedParamNameType Params[] = {
3992         std::make_pair(StringRef(), QualType()) // __context with shared vars
3993     };
3994     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3995                              Params);
3996     break;
3997   }
3998   case OMPD_task: {
3999     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4000     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4001     QualType KmpInt32PtrTy =
4002         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4003     QualType Args[] = {VoidPtrTy};
4004     FunctionProtoType::ExtProtoInfo EPI;
4005     EPI.Variadic = true;
4006     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4007     Sema::CapturedParamNameType Params[] = {
4008         std::make_pair(".global_tid.", KmpInt32Ty),
4009         std::make_pair(".part_id.", KmpInt32PtrTy),
4010         std::make_pair(".privates.", VoidPtrTy),
4011         std::make_pair(
4012             ".copy_fn.",
4013             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4014         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4015         std::make_pair(StringRef(), QualType()) // __context with shared vars
4016     };
4017     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4018                              Params);
4019     // Mark this captured region as inlined, because we don't use outlined
4020     // function directly.
4021     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4022         AlwaysInlineAttr::CreateImplicit(
4023             Context, {}, AttributeCommonInfo::AS_Keyword,
4024             AlwaysInlineAttr::Keyword_forceinline));
4025     break;
4026   }
4027   case OMPD_taskloop:
4028   case OMPD_taskloop_simd:
4029   case OMPD_master_taskloop:
4030   case OMPD_master_taskloop_simd: {
4031     QualType KmpInt32Ty =
4032         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4033             .withConst();
4034     QualType KmpUInt64Ty =
4035         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4036             .withConst();
4037     QualType KmpInt64Ty =
4038         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4039             .withConst();
4040     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4041     QualType KmpInt32PtrTy =
4042         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4043     QualType Args[] = {VoidPtrTy};
4044     FunctionProtoType::ExtProtoInfo EPI;
4045     EPI.Variadic = true;
4046     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4047     Sema::CapturedParamNameType Params[] = {
4048         std::make_pair(".global_tid.", KmpInt32Ty),
4049         std::make_pair(".part_id.", KmpInt32PtrTy),
4050         std::make_pair(".privates.", VoidPtrTy),
4051         std::make_pair(
4052             ".copy_fn.",
4053             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4054         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4055         std::make_pair(".lb.", KmpUInt64Ty),
4056         std::make_pair(".ub.", KmpUInt64Ty),
4057         std::make_pair(".st.", KmpInt64Ty),
4058         std::make_pair(".liter.", KmpInt32Ty),
4059         std::make_pair(".reductions.", VoidPtrTy),
4060         std::make_pair(StringRef(), QualType()) // __context with shared vars
4061     };
4062     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4063                              Params);
4064     // Mark this captured region as inlined, because we don't use outlined
4065     // function directly.
4066     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4067         AlwaysInlineAttr::CreateImplicit(
4068             Context, {}, AttributeCommonInfo::AS_Keyword,
4069             AlwaysInlineAttr::Keyword_forceinline));
4070     break;
4071   }
4072   case OMPD_parallel_master_taskloop:
4073   case OMPD_parallel_master_taskloop_simd: {
4074     QualType KmpInt32Ty =
4075         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4076             .withConst();
4077     QualType KmpUInt64Ty =
4078         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4079             .withConst();
4080     QualType KmpInt64Ty =
4081         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4082             .withConst();
4083     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4084     QualType KmpInt32PtrTy =
4085         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4086     Sema::CapturedParamNameType ParamsParallel[] = {
4087         std::make_pair(".global_tid.", KmpInt32PtrTy),
4088         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4089         std::make_pair(StringRef(), QualType()) // __context with shared vars
4090     };
4091     // Start a captured region for 'parallel'.
4092     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4093                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4094     QualType Args[] = {VoidPtrTy};
4095     FunctionProtoType::ExtProtoInfo EPI;
4096     EPI.Variadic = true;
4097     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4098     Sema::CapturedParamNameType Params[] = {
4099         std::make_pair(".global_tid.", KmpInt32Ty),
4100         std::make_pair(".part_id.", KmpInt32PtrTy),
4101         std::make_pair(".privates.", VoidPtrTy),
4102         std::make_pair(
4103             ".copy_fn.",
4104             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4105         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4106         std::make_pair(".lb.", KmpUInt64Ty),
4107         std::make_pair(".ub.", KmpUInt64Ty),
4108         std::make_pair(".st.", KmpInt64Ty),
4109         std::make_pair(".liter.", KmpInt32Ty),
4110         std::make_pair(".reductions.", VoidPtrTy),
4111         std::make_pair(StringRef(), QualType()) // __context with shared vars
4112     };
4113     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4114                              Params, /*OpenMPCaptureLevel=*/1);
4115     // Mark this captured region as inlined, because we don't use outlined
4116     // function directly.
4117     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4118         AlwaysInlineAttr::CreateImplicit(
4119             Context, {}, AttributeCommonInfo::AS_Keyword,
4120             AlwaysInlineAttr::Keyword_forceinline));
4121     break;
4122   }
4123   case OMPD_distribute_parallel_for_simd:
4124   case OMPD_distribute_parallel_for: {
4125     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4126     QualType KmpInt32PtrTy =
4127         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4128     Sema::CapturedParamNameType Params[] = {
4129         std::make_pair(".global_tid.", KmpInt32PtrTy),
4130         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4131         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4132         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4133         std::make_pair(StringRef(), QualType()) // __context with shared vars
4134     };
4135     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4136                              Params);
4137     break;
4138   }
4139   case OMPD_target_teams_distribute_parallel_for:
4140   case OMPD_target_teams_distribute_parallel_for_simd: {
4141     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4142     QualType KmpInt32PtrTy =
4143         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4144     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4145 
4146     QualType Args[] = {VoidPtrTy};
4147     FunctionProtoType::ExtProtoInfo EPI;
4148     EPI.Variadic = true;
4149     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4150     Sema::CapturedParamNameType Params[] = {
4151         std::make_pair(".global_tid.", KmpInt32Ty),
4152         std::make_pair(".part_id.", KmpInt32PtrTy),
4153         std::make_pair(".privates.", VoidPtrTy),
4154         std::make_pair(
4155             ".copy_fn.",
4156             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4157         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4158         std::make_pair(StringRef(), QualType()) // __context with shared vars
4159     };
4160     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4161                              Params, /*OpenMPCaptureLevel=*/0);
4162     // Mark this captured region as inlined, because we don't use outlined
4163     // function directly.
4164     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4165         AlwaysInlineAttr::CreateImplicit(
4166             Context, {}, AttributeCommonInfo::AS_Keyword,
4167             AlwaysInlineAttr::Keyword_forceinline));
4168     Sema::CapturedParamNameType ParamsTarget[] = {
4169         std::make_pair(StringRef(), QualType()) // __context with shared vars
4170     };
4171     // Start a captured region for 'target' with no implicit parameters.
4172     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4173                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4174 
4175     Sema::CapturedParamNameType ParamsTeams[] = {
4176         std::make_pair(".global_tid.", KmpInt32PtrTy),
4177         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4178         std::make_pair(StringRef(), QualType()) // __context with shared vars
4179     };
4180     // Start a captured region for 'target' with no implicit parameters.
4181     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4182                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4183 
4184     Sema::CapturedParamNameType ParamsParallel[] = {
4185         std::make_pair(".global_tid.", KmpInt32PtrTy),
4186         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4187         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4188         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4189         std::make_pair(StringRef(), QualType()) // __context with shared vars
4190     };
4191     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4192     // the same implicit parameters.
4193     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4194                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4195     break;
4196   }
4197 
4198   case OMPD_teams_distribute_parallel_for:
4199   case OMPD_teams_distribute_parallel_for_simd: {
4200     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4201     QualType KmpInt32PtrTy =
4202         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4203 
4204     Sema::CapturedParamNameType ParamsTeams[] = {
4205         std::make_pair(".global_tid.", KmpInt32PtrTy),
4206         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4207         std::make_pair(StringRef(), QualType()) // __context with shared vars
4208     };
4209     // Start a captured region for 'target' with no implicit parameters.
4210     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4211                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4212 
4213     Sema::CapturedParamNameType ParamsParallel[] = {
4214         std::make_pair(".global_tid.", KmpInt32PtrTy),
4215         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4216         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4217         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4218         std::make_pair(StringRef(), QualType()) // __context with shared vars
4219     };
4220     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4221     // the same implicit parameters.
4222     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4223                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4224     break;
4225   }
4226   case OMPD_target_update:
4227   case OMPD_target_enter_data:
4228   case OMPD_target_exit_data: {
4229     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4230     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4231     QualType KmpInt32PtrTy =
4232         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4233     QualType Args[] = {VoidPtrTy};
4234     FunctionProtoType::ExtProtoInfo EPI;
4235     EPI.Variadic = true;
4236     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4237     Sema::CapturedParamNameType Params[] = {
4238         std::make_pair(".global_tid.", KmpInt32Ty),
4239         std::make_pair(".part_id.", KmpInt32PtrTy),
4240         std::make_pair(".privates.", VoidPtrTy),
4241         std::make_pair(
4242             ".copy_fn.",
4243             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4244         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4245         std::make_pair(StringRef(), QualType()) // __context with shared vars
4246     };
4247     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4248                              Params);
4249     // Mark this captured region as inlined, because we don't use outlined
4250     // function directly.
4251     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4252         AlwaysInlineAttr::CreateImplicit(
4253             Context, {}, AttributeCommonInfo::AS_Keyword,
4254             AlwaysInlineAttr::Keyword_forceinline));
4255     break;
4256   }
4257   case OMPD_threadprivate:
4258   case OMPD_allocate:
4259   case OMPD_taskyield:
4260   case OMPD_barrier:
4261   case OMPD_taskwait:
4262   case OMPD_cancellation_point:
4263   case OMPD_cancel:
4264   case OMPD_flush:
4265   case OMPD_depobj:
4266   case OMPD_scan:
4267   case OMPD_declare_reduction:
4268   case OMPD_declare_mapper:
4269   case OMPD_declare_simd:
4270   case OMPD_declare_target:
4271   case OMPD_end_declare_target:
4272   case OMPD_requires:
4273   case OMPD_declare_variant:
4274   case OMPD_begin_declare_variant:
4275   case OMPD_end_declare_variant:
4276     llvm_unreachable("OpenMP Directive is not allowed");
4277   case OMPD_unknown:
4278   default:
4279     llvm_unreachable("Unknown OpenMP directive");
4280   }
4281   DSAStack->setContext(CurContext);
4282 }
4283 
4284 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4285   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4286 }
4287 
4288 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4289   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4290   getOpenMPCaptureRegions(CaptureRegions, DKind);
4291   return CaptureRegions.size();
4292 }
4293 
4294 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4295                                              Expr *CaptureExpr, bool WithInit,
4296                                              bool AsExpression) {
4297   assert(CaptureExpr);
4298   ASTContext &C = S.getASTContext();
4299   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4300   QualType Ty = Init->getType();
4301   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4302     if (S.getLangOpts().CPlusPlus) {
4303       Ty = C.getLValueReferenceType(Ty);
4304     } else {
4305       Ty = C.getPointerType(Ty);
4306       ExprResult Res =
4307           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4308       if (!Res.isUsable())
4309         return nullptr;
4310       Init = Res.get();
4311     }
4312     WithInit = true;
4313   }
4314   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4315                                           CaptureExpr->getBeginLoc());
4316   if (!WithInit)
4317     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4318   S.CurContext->addHiddenDecl(CED);
4319   Sema::TentativeAnalysisScope Trap(S);
4320   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4321   return CED;
4322 }
4323 
4324 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4325                                  bool WithInit) {
4326   OMPCapturedExprDecl *CD;
4327   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4328     CD = cast<OMPCapturedExprDecl>(VD);
4329   else
4330     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4331                           /*AsExpression=*/false);
4332   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4333                           CaptureExpr->getExprLoc());
4334 }
4335 
4336 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4337   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4338   if (!Ref) {
4339     OMPCapturedExprDecl *CD = buildCaptureDecl(
4340         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4341         /*WithInit=*/true, /*AsExpression=*/true);
4342     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4343                            CaptureExpr->getExprLoc());
4344   }
4345   ExprResult Res = Ref;
4346   if (!S.getLangOpts().CPlusPlus &&
4347       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4348       Ref->getType()->isPointerType()) {
4349     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4350     if (!Res.isUsable())
4351       return ExprError();
4352   }
4353   return S.DefaultLvalueConversion(Res.get());
4354 }
4355 
4356 namespace {
4357 // OpenMP directives parsed in this section are represented as a
4358 // CapturedStatement with an associated statement.  If a syntax error
4359 // is detected during the parsing of the associated statement, the
4360 // compiler must abort processing and close the CapturedStatement.
4361 //
4362 // Combined directives such as 'target parallel' have more than one
4363 // nested CapturedStatements.  This RAII ensures that we unwind out
4364 // of all the nested CapturedStatements when an error is found.
4365 class CaptureRegionUnwinderRAII {
4366 private:
4367   Sema &S;
4368   bool &ErrorFound;
4369   OpenMPDirectiveKind DKind = OMPD_unknown;
4370 
4371 public:
4372   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4373                             OpenMPDirectiveKind DKind)
4374       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4375   ~CaptureRegionUnwinderRAII() {
4376     if (ErrorFound) {
4377       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4378       while (--ThisCaptureLevel >= 0)
4379         S.ActOnCapturedRegionError();
4380     }
4381   }
4382 };
4383 } // namespace
4384 
4385 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4386   // Capture variables captured by reference in lambdas for target-based
4387   // directives.
4388   if (!CurContext->isDependentContext() &&
4389       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4390        isOpenMPTargetDataManagementDirective(
4391            DSAStack->getCurrentDirective()))) {
4392     QualType Type = V->getType();
4393     if (const auto *RD = Type.getCanonicalType()
4394                              .getNonReferenceType()
4395                              ->getAsCXXRecordDecl()) {
4396       bool SavedForceCaptureByReferenceInTargetExecutable =
4397           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4398       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4399           /*V=*/true);
4400       if (RD->isLambda()) {
4401         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4402         FieldDecl *ThisCapture;
4403         RD->getCaptureFields(Captures, ThisCapture);
4404         for (const LambdaCapture &LC : RD->captures()) {
4405           if (LC.getCaptureKind() == LCK_ByRef) {
4406             VarDecl *VD = LC.getCapturedVar();
4407             DeclContext *VDC = VD->getDeclContext();
4408             if (!VDC->Encloses(CurContext))
4409               continue;
4410             MarkVariableReferenced(LC.getLocation(), VD);
4411           } else if (LC.getCaptureKind() == LCK_This) {
4412             QualType ThisTy = getCurrentThisType();
4413             if (!ThisTy.isNull() &&
4414                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4415               CheckCXXThisCapture(LC.getLocation());
4416           }
4417         }
4418       }
4419       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4420           SavedForceCaptureByReferenceInTargetExecutable);
4421     }
4422   }
4423 }
4424 
4425 static bool checkOrderedOrderSpecified(Sema &S,
4426                                        const ArrayRef<OMPClause *> Clauses) {
4427   const OMPOrderedClause *Ordered = nullptr;
4428   const OMPOrderClause *Order = nullptr;
4429 
4430   for (const OMPClause *Clause : Clauses) {
4431     if (Clause->getClauseKind() == OMPC_ordered)
4432       Ordered = cast<OMPOrderedClause>(Clause);
4433     else if (Clause->getClauseKind() == OMPC_order) {
4434       Order = cast<OMPOrderClause>(Clause);
4435       if (Order->getKind() != OMPC_ORDER_concurrent)
4436         Order = nullptr;
4437     }
4438     if (Ordered && Order)
4439       break;
4440   }
4441 
4442   if (Ordered && Order) {
4443     S.Diag(Order->getKindKwLoc(),
4444            diag::err_omp_simple_clause_incompatible_with_ordered)
4445         << getOpenMPClauseName(OMPC_order)
4446         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4447         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4448     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4449         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4450     return true;
4451   }
4452   return false;
4453 }
4454 
4455 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4456                                       ArrayRef<OMPClause *> Clauses) {
4457   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4458       DSAStack->getCurrentDirective() == OMPD_critical ||
4459       DSAStack->getCurrentDirective() == OMPD_section ||
4460       DSAStack->getCurrentDirective() == OMPD_master ||
4461       DSAStack->getCurrentDirective() == OMPD_masked)
4462     return S;
4463 
4464   bool ErrorFound = false;
4465   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4466       *this, ErrorFound, DSAStack->getCurrentDirective());
4467   if (!S.isUsable()) {
4468     ErrorFound = true;
4469     return StmtError();
4470   }
4471 
4472   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4473   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4474   OMPOrderedClause *OC = nullptr;
4475   OMPScheduleClause *SC = nullptr;
4476   SmallVector<const OMPLinearClause *, 4> LCs;
4477   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4478   // This is required for proper codegen.
4479   for (OMPClause *Clause : Clauses) {
4480     if (!LangOpts.OpenMPSimd &&
4481         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4482         Clause->getClauseKind() == OMPC_in_reduction) {
4483       // Capture taskgroup task_reduction descriptors inside the tasking regions
4484       // with the corresponding in_reduction items.
4485       auto *IRC = cast<OMPInReductionClause>(Clause);
4486       for (Expr *E : IRC->taskgroup_descriptors())
4487         if (E)
4488           MarkDeclarationsReferencedInExpr(E);
4489     }
4490     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4491         Clause->getClauseKind() == OMPC_copyprivate ||
4492         (getLangOpts().OpenMPUseTLS &&
4493          getASTContext().getTargetInfo().isTLSSupported() &&
4494          Clause->getClauseKind() == OMPC_copyin)) {
4495       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4496       // Mark all variables in private list clauses as used in inner region.
4497       for (Stmt *VarRef : Clause->children()) {
4498         if (auto *E = cast_or_null<Expr>(VarRef)) {
4499           MarkDeclarationsReferencedInExpr(E);
4500         }
4501       }
4502       DSAStack->setForceVarCapturing(/*V=*/false);
4503     } else if (isOpenMPLoopTransformationDirective(
4504                    DSAStack->getCurrentDirective())) {
4505       assert(CaptureRegions.empty() &&
4506              "No captured regions in loop transformation directives.");
4507     } else if (CaptureRegions.size() > 1 ||
4508                CaptureRegions.back() != OMPD_unknown) {
4509       if (auto *C = OMPClauseWithPreInit::get(Clause))
4510         PICs.push_back(C);
4511       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4512         if (Expr *E = C->getPostUpdateExpr())
4513           MarkDeclarationsReferencedInExpr(E);
4514       }
4515     }
4516     if (Clause->getClauseKind() == OMPC_schedule)
4517       SC = cast<OMPScheduleClause>(Clause);
4518     else if (Clause->getClauseKind() == OMPC_ordered)
4519       OC = cast<OMPOrderedClause>(Clause);
4520     else if (Clause->getClauseKind() == OMPC_linear)
4521       LCs.push_back(cast<OMPLinearClause>(Clause));
4522   }
4523   // Capture allocator expressions if used.
4524   for (Expr *E : DSAStack->getInnerAllocators())
4525     MarkDeclarationsReferencedInExpr(E);
4526   // OpenMP, 2.7.1 Loop Construct, Restrictions
4527   // The nonmonotonic modifier cannot be specified if an ordered clause is
4528   // specified.
4529   if (SC &&
4530       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4531        SC->getSecondScheduleModifier() ==
4532            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4533       OC) {
4534     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4535              ? SC->getFirstScheduleModifierLoc()
4536              : SC->getSecondScheduleModifierLoc(),
4537          diag::err_omp_simple_clause_incompatible_with_ordered)
4538         << getOpenMPClauseName(OMPC_schedule)
4539         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4540                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4541         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4542     ErrorFound = true;
4543   }
4544   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4545   // If an order(concurrent) clause is present, an ordered clause may not appear
4546   // on the same directive.
4547   if (checkOrderedOrderSpecified(*this, Clauses))
4548     ErrorFound = true;
4549   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4550     for (const OMPLinearClause *C : LCs) {
4551       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4552           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4553     }
4554     ErrorFound = true;
4555   }
4556   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4557       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4558       OC->getNumForLoops()) {
4559     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4560         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4561     ErrorFound = true;
4562   }
4563   if (ErrorFound) {
4564     return StmtError();
4565   }
4566   StmtResult SR = S;
4567   unsigned CompletedRegions = 0;
4568   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4569     // Mark all variables in private list clauses as used in inner region.
4570     // Required for proper codegen of combined directives.
4571     // TODO: add processing for other clauses.
4572     if (ThisCaptureRegion != OMPD_unknown) {
4573       for (const clang::OMPClauseWithPreInit *C : PICs) {
4574         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4575         // Find the particular capture region for the clause if the
4576         // directive is a combined one with multiple capture regions.
4577         // If the directive is not a combined one, the capture region
4578         // associated with the clause is OMPD_unknown and is generated
4579         // only once.
4580         if (CaptureRegion == ThisCaptureRegion ||
4581             CaptureRegion == OMPD_unknown) {
4582           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4583             for (Decl *D : DS->decls())
4584               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4585           }
4586         }
4587       }
4588     }
4589     if (ThisCaptureRegion == OMPD_target) {
4590       // Capture allocator traits in the target region. They are used implicitly
4591       // and, thus, are not captured by default.
4592       for (OMPClause *C : Clauses) {
4593         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4594           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4595                ++I) {
4596             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4597             if (Expr *E = D.AllocatorTraits)
4598               MarkDeclarationsReferencedInExpr(E);
4599           }
4600           continue;
4601         }
4602       }
4603     }
4604     if (ThisCaptureRegion == OMPD_parallel) {
4605       // Capture temp arrays for inscan reductions.
4606       for (OMPClause *C : Clauses) {
4607         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4608           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4609             continue;
4610           for (Expr *E : RC->copy_array_temps())
4611             MarkDeclarationsReferencedInExpr(E);
4612         }
4613       }
4614     }
4615     if (++CompletedRegions == CaptureRegions.size())
4616       DSAStack->setBodyComplete();
4617     SR = ActOnCapturedRegionEnd(SR.get());
4618   }
4619   return SR;
4620 }
4621 
4622 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4623                               OpenMPDirectiveKind CancelRegion,
4624                               SourceLocation StartLoc) {
4625   // CancelRegion is only needed for cancel and cancellation_point.
4626   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4627     return false;
4628 
4629   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4630       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4631     return false;
4632 
4633   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4634       << getOpenMPDirectiveName(CancelRegion);
4635   return true;
4636 }
4637 
4638 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4639                                   OpenMPDirectiveKind CurrentRegion,
4640                                   const DeclarationNameInfo &CurrentName,
4641                                   OpenMPDirectiveKind CancelRegion,
4642                                   SourceLocation StartLoc) {
4643   if (Stack->getCurScope()) {
4644     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4645     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4646     bool NestingProhibited = false;
4647     bool CloseNesting = true;
4648     bool OrphanSeen = false;
4649     enum {
4650       NoRecommend,
4651       ShouldBeInParallelRegion,
4652       ShouldBeInOrderedRegion,
4653       ShouldBeInTargetRegion,
4654       ShouldBeInTeamsRegion,
4655       ShouldBeInLoopSimdRegion,
4656     } Recommend = NoRecommend;
4657     if (isOpenMPSimdDirective(ParentRegion) &&
4658         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4659          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4660           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4661           CurrentRegion != OMPD_scan))) {
4662       // OpenMP [2.16, Nesting of Regions]
4663       // OpenMP constructs may not be nested inside a simd region.
4664       // OpenMP [2.8.1,simd Construct, Restrictions]
4665       // An ordered construct with the simd clause is the only OpenMP
4666       // construct that can appear in the simd region.
4667       // Allowing a SIMD construct nested in another SIMD construct is an
4668       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4669       // message.
4670       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4671       // The only OpenMP constructs that can be encountered during execution of
4672       // a simd region are the atomic construct, the loop construct, the simd
4673       // construct and the ordered construct with the simd clause.
4674       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4675                                  ? diag::err_omp_prohibited_region_simd
4676                                  : diag::warn_omp_nesting_simd)
4677           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4678       return CurrentRegion != OMPD_simd;
4679     }
4680     if (ParentRegion == OMPD_atomic) {
4681       // OpenMP [2.16, Nesting of Regions]
4682       // OpenMP constructs may not be nested inside an atomic region.
4683       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4684       return true;
4685     }
4686     if (CurrentRegion == OMPD_section) {
4687       // OpenMP [2.7.2, sections Construct, Restrictions]
4688       // Orphaned section directives are prohibited. That is, the section
4689       // directives must appear within the sections construct and must not be
4690       // encountered elsewhere in the sections region.
4691       if (ParentRegion != OMPD_sections &&
4692           ParentRegion != OMPD_parallel_sections) {
4693         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4694             << (ParentRegion != OMPD_unknown)
4695             << getOpenMPDirectiveName(ParentRegion);
4696         return true;
4697       }
4698       return false;
4699     }
4700     // Allow some constructs (except teams and cancellation constructs) to be
4701     // orphaned (they could be used in functions, called from OpenMP regions
4702     // with the required preconditions).
4703     if (ParentRegion == OMPD_unknown &&
4704         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4705         CurrentRegion != OMPD_cancellation_point &&
4706         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4707       return false;
4708     if (CurrentRegion == OMPD_cancellation_point ||
4709         CurrentRegion == OMPD_cancel) {
4710       // OpenMP [2.16, Nesting of Regions]
4711       // A cancellation point construct for which construct-type-clause is
4712       // taskgroup must be nested inside a task construct. A cancellation
4713       // point construct for which construct-type-clause is not taskgroup must
4714       // be closely nested inside an OpenMP construct that matches the type
4715       // specified in construct-type-clause.
4716       // A cancel construct for which construct-type-clause is taskgroup must be
4717       // nested inside a task construct. A cancel construct for which
4718       // construct-type-clause is not taskgroup must be closely nested inside an
4719       // OpenMP construct that matches the type specified in
4720       // construct-type-clause.
4721       NestingProhibited =
4722           !((CancelRegion == OMPD_parallel &&
4723              (ParentRegion == OMPD_parallel ||
4724               ParentRegion == OMPD_target_parallel)) ||
4725             (CancelRegion == OMPD_for &&
4726              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4727               ParentRegion == OMPD_target_parallel_for ||
4728               ParentRegion == OMPD_distribute_parallel_for ||
4729               ParentRegion == OMPD_teams_distribute_parallel_for ||
4730               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4731             (CancelRegion == OMPD_taskgroup &&
4732              (ParentRegion == OMPD_task ||
4733               (SemaRef.getLangOpts().OpenMP >= 50 &&
4734                (ParentRegion == OMPD_taskloop ||
4735                 ParentRegion == OMPD_master_taskloop ||
4736                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4737             (CancelRegion == OMPD_sections &&
4738              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4739               ParentRegion == OMPD_parallel_sections)));
4740       OrphanSeen = ParentRegion == OMPD_unknown;
4741     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4742       // OpenMP 5.1 [2.22, Nesting of Regions]
4743       // A masked region may not be closely nested inside a worksharing, loop,
4744       // atomic, task, or taskloop region.
4745       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4746                           isOpenMPTaskingDirective(ParentRegion);
4747     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4748       // OpenMP [2.16, Nesting of Regions]
4749       // A critical region may not be nested (closely or otherwise) inside a
4750       // critical region with the same name. Note that this restriction is not
4751       // sufficient to prevent deadlock.
4752       SourceLocation PreviousCriticalLoc;
4753       bool DeadLock = Stack->hasDirective(
4754           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4755                                               const DeclarationNameInfo &DNI,
4756                                               SourceLocation Loc) {
4757             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4758               PreviousCriticalLoc = Loc;
4759               return true;
4760             }
4761             return false;
4762           },
4763           false /* skip top directive */);
4764       if (DeadLock) {
4765         SemaRef.Diag(StartLoc,
4766                      diag::err_omp_prohibited_region_critical_same_name)
4767             << CurrentName.getName();
4768         if (PreviousCriticalLoc.isValid())
4769           SemaRef.Diag(PreviousCriticalLoc,
4770                        diag::note_omp_previous_critical_region);
4771         return true;
4772       }
4773     } else if (CurrentRegion == OMPD_barrier) {
4774       // OpenMP 5.1 [2.22, Nesting of Regions]
4775       // A barrier region may not be closely nested inside a worksharing, loop,
4776       // task, taskloop, critical, ordered, atomic, or masked region.
4777       NestingProhibited =
4778           isOpenMPWorksharingDirective(ParentRegion) ||
4779           isOpenMPTaskingDirective(ParentRegion) ||
4780           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4781           ParentRegion == OMPD_parallel_master ||
4782           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4783     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4784                !isOpenMPParallelDirective(CurrentRegion) &&
4785                !isOpenMPTeamsDirective(CurrentRegion)) {
4786       // OpenMP 5.1 [2.22, Nesting of Regions]
4787       // A loop region that binds to a parallel region or a worksharing region
4788       // may not be closely nested inside a worksharing, loop, task, taskloop,
4789       // critical, ordered, atomic, or masked region.
4790       NestingProhibited =
4791           isOpenMPWorksharingDirective(ParentRegion) ||
4792           isOpenMPTaskingDirective(ParentRegion) ||
4793           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4794           ParentRegion == OMPD_parallel_master ||
4795           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4796       Recommend = ShouldBeInParallelRegion;
4797     } else if (CurrentRegion == OMPD_ordered) {
4798       // OpenMP [2.16, Nesting of Regions]
4799       // An ordered region may not be closely nested inside a critical,
4800       // atomic, or explicit task region.
4801       // An ordered region must be closely nested inside a loop region (or
4802       // parallel loop region) with an ordered clause.
4803       // OpenMP [2.8.1,simd Construct, Restrictions]
4804       // An ordered construct with the simd clause is the only OpenMP construct
4805       // that can appear in the simd region.
4806       NestingProhibited = ParentRegion == OMPD_critical ||
4807                           isOpenMPTaskingDirective(ParentRegion) ||
4808                           !(isOpenMPSimdDirective(ParentRegion) ||
4809                             Stack->isParentOrderedRegion());
4810       Recommend = ShouldBeInOrderedRegion;
4811     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4812       // OpenMP [2.16, Nesting of Regions]
4813       // If specified, a teams construct must be contained within a target
4814       // construct.
4815       NestingProhibited =
4816           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4817           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4818            ParentRegion != OMPD_target);
4819       OrphanSeen = ParentRegion == OMPD_unknown;
4820       Recommend = ShouldBeInTargetRegion;
4821     } else if (CurrentRegion == OMPD_scan) {
4822       // OpenMP [2.16, Nesting of Regions]
4823       // If specified, a teams construct must be contained within a target
4824       // construct.
4825       NestingProhibited =
4826           SemaRef.LangOpts.OpenMP < 50 ||
4827           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4828            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4829            ParentRegion != OMPD_parallel_for_simd);
4830       OrphanSeen = ParentRegion == OMPD_unknown;
4831       Recommend = ShouldBeInLoopSimdRegion;
4832     }
4833     if (!NestingProhibited &&
4834         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4835         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4836         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4837       // OpenMP [2.16, Nesting of Regions]
4838       // distribute, parallel, parallel sections, parallel workshare, and the
4839       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4840       // constructs that can be closely nested in the teams region.
4841       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4842                           !isOpenMPDistributeDirective(CurrentRegion);
4843       Recommend = ShouldBeInParallelRegion;
4844     }
4845     if (!NestingProhibited &&
4846         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4847       // OpenMP 4.5 [2.17 Nesting of Regions]
4848       // The region associated with the distribute construct must be strictly
4849       // nested inside a teams region
4850       NestingProhibited =
4851           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4852       Recommend = ShouldBeInTeamsRegion;
4853     }
4854     if (!NestingProhibited &&
4855         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4856          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4857       // OpenMP 4.5 [2.17 Nesting of Regions]
4858       // If a target, target update, target data, target enter data, or
4859       // target exit data construct is encountered during execution of a
4860       // target region, the behavior is unspecified.
4861       NestingProhibited = Stack->hasDirective(
4862           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4863                              SourceLocation) {
4864             if (isOpenMPTargetExecutionDirective(K)) {
4865               OffendingRegion = K;
4866               return true;
4867             }
4868             return false;
4869           },
4870           false /* don't skip top directive */);
4871       CloseNesting = false;
4872     }
4873     if (NestingProhibited) {
4874       if (OrphanSeen) {
4875         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4876             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4877       } else {
4878         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4879             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4880             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4881       }
4882       return true;
4883     }
4884   }
4885   return false;
4886 }
4887 
4888 struct Kind2Unsigned {
4889   using argument_type = OpenMPDirectiveKind;
4890   unsigned operator()(argument_type DK) { return unsigned(DK); }
4891 };
4892 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4893                            ArrayRef<OMPClause *> Clauses,
4894                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4895   bool ErrorFound = false;
4896   unsigned NamedModifiersNumber = 0;
4897   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4898   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4899   SmallVector<SourceLocation, 4> NameModifierLoc;
4900   for (const OMPClause *C : Clauses) {
4901     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4902       // At most one if clause without a directive-name-modifier can appear on
4903       // the directive.
4904       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4905       if (FoundNameModifiers[CurNM]) {
4906         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4907             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4908             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4909         ErrorFound = true;
4910       } else if (CurNM != OMPD_unknown) {
4911         NameModifierLoc.push_back(IC->getNameModifierLoc());
4912         ++NamedModifiersNumber;
4913       }
4914       FoundNameModifiers[CurNM] = IC;
4915       if (CurNM == OMPD_unknown)
4916         continue;
4917       // Check if the specified name modifier is allowed for the current
4918       // directive.
4919       // At most one if clause with the particular directive-name-modifier can
4920       // appear on the directive.
4921       bool MatchFound = false;
4922       for (auto NM : AllowedNameModifiers) {
4923         if (CurNM == NM) {
4924           MatchFound = true;
4925           break;
4926         }
4927       }
4928       if (!MatchFound) {
4929         S.Diag(IC->getNameModifierLoc(),
4930                diag::err_omp_wrong_if_directive_name_modifier)
4931             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4932         ErrorFound = true;
4933       }
4934     }
4935   }
4936   // If any if clause on the directive includes a directive-name-modifier then
4937   // all if clauses on the directive must include a directive-name-modifier.
4938   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4939     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4940       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4941              diag::err_omp_no_more_if_clause);
4942     } else {
4943       std::string Values;
4944       std::string Sep(", ");
4945       unsigned AllowedCnt = 0;
4946       unsigned TotalAllowedNum =
4947           AllowedNameModifiers.size() - NamedModifiersNumber;
4948       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4949            ++Cnt) {
4950         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4951         if (!FoundNameModifiers[NM]) {
4952           Values += "'";
4953           Values += getOpenMPDirectiveName(NM);
4954           Values += "'";
4955           if (AllowedCnt + 2 == TotalAllowedNum)
4956             Values += " or ";
4957           else if (AllowedCnt + 1 != TotalAllowedNum)
4958             Values += Sep;
4959           ++AllowedCnt;
4960         }
4961       }
4962       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4963              diag::err_omp_unnamed_if_clause)
4964           << (TotalAllowedNum > 1) << Values;
4965     }
4966     for (SourceLocation Loc : NameModifierLoc) {
4967       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4968     }
4969     ErrorFound = true;
4970   }
4971   return ErrorFound;
4972 }
4973 
4974 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4975                                                    SourceLocation &ELoc,
4976                                                    SourceRange &ERange,
4977                                                    bool AllowArraySection) {
4978   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4979       RefExpr->containsUnexpandedParameterPack())
4980     return std::make_pair(nullptr, true);
4981 
4982   // OpenMP [3.1, C/C++]
4983   //  A list item is a variable name.
4984   // OpenMP  [2.9.3.3, Restrictions, p.1]
4985   //  A variable that is part of another variable (as an array or
4986   //  structure element) cannot appear in a private clause.
4987   RefExpr = RefExpr->IgnoreParens();
4988   enum {
4989     NoArrayExpr = -1,
4990     ArraySubscript = 0,
4991     OMPArraySection = 1
4992   } IsArrayExpr = NoArrayExpr;
4993   if (AllowArraySection) {
4994     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4995       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4996       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4997         Base = TempASE->getBase()->IgnoreParenImpCasts();
4998       RefExpr = Base;
4999       IsArrayExpr = ArraySubscript;
5000     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5001       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5002       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5003         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5004       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5005         Base = TempASE->getBase()->IgnoreParenImpCasts();
5006       RefExpr = Base;
5007       IsArrayExpr = OMPArraySection;
5008     }
5009   }
5010   ELoc = RefExpr->getExprLoc();
5011   ERange = RefExpr->getSourceRange();
5012   RefExpr = RefExpr->IgnoreParenImpCasts();
5013   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5014   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5015   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5016       (S.getCurrentThisType().isNull() || !ME ||
5017        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5018        !isa<FieldDecl>(ME->getMemberDecl()))) {
5019     if (IsArrayExpr != NoArrayExpr) {
5020       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
5021                                                          << ERange;
5022     } else {
5023       S.Diag(ELoc,
5024              AllowArraySection
5025                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5026                  : diag::err_omp_expected_var_name_member_expr)
5027           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5028     }
5029     return std::make_pair(nullptr, false);
5030   }
5031   return std::make_pair(
5032       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5033 }
5034 
5035 namespace {
5036 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5037 /// target regions.
5038 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5039   DSAStackTy *S = nullptr;
5040 
5041 public:
5042   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5043     return S->isUsesAllocatorsDecl(E->getDecl())
5044                .getValueOr(
5045                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5046            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5047   }
5048   bool VisitStmt(const Stmt *S) {
5049     for (const Stmt *Child : S->children()) {
5050       if (Child && Visit(Child))
5051         return true;
5052     }
5053     return false;
5054   }
5055   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5056 };
5057 } // namespace
5058 
5059 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5060                                  ArrayRef<OMPClause *> Clauses) {
5061   assert(!S.CurContext->isDependentContext() &&
5062          "Expected non-dependent context.");
5063   auto AllocateRange =
5064       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5065   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
5066       DeclToCopy;
5067   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5068     return isOpenMPPrivate(C->getClauseKind());
5069   });
5070   for (OMPClause *Cl : PrivateRange) {
5071     MutableArrayRef<Expr *>::iterator I, It, Et;
5072     if (Cl->getClauseKind() == OMPC_private) {
5073       auto *PC = cast<OMPPrivateClause>(Cl);
5074       I = PC->private_copies().begin();
5075       It = PC->varlist_begin();
5076       Et = PC->varlist_end();
5077     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5078       auto *PC = cast<OMPFirstprivateClause>(Cl);
5079       I = PC->private_copies().begin();
5080       It = PC->varlist_begin();
5081       Et = PC->varlist_end();
5082     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5083       auto *PC = cast<OMPLastprivateClause>(Cl);
5084       I = PC->private_copies().begin();
5085       It = PC->varlist_begin();
5086       Et = PC->varlist_end();
5087     } else if (Cl->getClauseKind() == OMPC_linear) {
5088       auto *PC = cast<OMPLinearClause>(Cl);
5089       I = PC->privates().begin();
5090       It = PC->varlist_begin();
5091       Et = PC->varlist_end();
5092     } else if (Cl->getClauseKind() == OMPC_reduction) {
5093       auto *PC = cast<OMPReductionClause>(Cl);
5094       I = PC->privates().begin();
5095       It = PC->varlist_begin();
5096       Et = PC->varlist_end();
5097     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5098       auto *PC = cast<OMPTaskReductionClause>(Cl);
5099       I = PC->privates().begin();
5100       It = PC->varlist_begin();
5101       Et = PC->varlist_end();
5102     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5103       auto *PC = cast<OMPInReductionClause>(Cl);
5104       I = PC->privates().begin();
5105       It = PC->varlist_begin();
5106       Et = PC->varlist_end();
5107     } else {
5108       llvm_unreachable("Expected private clause.");
5109     }
5110     for (Expr *E : llvm::make_range(It, Et)) {
5111       if (!*I) {
5112         ++I;
5113         continue;
5114       }
5115       SourceLocation ELoc;
5116       SourceRange ERange;
5117       Expr *SimpleRefExpr = E;
5118       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5119                                 /*AllowArraySection=*/true);
5120       DeclToCopy.try_emplace(Res.first,
5121                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5122       ++I;
5123     }
5124   }
5125   for (OMPClause *C : AllocateRange) {
5126     auto *AC = cast<OMPAllocateClause>(C);
5127     if (S.getLangOpts().OpenMP >= 50 &&
5128         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5129         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5130         AC->getAllocator()) {
5131       Expr *Allocator = AC->getAllocator();
5132       // OpenMP, 2.12.5 target Construct
5133       // Memory allocators that do not appear in a uses_allocators clause cannot
5134       // appear as an allocator in an allocate clause or be used in the target
5135       // region unless a requires directive with the dynamic_allocators clause
5136       // is present in the same compilation unit.
5137       AllocatorChecker Checker(Stack);
5138       if (Checker.Visit(Allocator))
5139         S.Diag(Allocator->getExprLoc(),
5140                diag::err_omp_allocator_not_in_uses_allocators)
5141             << Allocator->getSourceRange();
5142     }
5143     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5144         getAllocatorKind(S, Stack, AC->getAllocator());
5145     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5146     // For task, taskloop or target directives, allocation requests to memory
5147     // allocators with the trait access set to thread result in unspecified
5148     // behavior.
5149     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5150         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5151          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5152       S.Diag(AC->getAllocator()->getExprLoc(),
5153              diag::warn_omp_allocate_thread_on_task_target_directive)
5154           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5155     }
5156     for (Expr *E : AC->varlists()) {
5157       SourceLocation ELoc;
5158       SourceRange ERange;
5159       Expr *SimpleRefExpr = E;
5160       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5161       ValueDecl *VD = Res.first;
5162       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5163       if (!isOpenMPPrivate(Data.CKind)) {
5164         S.Diag(E->getExprLoc(),
5165                diag::err_omp_expected_private_copy_for_allocate);
5166         continue;
5167       }
5168       VarDecl *PrivateVD = DeclToCopy[VD];
5169       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5170                                             AllocatorKind, AC->getAllocator()))
5171         continue;
5172       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5173                                 E->getSourceRange());
5174     }
5175   }
5176 }
5177 
5178 namespace {
5179 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5180 ///
5181 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5182 /// context. DeclRefExpr used inside the new context are changed to refer to the
5183 /// captured variable instead.
5184 class CaptureVars : public TreeTransform<CaptureVars> {
5185   using BaseTransform = TreeTransform<CaptureVars>;
5186 
5187 public:
5188   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5189 
5190   bool AlwaysRebuild() { return true; }
5191 };
5192 } // namespace
5193 
5194 static VarDecl *precomputeExpr(Sema &Actions,
5195                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5196                                StringRef Name) {
5197   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5198   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5199                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5200   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5201       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5202   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5203   BodyStmts.push_back(NewDeclStmt);
5204   return NewVar;
5205 }
5206 
5207 /// Create a closure that computes the number of iterations of a loop.
5208 ///
5209 /// \param Actions   The Sema object.
5210 /// \param LogicalTy Type for the logical iteration number.
5211 /// \param Rel       Comparison operator of the loop condition.
5212 /// \param StartExpr Value of the loop counter at the first iteration.
5213 /// \param StopExpr  Expression the loop counter is compared against in the loop
5214 /// condition. \param StepExpr      Amount of increment after each iteration.
5215 ///
5216 /// \return Closure (CapturedStmt) of the distance calculation.
5217 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5218                                        BinaryOperator::Opcode Rel,
5219                                        Expr *StartExpr, Expr *StopExpr,
5220                                        Expr *StepExpr) {
5221   ASTContext &Ctx = Actions.getASTContext();
5222   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5223 
5224   // Captured regions currently don't support return values, we use an
5225   // out-parameter instead. All inputs are implicit captures.
5226   // TODO: Instead of capturing each DeclRefExpr occurring in
5227   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5228   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5229   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5230                                           {StringRef(), QualType()}};
5231   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5232 
5233   Stmt *Body;
5234   {
5235     Sema::CompoundScopeRAII CompoundScope(Actions);
5236     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5237 
5238     // Get the LValue expression for the result.
5239     ImplicitParamDecl *DistParam = CS->getParam(0);
5240     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5241         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5242 
5243     SmallVector<Stmt *, 4> BodyStmts;
5244 
5245     // Capture all referenced variable references.
5246     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5247     // CapturedStmt, we could compute them before and capture the result, to be
5248     // used jointly with the LoopVar function.
5249     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5250     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5251     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5252     auto BuildVarRef = [&](VarDecl *VD) {
5253       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5254     };
5255 
5256     IntegerLiteral *Zero = IntegerLiteral::Create(
5257         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5258     Expr *Dist;
5259     if (Rel == BO_NE) {
5260       // When using a != comparison, the increment can be +1 or -1. This can be
5261       // dynamic at runtime, so we need to check for the direction.
5262       Expr *IsNegStep = AssertSuccess(
5263           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5264 
5265       // Positive increment.
5266       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5267           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5268       ForwardRange = AssertSuccess(
5269           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5270       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5271           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5272 
5273       // Negative increment.
5274       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5275           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5276       BackwardRange = AssertSuccess(
5277           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5278       Expr *NegIncAmount = AssertSuccess(
5279           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5280       Expr *BackwardDist = AssertSuccess(
5281           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5282 
5283       // Use the appropriate case.
5284       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5285           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5286     } else {
5287       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5288              "Expected one of these relational operators");
5289 
5290       // We can derive the direction from any other comparison operator. It is
5291       // non well-formed OpenMP if Step increments/decrements in the other
5292       // directions. Whether at least the first iteration passes the loop
5293       // condition.
5294       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5295           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5296 
5297       // Compute the range between first and last counter value.
5298       Expr *Range;
5299       if (Rel == BO_GE || Rel == BO_GT)
5300         Range = AssertSuccess(Actions.BuildBinOp(
5301             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5302       else
5303         Range = AssertSuccess(Actions.BuildBinOp(
5304             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5305 
5306       // Ensure unsigned range space.
5307       Range =
5308           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5309 
5310       if (Rel == BO_LE || Rel == BO_GE) {
5311         // Add one to the range if the relational operator is inclusive.
5312         Range =
5313             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_PreInc, Range));
5314       }
5315 
5316       // Divide by the absolute step amount.
5317       Expr *Divisor = BuildVarRef(NewStep);
5318       if (Rel == BO_GE || Rel == BO_GT)
5319         Divisor =
5320             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5321       Dist = AssertSuccess(
5322           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5323 
5324       // If there is not at least one iteration, the range contains garbage. Fix
5325       // to zero in this case.
5326       Dist = AssertSuccess(
5327           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5328     }
5329 
5330     // Assign the result to the out-parameter.
5331     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5332         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5333     BodyStmts.push_back(ResultAssign);
5334 
5335     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5336   }
5337 
5338   return cast<CapturedStmt>(
5339       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5340 }
5341 
5342 /// Create a closure that computes the loop variable from the logical iteration
5343 /// number.
5344 ///
5345 /// \param Actions   The Sema object.
5346 /// \param LoopVarTy Type for the loop variable used for result value.
5347 /// \param LogicalTy Type for the logical iteration number.
5348 /// \param StartExpr Value of the loop counter at the first iteration.
5349 /// \param Step      Amount of increment after each iteration.
5350 /// \param Deref     Whether the loop variable is a dereference of the loop
5351 /// counter variable.
5352 ///
5353 /// \return Closure (CapturedStmt) of the loop value calculation.
5354 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5355                                       QualType LogicalTy,
5356                                       DeclRefExpr *StartExpr, Expr *Step,
5357                                       bool Deref) {
5358   ASTContext &Ctx = Actions.getASTContext();
5359 
5360   // Pass the result as an out-parameter. Passing as return value would require
5361   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5362   // invoke a copy constructor.
5363   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5364   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5365                                           {"Logical", LogicalTy},
5366                                           {StringRef(), QualType()}};
5367   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5368 
5369   // Capture the initial iterator which represents the LoopVar value at the
5370   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5371   // it in every iteration, capture it by value before it is modified.
5372   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5373   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5374                                             Sema::TryCapture_ExplicitByVal, {});
5375   (void)Invalid;
5376   assert(!Invalid && "Expecting capture-by-value to work.");
5377 
5378   Expr *Body;
5379   {
5380     Sema::CompoundScopeRAII CompoundScope(Actions);
5381     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5382 
5383     ImplicitParamDecl *TargetParam = CS->getParam(0);
5384     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5385         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5386     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5387     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5388         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5389 
5390     // Capture the Start expression.
5391     CaptureVars Recap(Actions);
5392     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5393     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5394 
5395     Expr *Skip = AssertSuccess(
5396         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5397     // TODO: Explicitly cast to the iterator's difference_type instead of
5398     // relying on implicit conversion.
5399     Expr *Advanced =
5400         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5401 
5402     if (Deref) {
5403       // For range-based for-loops convert the loop counter value to a concrete
5404       // loop variable value by dereferencing the iterator.
5405       Advanced =
5406           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5407     }
5408 
5409     // Assign the result to the output parameter.
5410     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5411                                             BO_Assign, TargetRef, Advanced));
5412   }
5413   return cast<CapturedStmt>(
5414       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5415 }
5416 
5417 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5418   ASTContext &Ctx = getASTContext();
5419 
5420   // Extract the common elements of ForStmt and CXXForRangeStmt:
5421   // Loop variable, repeat condition, increment
5422   Expr *Cond, *Inc;
5423   VarDecl *LIVDecl, *LUVDecl;
5424   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5425     Stmt *Init = For->getInit();
5426     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5427       // For statement declares loop variable.
5428       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5429     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5430       // For statement reuses variable.
5431       assert(LCAssign->getOpcode() == BO_Assign &&
5432              "init part must be a loop variable assignment");
5433       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5434       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5435     } else
5436       llvm_unreachable("Cannot determine loop variable");
5437     LUVDecl = LIVDecl;
5438 
5439     Cond = For->getCond();
5440     Inc = For->getInc();
5441   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5442     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5443     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5444     LUVDecl = RangeFor->getLoopVariable();
5445 
5446     Cond = RangeFor->getCond();
5447     Inc = RangeFor->getInc();
5448   } else
5449     llvm_unreachable("unhandled kind of loop");
5450 
5451   QualType CounterTy = LIVDecl->getType();
5452   QualType LVTy = LUVDecl->getType();
5453 
5454   // Analyze the loop condition.
5455   Expr *LHS, *RHS;
5456   BinaryOperator::Opcode CondRel;
5457   Cond = Cond->IgnoreImplicit();
5458   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5459     LHS = CondBinExpr->getLHS();
5460     RHS = CondBinExpr->getRHS();
5461     CondRel = CondBinExpr->getOpcode();
5462   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5463     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5464     LHS = CondCXXOp->getArg(0);
5465     RHS = CondCXXOp->getArg(1);
5466     switch (CondCXXOp->getOperator()) {
5467     case OO_ExclaimEqual:
5468       CondRel = BO_NE;
5469       break;
5470     case OO_Less:
5471       CondRel = BO_LT;
5472       break;
5473     case OO_LessEqual:
5474       CondRel = BO_LE;
5475       break;
5476     case OO_Greater:
5477       CondRel = BO_GT;
5478       break;
5479     case OO_GreaterEqual:
5480       CondRel = BO_GE;
5481       break;
5482     default:
5483       llvm_unreachable("unexpected iterator operator");
5484     }
5485   } else
5486     llvm_unreachable("unexpected loop condition");
5487 
5488   // Normalize such that the loop counter is on the LHS.
5489   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5490       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5491     std::swap(LHS, RHS);
5492     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5493   }
5494   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5495 
5496   // Decide the bit width for the logical iteration counter. By default use the
5497   // unsigned ptrdiff_t integer size (for iterators and pointers).
5498   // TODO: For iterators, use iterator::difference_type,
5499   // std::iterator_traits<>::difference_type or decltype(it - end).
5500   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5501   if (CounterTy->isIntegerType()) {
5502     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5503     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5504   }
5505 
5506   // Analyze the loop increment.
5507   Expr *Step;
5508   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5509     int Direction;
5510     switch (IncUn->getOpcode()) {
5511     case UO_PreInc:
5512     case UO_PostInc:
5513       Direction = 1;
5514       break;
5515     case UO_PreDec:
5516     case UO_PostDec:
5517       Direction = -1;
5518       break;
5519     default:
5520       llvm_unreachable("unhandled unary increment operator");
5521     }
5522     Step = IntegerLiteral::Create(
5523         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5524   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5525     if (IncBin->getOpcode() == BO_AddAssign) {
5526       Step = IncBin->getRHS();
5527     } else if (IncBin->getOpcode() == BO_SubAssign) {
5528       Step =
5529           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5530     } else
5531       llvm_unreachable("unhandled binary increment operator");
5532   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5533     switch (CondCXXOp->getOperator()) {
5534     case OO_PlusPlus:
5535       Step = IntegerLiteral::Create(
5536           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5537       break;
5538     case OO_MinusMinus:
5539       Step = IntegerLiteral::Create(
5540           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5541       break;
5542     case OO_PlusEqual:
5543       Step = CondCXXOp->getArg(1);
5544       break;
5545     case OO_MinusEqual:
5546       Step = AssertSuccess(
5547           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5548       break;
5549     default:
5550       llvm_unreachable("unhandled overloaded increment operator");
5551     }
5552   } else
5553     llvm_unreachable("unknown increment expression");
5554 
5555   CapturedStmt *DistanceFunc =
5556       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5557   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5558       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5559   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5560                                         {}, nullptr, nullptr, {}, nullptr);
5561   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5562                                   LoopVarFunc, LVRef);
5563 }
5564 
5565 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5566                                             CXXScopeSpec &MapperIdScopeSpec,
5567                                             const DeclarationNameInfo &MapperId,
5568                                             QualType Type,
5569                                             Expr *UnresolvedMapper);
5570 
5571 /// Perform DFS through the structure/class data members trying to find
5572 /// member(s) with user-defined 'default' mapper and generate implicit map
5573 /// clauses for such members with the found 'default' mapper.
5574 static void
5575 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5576                                       SmallVectorImpl<OMPClause *> &Clauses) {
5577   // Check for the deault mapper for data members.
5578   if (S.getLangOpts().OpenMP < 50)
5579     return;
5580   SmallVector<OMPClause *, 4> ImplicitMaps;
5581   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5582     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5583     if (!C)
5584       continue;
5585     SmallVector<Expr *, 4> SubExprs;
5586     auto *MI = C->mapperlist_begin();
5587     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5588          ++I, ++MI) {
5589       // Expression is mapped using mapper - skip it.
5590       if (*MI)
5591         continue;
5592       Expr *E = *I;
5593       // Expression is dependent - skip it, build the mapper when it gets
5594       // instantiated.
5595       if (E->isTypeDependent() || E->isValueDependent() ||
5596           E->containsUnexpandedParameterPack())
5597         continue;
5598       // Array section - need to check for the mapping of the array section
5599       // element.
5600       QualType CanonType = E->getType().getCanonicalType();
5601       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5602         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5603         QualType BaseType =
5604             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5605         QualType ElemType;
5606         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5607           ElemType = ATy->getElementType();
5608         else
5609           ElemType = BaseType->getPointeeType();
5610         CanonType = ElemType;
5611       }
5612 
5613       // DFS over data members in structures/classes.
5614       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5615           1, {CanonType, nullptr});
5616       llvm::DenseMap<const Type *, Expr *> Visited;
5617       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5618           1, {nullptr, 1});
5619       while (!Types.empty()) {
5620         QualType BaseType;
5621         FieldDecl *CurFD;
5622         std::tie(BaseType, CurFD) = Types.pop_back_val();
5623         while (ParentChain.back().second == 0)
5624           ParentChain.pop_back();
5625         --ParentChain.back().second;
5626         if (BaseType.isNull())
5627           continue;
5628         // Only structs/classes are allowed to have mappers.
5629         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5630         if (!RD)
5631           continue;
5632         auto It = Visited.find(BaseType.getTypePtr());
5633         if (It == Visited.end()) {
5634           // Try to find the associated user-defined mapper.
5635           CXXScopeSpec MapperIdScopeSpec;
5636           DeclarationNameInfo DefaultMapperId;
5637           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5638               &S.Context.Idents.get("default")));
5639           DefaultMapperId.setLoc(E->getExprLoc());
5640           ExprResult ER = buildUserDefinedMapperRef(
5641               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5642               BaseType, /*UnresolvedMapper=*/nullptr);
5643           if (ER.isInvalid())
5644             continue;
5645           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5646         }
5647         // Found default mapper.
5648         if (It->second) {
5649           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5650                                                      VK_LValue, OK_Ordinary, E);
5651           OE->setIsUnique(/*V=*/true);
5652           Expr *BaseExpr = OE;
5653           for (const auto &P : ParentChain) {
5654             if (P.first) {
5655               BaseExpr = S.BuildMemberExpr(
5656                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5657                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5658                   DeclAccessPair::make(P.first, P.first->getAccess()),
5659                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5660                   P.first->getType(), VK_LValue, OK_Ordinary);
5661               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5662             }
5663           }
5664           if (CurFD)
5665             BaseExpr = S.BuildMemberExpr(
5666                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5667                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5668                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5669                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5670                 CurFD->getType(), VK_LValue, OK_Ordinary);
5671           SubExprs.push_back(BaseExpr);
5672           continue;
5673         }
5674         // Check for the "default" mapper for data memebers.
5675         bool FirstIter = true;
5676         for (FieldDecl *FD : RD->fields()) {
5677           if (!FD)
5678             continue;
5679           QualType FieldTy = FD->getType();
5680           if (FieldTy.isNull() ||
5681               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5682             continue;
5683           if (FirstIter) {
5684             FirstIter = false;
5685             ParentChain.emplace_back(CurFD, 1);
5686           } else {
5687             ++ParentChain.back().second;
5688           }
5689           Types.emplace_back(FieldTy, FD);
5690         }
5691       }
5692     }
5693     if (SubExprs.empty())
5694       continue;
5695     CXXScopeSpec MapperIdScopeSpec;
5696     DeclarationNameInfo MapperId;
5697     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5698             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5699             MapperIdScopeSpec, MapperId, C->getMapType(),
5700             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5701             SubExprs, OMPVarListLocTy()))
5702       Clauses.push_back(NewClause);
5703   }
5704 }
5705 
5706 StmtResult Sema::ActOnOpenMPExecutableDirective(
5707     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5708     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5709     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5710   StmtResult Res = StmtError();
5711   // First check CancelRegion which is then used in checkNestingOfRegions.
5712   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5713       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5714                             StartLoc))
5715     return StmtError();
5716 
5717   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5718   VarsWithInheritedDSAType VarsWithInheritedDSA;
5719   bool ErrorFound = false;
5720   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5721   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5722       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5723       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5724     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5725 
5726     // Check default data sharing attributes for referenced variables.
5727     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5728     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5729     Stmt *S = AStmt;
5730     while (--ThisCaptureLevel >= 0)
5731       S = cast<CapturedStmt>(S)->getCapturedStmt();
5732     DSAChecker.Visit(S);
5733     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5734         !isOpenMPTaskingDirective(Kind)) {
5735       // Visit subcaptures to generate implicit clauses for captured vars.
5736       auto *CS = cast<CapturedStmt>(AStmt);
5737       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5738       getOpenMPCaptureRegions(CaptureRegions, Kind);
5739       // Ignore outer tasking regions for target directives.
5740       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5741         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5742       DSAChecker.visitSubCaptures(CS);
5743     }
5744     if (DSAChecker.isErrorFound())
5745       return StmtError();
5746     // Generate list of implicitly defined firstprivate variables.
5747     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5748 
5749     SmallVector<Expr *, 4> ImplicitFirstprivates(
5750         DSAChecker.getImplicitFirstprivate().begin(),
5751         DSAChecker.getImplicitFirstprivate().end());
5752     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5753     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5754     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5755         ImplicitMapModifiers[DefaultmapKindNum];
5756     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5757         ImplicitMapModifiersLoc[DefaultmapKindNum];
5758     // Get the original location of present modifier from Defaultmap clause.
5759     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5760     for (OMPClause *C : Clauses) {
5761       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5762         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5763           PresentModifierLocs[DMC->getDefaultmapKind()] =
5764               DMC->getDefaultmapModifierLoc();
5765     }
5766     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5767       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5768       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5769         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5770             Kind, static_cast<OpenMPMapClauseKind>(I));
5771         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5772       }
5773       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5774           DSAChecker.getImplicitMapModifier(Kind);
5775       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5776                                       ImplicitModifier.end());
5777       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5778                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5779     }
5780     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5781     for (OMPClause *C : Clauses) {
5782       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5783         for (Expr *E : IRC->taskgroup_descriptors())
5784           if (E)
5785             ImplicitFirstprivates.emplace_back(E);
5786       }
5787       // OpenMP 5.0, 2.10.1 task Construct
5788       // [detach clause]... The event-handle will be considered as if it was
5789       // specified on a firstprivate clause.
5790       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5791         ImplicitFirstprivates.push_back(DC->getEventHandler());
5792     }
5793     if (!ImplicitFirstprivates.empty()) {
5794       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5795               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5796               SourceLocation())) {
5797         ClausesWithImplicit.push_back(Implicit);
5798         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5799                      ImplicitFirstprivates.size();
5800       } else {
5801         ErrorFound = true;
5802       }
5803     }
5804     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5805       int ClauseKindCnt = -1;
5806       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5807         ++ClauseKindCnt;
5808         if (ImplicitMap.empty())
5809           continue;
5810         CXXScopeSpec MapperIdScopeSpec;
5811         DeclarationNameInfo MapperId;
5812         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5813         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5814                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5815                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5816                 SourceLocation(), SourceLocation(), ImplicitMap,
5817                 OMPVarListLocTy())) {
5818           ClausesWithImplicit.emplace_back(Implicit);
5819           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5820                         ImplicitMap.size();
5821         } else {
5822           ErrorFound = true;
5823         }
5824       }
5825     }
5826     // Build expressions for implicit maps of data members with 'default'
5827     // mappers.
5828     if (LangOpts.OpenMP >= 50)
5829       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5830                                             ClausesWithImplicit);
5831   }
5832 
5833   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5834   switch (Kind) {
5835   case OMPD_parallel:
5836     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5837                                        EndLoc);
5838     AllowedNameModifiers.push_back(OMPD_parallel);
5839     break;
5840   case OMPD_simd:
5841     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5842                                    VarsWithInheritedDSA);
5843     if (LangOpts.OpenMP >= 50)
5844       AllowedNameModifiers.push_back(OMPD_simd);
5845     break;
5846   case OMPD_tile:
5847     Res =
5848         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5849     break;
5850   case OMPD_for:
5851     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5852                                   VarsWithInheritedDSA);
5853     break;
5854   case OMPD_for_simd:
5855     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5856                                       EndLoc, VarsWithInheritedDSA);
5857     if (LangOpts.OpenMP >= 50)
5858       AllowedNameModifiers.push_back(OMPD_simd);
5859     break;
5860   case OMPD_sections:
5861     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5862                                        EndLoc);
5863     break;
5864   case OMPD_section:
5865     assert(ClausesWithImplicit.empty() &&
5866            "No clauses are allowed for 'omp section' directive");
5867     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5868     break;
5869   case OMPD_single:
5870     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5871                                      EndLoc);
5872     break;
5873   case OMPD_master:
5874     assert(ClausesWithImplicit.empty() &&
5875            "No clauses are allowed for 'omp master' directive");
5876     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5877     break;
5878   case OMPD_masked:
5879     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
5880                                      EndLoc);
5881     break;
5882   case OMPD_critical:
5883     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5884                                        StartLoc, EndLoc);
5885     break;
5886   case OMPD_parallel_for:
5887     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5888                                           EndLoc, VarsWithInheritedDSA);
5889     AllowedNameModifiers.push_back(OMPD_parallel);
5890     break;
5891   case OMPD_parallel_for_simd:
5892     Res = ActOnOpenMPParallelForSimdDirective(
5893         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5894     AllowedNameModifiers.push_back(OMPD_parallel);
5895     if (LangOpts.OpenMP >= 50)
5896       AllowedNameModifiers.push_back(OMPD_simd);
5897     break;
5898   case OMPD_parallel_master:
5899     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5900                                                StartLoc, EndLoc);
5901     AllowedNameModifiers.push_back(OMPD_parallel);
5902     break;
5903   case OMPD_parallel_sections:
5904     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5905                                                StartLoc, EndLoc);
5906     AllowedNameModifiers.push_back(OMPD_parallel);
5907     break;
5908   case OMPD_task:
5909     Res =
5910         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5911     AllowedNameModifiers.push_back(OMPD_task);
5912     break;
5913   case OMPD_taskyield:
5914     assert(ClausesWithImplicit.empty() &&
5915            "No clauses are allowed for 'omp taskyield' directive");
5916     assert(AStmt == nullptr &&
5917            "No associated statement allowed for 'omp taskyield' directive");
5918     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5919     break;
5920   case OMPD_barrier:
5921     assert(ClausesWithImplicit.empty() &&
5922            "No clauses are allowed for 'omp barrier' directive");
5923     assert(AStmt == nullptr &&
5924            "No associated statement allowed for 'omp barrier' directive");
5925     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5926     break;
5927   case OMPD_taskwait:
5928     assert(ClausesWithImplicit.empty() &&
5929            "No clauses are allowed for 'omp taskwait' directive");
5930     assert(AStmt == nullptr &&
5931            "No associated statement allowed for 'omp taskwait' directive");
5932     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5933     break;
5934   case OMPD_taskgroup:
5935     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5936                                         EndLoc);
5937     break;
5938   case OMPD_flush:
5939     assert(AStmt == nullptr &&
5940            "No associated statement allowed for 'omp flush' directive");
5941     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5942     break;
5943   case OMPD_depobj:
5944     assert(AStmt == nullptr &&
5945            "No associated statement allowed for 'omp depobj' directive");
5946     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5947     break;
5948   case OMPD_scan:
5949     assert(AStmt == nullptr &&
5950            "No associated statement allowed for 'omp scan' directive");
5951     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5952     break;
5953   case OMPD_ordered:
5954     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5955                                       EndLoc);
5956     break;
5957   case OMPD_atomic:
5958     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5959                                      EndLoc);
5960     break;
5961   case OMPD_teams:
5962     Res =
5963         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5964     break;
5965   case OMPD_target:
5966     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5967                                      EndLoc);
5968     AllowedNameModifiers.push_back(OMPD_target);
5969     break;
5970   case OMPD_target_parallel:
5971     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5972                                              StartLoc, EndLoc);
5973     AllowedNameModifiers.push_back(OMPD_target);
5974     AllowedNameModifiers.push_back(OMPD_parallel);
5975     break;
5976   case OMPD_target_parallel_for:
5977     Res = ActOnOpenMPTargetParallelForDirective(
5978         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5979     AllowedNameModifiers.push_back(OMPD_target);
5980     AllowedNameModifiers.push_back(OMPD_parallel);
5981     break;
5982   case OMPD_cancellation_point:
5983     assert(ClausesWithImplicit.empty() &&
5984            "No clauses are allowed for 'omp cancellation point' directive");
5985     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5986                                "cancellation point' directive");
5987     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5988     break;
5989   case OMPD_cancel:
5990     assert(AStmt == nullptr &&
5991            "No associated statement allowed for 'omp cancel' directive");
5992     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5993                                      CancelRegion);
5994     AllowedNameModifiers.push_back(OMPD_cancel);
5995     break;
5996   case OMPD_target_data:
5997     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5998                                          EndLoc);
5999     AllowedNameModifiers.push_back(OMPD_target_data);
6000     break;
6001   case OMPD_target_enter_data:
6002     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6003                                               EndLoc, AStmt);
6004     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6005     break;
6006   case OMPD_target_exit_data:
6007     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6008                                              EndLoc, AStmt);
6009     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6010     break;
6011   case OMPD_taskloop:
6012     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6013                                        EndLoc, VarsWithInheritedDSA);
6014     AllowedNameModifiers.push_back(OMPD_taskloop);
6015     break;
6016   case OMPD_taskloop_simd:
6017     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6018                                            EndLoc, VarsWithInheritedDSA);
6019     AllowedNameModifiers.push_back(OMPD_taskloop);
6020     if (LangOpts.OpenMP >= 50)
6021       AllowedNameModifiers.push_back(OMPD_simd);
6022     break;
6023   case OMPD_master_taskloop:
6024     Res = ActOnOpenMPMasterTaskLoopDirective(
6025         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6026     AllowedNameModifiers.push_back(OMPD_taskloop);
6027     break;
6028   case OMPD_master_taskloop_simd:
6029     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6030         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6031     AllowedNameModifiers.push_back(OMPD_taskloop);
6032     if (LangOpts.OpenMP >= 50)
6033       AllowedNameModifiers.push_back(OMPD_simd);
6034     break;
6035   case OMPD_parallel_master_taskloop:
6036     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6037         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6038     AllowedNameModifiers.push_back(OMPD_taskloop);
6039     AllowedNameModifiers.push_back(OMPD_parallel);
6040     break;
6041   case OMPD_parallel_master_taskloop_simd:
6042     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6043         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6044     AllowedNameModifiers.push_back(OMPD_taskloop);
6045     AllowedNameModifiers.push_back(OMPD_parallel);
6046     if (LangOpts.OpenMP >= 50)
6047       AllowedNameModifiers.push_back(OMPD_simd);
6048     break;
6049   case OMPD_distribute:
6050     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6051                                          EndLoc, VarsWithInheritedDSA);
6052     break;
6053   case OMPD_target_update:
6054     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6055                                            EndLoc, AStmt);
6056     AllowedNameModifiers.push_back(OMPD_target_update);
6057     break;
6058   case OMPD_distribute_parallel_for:
6059     Res = ActOnOpenMPDistributeParallelForDirective(
6060         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6061     AllowedNameModifiers.push_back(OMPD_parallel);
6062     break;
6063   case OMPD_distribute_parallel_for_simd:
6064     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6065         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6066     AllowedNameModifiers.push_back(OMPD_parallel);
6067     if (LangOpts.OpenMP >= 50)
6068       AllowedNameModifiers.push_back(OMPD_simd);
6069     break;
6070   case OMPD_distribute_simd:
6071     Res = ActOnOpenMPDistributeSimdDirective(
6072         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6073     if (LangOpts.OpenMP >= 50)
6074       AllowedNameModifiers.push_back(OMPD_simd);
6075     break;
6076   case OMPD_target_parallel_for_simd:
6077     Res = ActOnOpenMPTargetParallelForSimdDirective(
6078         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6079     AllowedNameModifiers.push_back(OMPD_target);
6080     AllowedNameModifiers.push_back(OMPD_parallel);
6081     if (LangOpts.OpenMP >= 50)
6082       AllowedNameModifiers.push_back(OMPD_simd);
6083     break;
6084   case OMPD_target_simd:
6085     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6086                                          EndLoc, VarsWithInheritedDSA);
6087     AllowedNameModifiers.push_back(OMPD_target);
6088     if (LangOpts.OpenMP >= 50)
6089       AllowedNameModifiers.push_back(OMPD_simd);
6090     break;
6091   case OMPD_teams_distribute:
6092     Res = ActOnOpenMPTeamsDistributeDirective(
6093         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6094     break;
6095   case OMPD_teams_distribute_simd:
6096     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6097         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6098     if (LangOpts.OpenMP >= 50)
6099       AllowedNameModifiers.push_back(OMPD_simd);
6100     break;
6101   case OMPD_teams_distribute_parallel_for_simd:
6102     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6103         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6104     AllowedNameModifiers.push_back(OMPD_parallel);
6105     if (LangOpts.OpenMP >= 50)
6106       AllowedNameModifiers.push_back(OMPD_simd);
6107     break;
6108   case OMPD_teams_distribute_parallel_for:
6109     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6110         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6111     AllowedNameModifiers.push_back(OMPD_parallel);
6112     break;
6113   case OMPD_target_teams:
6114     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6115                                           EndLoc);
6116     AllowedNameModifiers.push_back(OMPD_target);
6117     break;
6118   case OMPD_target_teams_distribute:
6119     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6120         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6121     AllowedNameModifiers.push_back(OMPD_target);
6122     break;
6123   case OMPD_target_teams_distribute_parallel_for:
6124     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6125         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6126     AllowedNameModifiers.push_back(OMPD_target);
6127     AllowedNameModifiers.push_back(OMPD_parallel);
6128     break;
6129   case OMPD_target_teams_distribute_parallel_for_simd:
6130     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6131         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6132     AllowedNameModifiers.push_back(OMPD_target);
6133     AllowedNameModifiers.push_back(OMPD_parallel);
6134     if (LangOpts.OpenMP >= 50)
6135       AllowedNameModifiers.push_back(OMPD_simd);
6136     break;
6137   case OMPD_target_teams_distribute_simd:
6138     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6139         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6140     AllowedNameModifiers.push_back(OMPD_target);
6141     if (LangOpts.OpenMP >= 50)
6142       AllowedNameModifiers.push_back(OMPD_simd);
6143     break;
6144   case OMPD_interop:
6145     assert(AStmt == nullptr &&
6146            "No associated statement allowed for 'omp interop' directive");
6147     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6148     break;
6149   case OMPD_dispatch:
6150     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6151                                        EndLoc);
6152     break;
6153   case OMPD_declare_target:
6154   case OMPD_end_declare_target:
6155   case OMPD_threadprivate:
6156   case OMPD_allocate:
6157   case OMPD_declare_reduction:
6158   case OMPD_declare_mapper:
6159   case OMPD_declare_simd:
6160   case OMPD_requires:
6161   case OMPD_declare_variant:
6162   case OMPD_begin_declare_variant:
6163   case OMPD_end_declare_variant:
6164     llvm_unreachable("OpenMP Directive is not allowed");
6165   case OMPD_unknown:
6166   default:
6167     llvm_unreachable("Unknown OpenMP directive");
6168   }
6169 
6170   ErrorFound = Res.isInvalid() || ErrorFound;
6171 
6172   // Check variables in the clauses if default(none) or
6173   // default(firstprivate) was specified.
6174   if (DSAStack->getDefaultDSA() == DSA_none ||
6175       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6176     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6177     for (OMPClause *C : Clauses) {
6178       switch (C->getClauseKind()) {
6179       case OMPC_num_threads:
6180       case OMPC_dist_schedule:
6181         // Do not analyse if no parent teams directive.
6182         if (isOpenMPTeamsDirective(Kind))
6183           break;
6184         continue;
6185       case OMPC_if:
6186         if (isOpenMPTeamsDirective(Kind) &&
6187             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6188           break;
6189         if (isOpenMPParallelDirective(Kind) &&
6190             isOpenMPTaskLoopDirective(Kind) &&
6191             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6192           break;
6193         continue;
6194       case OMPC_schedule:
6195       case OMPC_detach:
6196         break;
6197       case OMPC_grainsize:
6198       case OMPC_num_tasks:
6199       case OMPC_final:
6200       case OMPC_priority:
6201       case OMPC_novariants:
6202       case OMPC_nocontext:
6203         // Do not analyze if no parent parallel directive.
6204         if (isOpenMPParallelDirective(Kind))
6205           break;
6206         continue;
6207       case OMPC_ordered:
6208       case OMPC_device:
6209       case OMPC_num_teams:
6210       case OMPC_thread_limit:
6211       case OMPC_hint:
6212       case OMPC_collapse:
6213       case OMPC_safelen:
6214       case OMPC_simdlen:
6215       case OMPC_sizes:
6216       case OMPC_default:
6217       case OMPC_proc_bind:
6218       case OMPC_private:
6219       case OMPC_firstprivate:
6220       case OMPC_lastprivate:
6221       case OMPC_shared:
6222       case OMPC_reduction:
6223       case OMPC_task_reduction:
6224       case OMPC_in_reduction:
6225       case OMPC_linear:
6226       case OMPC_aligned:
6227       case OMPC_copyin:
6228       case OMPC_copyprivate:
6229       case OMPC_nowait:
6230       case OMPC_untied:
6231       case OMPC_mergeable:
6232       case OMPC_allocate:
6233       case OMPC_read:
6234       case OMPC_write:
6235       case OMPC_update:
6236       case OMPC_capture:
6237       case OMPC_seq_cst:
6238       case OMPC_acq_rel:
6239       case OMPC_acquire:
6240       case OMPC_release:
6241       case OMPC_relaxed:
6242       case OMPC_depend:
6243       case OMPC_threads:
6244       case OMPC_simd:
6245       case OMPC_map:
6246       case OMPC_nogroup:
6247       case OMPC_defaultmap:
6248       case OMPC_to:
6249       case OMPC_from:
6250       case OMPC_use_device_ptr:
6251       case OMPC_use_device_addr:
6252       case OMPC_is_device_ptr:
6253       case OMPC_nontemporal:
6254       case OMPC_order:
6255       case OMPC_destroy:
6256       case OMPC_inclusive:
6257       case OMPC_exclusive:
6258       case OMPC_uses_allocators:
6259       case OMPC_affinity:
6260         continue;
6261       case OMPC_allocator:
6262       case OMPC_flush:
6263       case OMPC_depobj:
6264       case OMPC_threadprivate:
6265       case OMPC_uniform:
6266       case OMPC_unknown:
6267       case OMPC_unified_address:
6268       case OMPC_unified_shared_memory:
6269       case OMPC_reverse_offload:
6270       case OMPC_dynamic_allocators:
6271       case OMPC_atomic_default_mem_order:
6272       case OMPC_device_type:
6273       case OMPC_match:
6274       default:
6275         llvm_unreachable("Unexpected clause");
6276       }
6277       for (Stmt *CC : C->children()) {
6278         if (CC)
6279           DSAChecker.Visit(CC);
6280       }
6281     }
6282     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6283       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6284   }
6285   for (const auto &P : VarsWithInheritedDSA) {
6286     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6287       continue;
6288     ErrorFound = true;
6289     if (DSAStack->getDefaultDSA() == DSA_none ||
6290         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6291       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6292           << P.first << P.second->getSourceRange();
6293       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6294     } else if (getLangOpts().OpenMP >= 50) {
6295       Diag(P.second->getExprLoc(),
6296            diag::err_omp_defaultmap_no_attr_for_variable)
6297           << P.first << P.second->getSourceRange();
6298       Diag(DSAStack->getDefaultDSALocation(),
6299            diag::note_omp_defaultmap_attr_none);
6300     }
6301   }
6302 
6303   if (!AllowedNameModifiers.empty())
6304     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6305                  ErrorFound;
6306 
6307   if (ErrorFound)
6308     return StmtError();
6309 
6310   if (!CurContext->isDependentContext() &&
6311       isOpenMPTargetExecutionDirective(Kind) &&
6312       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6313         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6314         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6315         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6316     // Register target to DSA Stack.
6317     DSAStack->addTargetDirLocation(StartLoc);
6318   }
6319 
6320   return Res;
6321 }
6322 
6323 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6324     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6325     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6326     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6327     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6328   assert(Aligneds.size() == Alignments.size());
6329   assert(Linears.size() == LinModifiers.size());
6330   assert(Linears.size() == Steps.size());
6331   if (!DG || DG.get().isNull())
6332     return DeclGroupPtrTy();
6333 
6334   const int SimdId = 0;
6335   if (!DG.get().isSingleDecl()) {
6336     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6337         << SimdId;
6338     return DG;
6339   }
6340   Decl *ADecl = DG.get().getSingleDecl();
6341   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6342     ADecl = FTD->getTemplatedDecl();
6343 
6344   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6345   if (!FD) {
6346     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6347     return DeclGroupPtrTy();
6348   }
6349 
6350   // OpenMP [2.8.2, declare simd construct, Description]
6351   // The parameter of the simdlen clause must be a constant positive integer
6352   // expression.
6353   ExprResult SL;
6354   if (Simdlen)
6355     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6356   // OpenMP [2.8.2, declare simd construct, Description]
6357   // The special this pointer can be used as if was one of the arguments to the
6358   // function in any of the linear, aligned, or uniform clauses.
6359   // The uniform clause declares one or more arguments to have an invariant
6360   // value for all concurrent invocations of the function in the execution of a
6361   // single SIMD loop.
6362   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6363   const Expr *UniformedLinearThis = nullptr;
6364   for (const Expr *E : Uniforms) {
6365     E = E->IgnoreParenImpCasts();
6366     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6367       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6368         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6369             FD->getParamDecl(PVD->getFunctionScopeIndex())
6370                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6371           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6372           continue;
6373         }
6374     if (isa<CXXThisExpr>(E)) {
6375       UniformedLinearThis = E;
6376       continue;
6377     }
6378     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6379         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6380   }
6381   // OpenMP [2.8.2, declare simd construct, Description]
6382   // The aligned clause declares that the object to which each list item points
6383   // is aligned to the number of bytes expressed in the optional parameter of
6384   // the aligned clause.
6385   // The special this pointer can be used as if was one of the arguments to the
6386   // function in any of the linear, aligned, or uniform clauses.
6387   // The type of list items appearing in the aligned clause must be array,
6388   // pointer, reference to array, or reference to pointer.
6389   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6390   const Expr *AlignedThis = nullptr;
6391   for (const Expr *E : Aligneds) {
6392     E = E->IgnoreParenImpCasts();
6393     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6394       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6395         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6396         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6397             FD->getParamDecl(PVD->getFunctionScopeIndex())
6398                     ->getCanonicalDecl() == CanonPVD) {
6399           // OpenMP  [2.8.1, simd construct, Restrictions]
6400           // A list-item cannot appear in more than one aligned clause.
6401           if (AlignedArgs.count(CanonPVD) > 0) {
6402             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6403                 << 1 << getOpenMPClauseName(OMPC_aligned)
6404                 << E->getSourceRange();
6405             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6406                  diag::note_omp_explicit_dsa)
6407                 << getOpenMPClauseName(OMPC_aligned);
6408             continue;
6409           }
6410           AlignedArgs[CanonPVD] = E;
6411           QualType QTy = PVD->getType()
6412                              .getNonReferenceType()
6413                              .getUnqualifiedType()
6414                              .getCanonicalType();
6415           const Type *Ty = QTy.getTypePtrOrNull();
6416           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6417             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6418                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6419             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6420           }
6421           continue;
6422         }
6423       }
6424     if (isa<CXXThisExpr>(E)) {
6425       if (AlignedThis) {
6426         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6427             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6428         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6429             << getOpenMPClauseName(OMPC_aligned);
6430       }
6431       AlignedThis = E;
6432       continue;
6433     }
6434     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6435         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6436   }
6437   // The optional parameter of the aligned clause, alignment, must be a constant
6438   // positive integer expression. If no optional parameter is specified,
6439   // implementation-defined default alignments for SIMD instructions on the
6440   // target platforms are assumed.
6441   SmallVector<const Expr *, 4> NewAligns;
6442   for (Expr *E : Alignments) {
6443     ExprResult Align;
6444     if (E)
6445       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6446     NewAligns.push_back(Align.get());
6447   }
6448   // OpenMP [2.8.2, declare simd construct, Description]
6449   // The linear clause declares one or more list items to be private to a SIMD
6450   // lane and to have a linear relationship with respect to the iteration space
6451   // of a loop.
6452   // The special this pointer can be used as if was one of the arguments to the
6453   // function in any of the linear, aligned, or uniform clauses.
6454   // When a linear-step expression is specified in a linear clause it must be
6455   // either a constant integer expression or an integer-typed parameter that is
6456   // specified in a uniform clause on the directive.
6457   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6458   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6459   auto MI = LinModifiers.begin();
6460   for (const Expr *E : Linears) {
6461     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6462     ++MI;
6463     E = E->IgnoreParenImpCasts();
6464     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6465       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6466         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6467         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6468             FD->getParamDecl(PVD->getFunctionScopeIndex())
6469                     ->getCanonicalDecl() == CanonPVD) {
6470           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6471           // A list-item cannot appear in more than one linear clause.
6472           if (LinearArgs.count(CanonPVD) > 0) {
6473             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6474                 << getOpenMPClauseName(OMPC_linear)
6475                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6476             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6477                  diag::note_omp_explicit_dsa)
6478                 << getOpenMPClauseName(OMPC_linear);
6479             continue;
6480           }
6481           // Each argument can appear in at most one uniform or linear clause.
6482           if (UniformedArgs.count(CanonPVD) > 0) {
6483             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6484                 << getOpenMPClauseName(OMPC_linear)
6485                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6486             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6487                  diag::note_omp_explicit_dsa)
6488                 << getOpenMPClauseName(OMPC_uniform);
6489             continue;
6490           }
6491           LinearArgs[CanonPVD] = E;
6492           if (E->isValueDependent() || E->isTypeDependent() ||
6493               E->isInstantiationDependent() ||
6494               E->containsUnexpandedParameterPack())
6495             continue;
6496           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6497                                       PVD->getOriginalType(),
6498                                       /*IsDeclareSimd=*/true);
6499           continue;
6500         }
6501       }
6502     if (isa<CXXThisExpr>(E)) {
6503       if (UniformedLinearThis) {
6504         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6505             << getOpenMPClauseName(OMPC_linear)
6506             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6507             << E->getSourceRange();
6508         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6509             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6510                                                    : OMPC_linear);
6511         continue;
6512       }
6513       UniformedLinearThis = E;
6514       if (E->isValueDependent() || E->isTypeDependent() ||
6515           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6516         continue;
6517       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6518                                   E->getType(), /*IsDeclareSimd=*/true);
6519       continue;
6520     }
6521     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6522         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6523   }
6524   Expr *Step = nullptr;
6525   Expr *NewStep = nullptr;
6526   SmallVector<Expr *, 4> NewSteps;
6527   for (Expr *E : Steps) {
6528     // Skip the same step expression, it was checked already.
6529     if (Step == E || !E) {
6530       NewSteps.push_back(E ? NewStep : nullptr);
6531       continue;
6532     }
6533     Step = E;
6534     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6535       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6536         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6537         if (UniformedArgs.count(CanonPVD) == 0) {
6538           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6539               << Step->getSourceRange();
6540         } else if (E->isValueDependent() || E->isTypeDependent() ||
6541                    E->isInstantiationDependent() ||
6542                    E->containsUnexpandedParameterPack() ||
6543                    CanonPVD->getType()->hasIntegerRepresentation()) {
6544           NewSteps.push_back(Step);
6545         } else {
6546           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6547               << Step->getSourceRange();
6548         }
6549         continue;
6550       }
6551     NewStep = Step;
6552     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6553         !Step->isInstantiationDependent() &&
6554         !Step->containsUnexpandedParameterPack()) {
6555       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6556                     .get();
6557       if (NewStep)
6558         NewStep =
6559             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6560     }
6561     NewSteps.push_back(NewStep);
6562   }
6563   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6564       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6565       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6566       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6567       const_cast<Expr **>(Linears.data()), Linears.size(),
6568       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6569       NewSteps.data(), NewSteps.size(), SR);
6570   ADecl->addAttr(NewAttr);
6571   return DG;
6572 }
6573 
6574 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6575                          QualType NewType) {
6576   assert(NewType->isFunctionProtoType() &&
6577          "Expected function type with prototype.");
6578   assert(FD->getType()->isFunctionNoProtoType() &&
6579          "Expected function with type with no prototype.");
6580   assert(FDWithProto->getType()->isFunctionProtoType() &&
6581          "Expected function with prototype.");
6582   // Synthesize parameters with the same types.
6583   FD->setType(NewType);
6584   SmallVector<ParmVarDecl *, 16> Params;
6585   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6586     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6587                                       SourceLocation(), nullptr, P->getType(),
6588                                       /*TInfo=*/nullptr, SC_None, nullptr);
6589     Param->setScopeInfo(0, Params.size());
6590     Param->setImplicit();
6591     Params.push_back(Param);
6592   }
6593 
6594   FD->setParams(Params);
6595 }
6596 
6597 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6598   if (D->isInvalidDecl())
6599     return;
6600   FunctionDecl *FD = nullptr;
6601   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6602     FD = UTemplDecl->getTemplatedDecl();
6603   else
6604     FD = cast<FunctionDecl>(D);
6605   assert(FD && "Expected a function declaration!");
6606 
6607   // If we are intantiating templates we do *not* apply scoped assumptions but
6608   // only global ones. We apply scoped assumption to the template definition
6609   // though.
6610   if (!inTemplateInstantiation()) {
6611     for (AssumptionAttr *AA : OMPAssumeScoped)
6612       FD->addAttr(AA);
6613   }
6614   for (AssumptionAttr *AA : OMPAssumeGlobal)
6615     FD->addAttr(AA);
6616 }
6617 
6618 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6619     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6620 
6621 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6622     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6623     SmallVectorImpl<FunctionDecl *> &Bases) {
6624   if (!D.getIdentifier())
6625     return;
6626 
6627   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6628 
6629   // Template specialization is an extension, check if we do it.
6630   bool IsTemplated = !TemplateParamLists.empty();
6631   if (IsTemplated &
6632       !DVScope.TI->isExtensionActive(
6633           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6634     return;
6635 
6636   IdentifierInfo *BaseII = D.getIdentifier();
6637   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6638                       LookupOrdinaryName);
6639   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6640 
6641   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6642   QualType FType = TInfo->getType();
6643 
6644   bool IsConstexpr =
6645       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6646   bool IsConsteval =
6647       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6648 
6649   for (auto *Candidate : Lookup) {
6650     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6651     FunctionDecl *UDecl = nullptr;
6652     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl))
6653       UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl();
6654     else if (!IsTemplated)
6655       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6656     if (!UDecl)
6657       continue;
6658 
6659     // Don't specialize constexpr/consteval functions with
6660     // non-constexpr/consteval functions.
6661     if (UDecl->isConstexpr() && !IsConstexpr)
6662       continue;
6663     if (UDecl->isConsteval() && !IsConsteval)
6664       continue;
6665 
6666     QualType UDeclTy = UDecl->getType();
6667     if (!UDeclTy->isDependentType()) {
6668       QualType NewType = Context.mergeFunctionTypes(
6669           FType, UDeclTy, /* OfBlockPointer */ false,
6670           /* Unqualified */ false, /* AllowCXX */ true);
6671       if (NewType.isNull())
6672         continue;
6673     }
6674 
6675     // Found a base!
6676     Bases.push_back(UDecl);
6677   }
6678 
6679   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6680       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6681   // If no base was found we create a declaration that we use as base.
6682   if (Bases.empty() && UseImplicitBase) {
6683     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6684     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6685     BaseD->setImplicit(true);
6686     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6687       Bases.push_back(BaseTemplD->getTemplatedDecl());
6688     else
6689       Bases.push_back(cast<FunctionDecl>(BaseD));
6690   }
6691 
6692   std::string MangledName;
6693   MangledName += D.getIdentifier()->getName();
6694   MangledName += getOpenMPVariantManglingSeparatorStr();
6695   MangledName += DVScope.NameSuffix;
6696   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6697 
6698   VariantII.setMangledOpenMPVariantName(true);
6699   D.SetIdentifier(&VariantII, D.getBeginLoc());
6700 }
6701 
6702 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6703     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6704   // Do not mark function as is used to prevent its emission if this is the
6705   // only place where it is used.
6706   EnterExpressionEvaluationContext Unevaluated(
6707       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6708 
6709   FunctionDecl *FD = nullptr;
6710   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6711     FD = UTemplDecl->getTemplatedDecl();
6712   else
6713     FD = cast<FunctionDecl>(D);
6714   auto *VariantFuncRef = DeclRefExpr::Create(
6715       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6716       /* RefersToEnclosingVariableOrCapture */ false,
6717       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
6718 
6719   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6720   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6721       Context, VariantFuncRef, DVScope.TI);
6722   for (FunctionDecl *BaseFD : Bases)
6723     BaseFD->addAttr(OMPDeclareVariantA);
6724 }
6725 
6726 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6727                                  SourceLocation LParenLoc,
6728                                  MultiExprArg ArgExprs,
6729                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6730   // The common case is a regular call we do not want to specialize at all. Try
6731   // to make that case fast by bailing early.
6732   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6733   if (!CE)
6734     return Call;
6735 
6736   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6737   if (!CalleeFnDecl)
6738     return Call;
6739 
6740   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6741     return Call;
6742 
6743   ASTContext &Context = getASTContext();
6744   std::function<void(StringRef)> DiagUnknownTrait = [this,
6745                                                      CE](StringRef ISATrait) {
6746     // TODO Track the selector locations in a way that is accessible here to
6747     // improve the diagnostic location.
6748     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6749         << ISATrait;
6750   };
6751   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6752                           getCurFunctionDecl());
6753 
6754   QualType CalleeFnType = CalleeFnDecl->getType();
6755 
6756   SmallVector<Expr *, 4> Exprs;
6757   SmallVector<VariantMatchInfo, 4> VMIs;
6758   while (CalleeFnDecl) {
6759     for (OMPDeclareVariantAttr *A :
6760          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6761       Expr *VariantRef = A->getVariantFuncRef();
6762 
6763       VariantMatchInfo VMI;
6764       OMPTraitInfo &TI = A->getTraitInfo();
6765       TI.getAsVariantMatchInfo(Context, VMI);
6766       if (!isVariantApplicableInContext(VMI, OMPCtx,
6767                                         /* DeviceSetOnly */ false))
6768         continue;
6769 
6770       VMIs.push_back(VMI);
6771       Exprs.push_back(VariantRef);
6772     }
6773 
6774     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6775   }
6776 
6777   ExprResult NewCall;
6778   do {
6779     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6780     if (BestIdx < 0)
6781       return Call;
6782     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6783     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6784 
6785     {
6786       // Try to build a (member) call expression for the current best applicable
6787       // variant expression. We allow this to fail in which case we continue
6788       // with the next best variant expression. The fail case is part of the
6789       // implementation defined behavior in the OpenMP standard when it talks
6790       // about what differences in the function prototypes: "Any differences
6791       // that the specific OpenMP context requires in the prototype of the
6792       // variant from the base function prototype are implementation defined."
6793       // This wording is there to allow the specialized variant to have a
6794       // different type than the base function. This is intended and OK but if
6795       // we cannot create a call the difference is not in the "implementation
6796       // defined range" we allow.
6797       Sema::TentativeAnalysisScope Trap(*this);
6798 
6799       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6800         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6801         BestExpr = MemberExpr::CreateImplicit(
6802             Context, MemberCall->getImplicitObjectArgument(),
6803             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6804             MemberCall->getValueKind(), MemberCall->getObjectKind());
6805       }
6806       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6807                               ExecConfig);
6808       if (NewCall.isUsable()) {
6809         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6810           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6811           QualType NewType = Context.mergeFunctionTypes(
6812               CalleeFnType, NewCalleeFnDecl->getType(),
6813               /* OfBlockPointer */ false,
6814               /* Unqualified */ false, /* AllowCXX */ true);
6815           if (!NewType.isNull())
6816             break;
6817           // Don't use the call if the function type was not compatible.
6818           NewCall = nullptr;
6819         }
6820       }
6821     }
6822 
6823     VMIs.erase(VMIs.begin() + BestIdx);
6824     Exprs.erase(Exprs.begin() + BestIdx);
6825   } while (!VMIs.empty());
6826 
6827   if (!NewCall.isUsable())
6828     return Call;
6829   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6830 }
6831 
6832 Optional<std::pair<FunctionDecl *, Expr *>>
6833 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6834                                         Expr *VariantRef, OMPTraitInfo &TI,
6835                                         SourceRange SR) {
6836   if (!DG || DG.get().isNull())
6837     return None;
6838 
6839   const int VariantId = 1;
6840   // Must be applied only to single decl.
6841   if (!DG.get().isSingleDecl()) {
6842     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6843         << VariantId << SR;
6844     return None;
6845   }
6846   Decl *ADecl = DG.get().getSingleDecl();
6847   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6848     ADecl = FTD->getTemplatedDecl();
6849 
6850   // Decl must be a function.
6851   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6852   if (!FD) {
6853     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6854         << VariantId << SR;
6855     return None;
6856   }
6857 
6858   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6859     return FD->hasAttrs() &&
6860            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6861             FD->hasAttr<TargetAttr>());
6862   };
6863   // OpenMP is not compatible with CPU-specific attributes.
6864   if (HasMultiVersionAttributes(FD)) {
6865     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6866         << SR;
6867     return None;
6868   }
6869 
6870   // Allow #pragma omp declare variant only if the function is not used.
6871   if (FD->isUsed(false))
6872     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
6873         << FD->getLocation();
6874 
6875   // Check if the function was emitted already.
6876   const FunctionDecl *Definition;
6877   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
6878       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
6879     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
6880         << FD->getLocation();
6881 
6882   // The VariantRef must point to function.
6883   if (!VariantRef) {
6884     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
6885     return None;
6886   }
6887 
6888   auto ShouldDelayChecks = [](Expr *&E, bool) {
6889     return E && (E->isTypeDependent() || E->isValueDependent() ||
6890                  E->containsUnexpandedParameterPack() ||
6891                  E->isInstantiationDependent());
6892   };
6893   // Do not check templates, wait until instantiation.
6894   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
6895       TI.anyScoreOrCondition(ShouldDelayChecks))
6896     return std::make_pair(FD, VariantRef);
6897 
6898   // Deal with non-constant score and user condition expressions.
6899   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
6900                                                      bool IsScore) -> bool {
6901     if (!E || E->isIntegerConstantExpr(Context))
6902       return false;
6903 
6904     if (IsScore) {
6905       // We warn on non-constant scores and pretend they were not present.
6906       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
6907           << E;
6908       E = nullptr;
6909     } else {
6910       // We could replace a non-constant user condition with "false" but we
6911       // will soon need to handle these anyway for the dynamic version of
6912       // OpenMP context selectors.
6913       Diag(E->getExprLoc(),
6914            diag::err_omp_declare_variant_user_condition_not_constant)
6915           << E;
6916     }
6917     return true;
6918   };
6919   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6920     return None;
6921 
6922   // Convert VariantRef expression to the type of the original function to
6923   // resolve possible conflicts.
6924   ExprResult VariantRefCast = VariantRef;
6925   if (LangOpts.CPlusPlus) {
6926     QualType FnPtrType;
6927     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6928     if (Method && !Method->isStatic()) {
6929       const Type *ClassType =
6930           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6931       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6932       ExprResult ER;
6933       {
6934         // Build adrr_of unary op to correctly handle type checks for member
6935         // functions.
6936         Sema::TentativeAnalysisScope Trap(*this);
6937         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6938                                   VariantRef);
6939       }
6940       if (!ER.isUsable()) {
6941         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6942             << VariantId << VariantRef->getSourceRange();
6943         return None;
6944       }
6945       VariantRef = ER.get();
6946     } else {
6947       FnPtrType = Context.getPointerType(FD->getType());
6948     }
6949     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
6950     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
6951       ImplicitConversionSequence ICS = TryImplicitConversion(
6952           VariantRef, FnPtrType.getUnqualifiedType(),
6953           /*SuppressUserConversions=*/false, AllowedExplicit::None,
6954           /*InOverloadResolution=*/false,
6955           /*CStyle=*/false,
6956           /*AllowObjCWritebackConversion=*/false);
6957       if (ICS.isFailure()) {
6958         Diag(VariantRef->getExprLoc(),
6959              diag::err_omp_declare_variant_incompat_types)
6960             << VariantRef->getType()
6961             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6962             << VariantRef->getSourceRange();
6963         return None;
6964       }
6965       VariantRefCast = PerformImplicitConversion(
6966           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6967       if (!VariantRefCast.isUsable())
6968         return None;
6969     }
6970     // Drop previously built artificial addr_of unary op for member functions.
6971     if (Method && !Method->isStatic()) {
6972       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6973       if (auto *UO = dyn_cast<UnaryOperator>(
6974               PossibleAddrOfVariantRef->IgnoreImplicit()))
6975         VariantRefCast = UO->getSubExpr();
6976     }
6977   }
6978 
6979   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6980   if (!ER.isUsable() ||
6981       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6982     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6983         << VariantId << VariantRef->getSourceRange();
6984     return None;
6985   }
6986 
6987   // The VariantRef must point to function.
6988   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6989   if (!DRE) {
6990     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6991         << VariantId << VariantRef->getSourceRange();
6992     return None;
6993   }
6994   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6995   if (!NewFD) {
6996     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6997         << VariantId << VariantRef->getSourceRange();
6998     return None;
6999   }
7000 
7001   // Check if function types are compatible in C.
7002   if (!LangOpts.CPlusPlus) {
7003     QualType NewType =
7004         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
7005     if (NewType.isNull()) {
7006       Diag(VariantRef->getExprLoc(),
7007            diag::err_omp_declare_variant_incompat_types)
7008           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
7009       return None;
7010     }
7011     if (NewType->isFunctionProtoType()) {
7012       if (FD->getType()->isFunctionNoProtoType())
7013         setPrototype(*this, FD, NewFD, NewType);
7014       else if (NewFD->getType()->isFunctionNoProtoType())
7015         setPrototype(*this, NewFD, FD, NewType);
7016     }
7017   }
7018 
7019   // Check if variant function is not marked with declare variant directive.
7020   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7021     Diag(VariantRef->getExprLoc(),
7022          diag::warn_omp_declare_variant_marked_as_declare_variant)
7023         << VariantRef->getSourceRange();
7024     SourceRange SR =
7025         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7026     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7027     return None;
7028   }
7029 
7030   enum DoesntSupport {
7031     VirtFuncs = 1,
7032     Constructors = 3,
7033     Destructors = 4,
7034     DeletedFuncs = 5,
7035     DefaultedFuncs = 6,
7036     ConstexprFuncs = 7,
7037     ConstevalFuncs = 8,
7038   };
7039   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7040     if (CXXFD->isVirtual()) {
7041       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7042           << VirtFuncs;
7043       return None;
7044     }
7045 
7046     if (isa<CXXConstructorDecl>(FD)) {
7047       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7048           << Constructors;
7049       return None;
7050     }
7051 
7052     if (isa<CXXDestructorDecl>(FD)) {
7053       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7054           << Destructors;
7055       return None;
7056     }
7057   }
7058 
7059   if (FD->isDeleted()) {
7060     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7061         << DeletedFuncs;
7062     return None;
7063   }
7064 
7065   if (FD->isDefaulted()) {
7066     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7067         << DefaultedFuncs;
7068     return None;
7069   }
7070 
7071   if (FD->isConstexpr()) {
7072     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7073         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7074     return None;
7075   }
7076 
7077   // Check general compatibility.
7078   if (areMultiversionVariantFunctionsCompatible(
7079           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7080           PartialDiagnosticAt(SourceLocation(),
7081                               PartialDiagnostic::NullDiagnostic()),
7082           PartialDiagnosticAt(
7083               VariantRef->getExprLoc(),
7084               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7085           PartialDiagnosticAt(VariantRef->getExprLoc(),
7086                               PDiag(diag::err_omp_declare_variant_diff)
7087                                   << FD->getLocation()),
7088           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7089           /*CLinkageMayDiffer=*/true))
7090     return None;
7091   return std::make_pair(FD, cast<Expr>(DRE));
7092 }
7093 
7094 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
7095                                               Expr *VariantRef,
7096                                               OMPTraitInfo &TI,
7097                                               SourceRange SR) {
7098   auto *NewAttr =
7099       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
7100   FD->addAttr(NewAttr);
7101 }
7102 
7103 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7104                                               Stmt *AStmt,
7105                                               SourceLocation StartLoc,
7106                                               SourceLocation EndLoc) {
7107   if (!AStmt)
7108     return StmtError();
7109 
7110   auto *CS = cast<CapturedStmt>(AStmt);
7111   // 1.2.2 OpenMP Language Terminology
7112   // Structured block - An executable statement with a single entry at the
7113   // top and a single exit at the bottom.
7114   // The point of exit cannot be a branch out of the structured block.
7115   // longjmp() and throw() must not violate the entry/exit criteria.
7116   CS->getCapturedDecl()->setNothrow();
7117 
7118   setFunctionHasBranchProtectedScope();
7119 
7120   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7121                                       DSAStack->getTaskgroupReductionRef(),
7122                                       DSAStack->isCancelRegion());
7123 }
7124 
7125 namespace {
7126 /// Iteration space of a single for loop.
7127 struct LoopIterationSpace final {
7128   /// True if the condition operator is the strict compare operator (<, > or
7129   /// !=).
7130   bool IsStrictCompare = false;
7131   /// Condition of the loop.
7132   Expr *PreCond = nullptr;
7133   /// This expression calculates the number of iterations in the loop.
7134   /// It is always possible to calculate it before starting the loop.
7135   Expr *NumIterations = nullptr;
7136   /// The loop counter variable.
7137   Expr *CounterVar = nullptr;
7138   /// Private loop counter variable.
7139   Expr *PrivateCounterVar = nullptr;
7140   /// This is initializer for the initial value of #CounterVar.
7141   Expr *CounterInit = nullptr;
7142   /// This is step for the #CounterVar used to generate its update:
7143   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7144   Expr *CounterStep = nullptr;
7145   /// Should step be subtracted?
7146   bool Subtract = false;
7147   /// Source range of the loop init.
7148   SourceRange InitSrcRange;
7149   /// Source range of the loop condition.
7150   SourceRange CondSrcRange;
7151   /// Source range of the loop increment.
7152   SourceRange IncSrcRange;
7153   /// Minimum value that can have the loop control variable. Used to support
7154   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7155   /// since only such variables can be used in non-loop invariant expressions.
7156   Expr *MinValue = nullptr;
7157   /// Maximum value that can have the loop control variable. Used to support
7158   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7159   /// since only such variables can be used in non-loop invariant expressions.
7160   Expr *MaxValue = nullptr;
7161   /// true, if the lower bound depends on the outer loop control var.
7162   bool IsNonRectangularLB = false;
7163   /// true, if the upper bound depends on the outer loop control var.
7164   bool IsNonRectangularUB = false;
7165   /// Index of the loop this loop depends on and forms non-rectangular loop
7166   /// nest.
7167   unsigned LoopDependentIdx = 0;
7168   /// Final condition for the non-rectangular loop nest support. It is used to
7169   /// check that the number of iterations for this particular counter must be
7170   /// finished.
7171   Expr *FinalCondition = nullptr;
7172 };
7173 
7174 /// Helper class for checking canonical form of the OpenMP loops and
7175 /// extracting iteration space of each loop in the loop nest, that will be used
7176 /// for IR generation.
7177 class OpenMPIterationSpaceChecker {
7178   /// Reference to Sema.
7179   Sema &SemaRef;
7180   /// Does the loop associated directive support non-rectangular loops?
7181   bool SupportsNonRectangular;
7182   /// Data-sharing stack.
7183   DSAStackTy &Stack;
7184   /// A location for diagnostics (when there is no some better location).
7185   SourceLocation DefaultLoc;
7186   /// A location for diagnostics (when increment is not compatible).
7187   SourceLocation ConditionLoc;
7188   /// A source location for referring to loop init later.
7189   SourceRange InitSrcRange;
7190   /// A source location for referring to condition later.
7191   SourceRange ConditionSrcRange;
7192   /// A source location for referring to increment later.
7193   SourceRange IncrementSrcRange;
7194   /// Loop variable.
7195   ValueDecl *LCDecl = nullptr;
7196   /// Reference to loop variable.
7197   Expr *LCRef = nullptr;
7198   /// Lower bound (initializer for the var).
7199   Expr *LB = nullptr;
7200   /// Upper bound.
7201   Expr *UB = nullptr;
7202   /// Loop step (increment).
7203   Expr *Step = nullptr;
7204   /// This flag is true when condition is one of:
7205   ///   Var <  UB
7206   ///   Var <= UB
7207   ///   UB  >  Var
7208   ///   UB  >= Var
7209   /// This will have no value when the condition is !=
7210   llvm::Optional<bool> TestIsLessOp;
7211   /// This flag is true when condition is strict ( < or > ).
7212   bool TestIsStrictOp = false;
7213   /// This flag is true when step is subtracted on each iteration.
7214   bool SubtractStep = false;
7215   /// The outer loop counter this loop depends on (if any).
7216   const ValueDecl *DepDecl = nullptr;
7217   /// Contains number of loop (starts from 1) on which loop counter init
7218   /// expression of this loop depends on.
7219   Optional<unsigned> InitDependOnLC;
7220   /// Contains number of loop (starts from 1) on which loop counter condition
7221   /// expression of this loop depends on.
7222   Optional<unsigned> CondDependOnLC;
7223   /// Checks if the provide statement depends on the loop counter.
7224   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7225   /// Original condition required for checking of the exit condition for
7226   /// non-rectangular loop.
7227   Expr *Condition = nullptr;
7228 
7229 public:
7230   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7231                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7232       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7233         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7234   /// Check init-expr for canonical loop form and save loop counter
7235   /// variable - #Var and its initialization value - #LB.
7236   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7237   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7238   /// for less/greater and for strict/non-strict comparison.
7239   bool checkAndSetCond(Expr *S);
7240   /// Check incr-expr for canonical loop form and return true if it
7241   /// does not conform, otherwise save loop step (#Step).
7242   bool checkAndSetInc(Expr *S);
7243   /// Return the loop counter variable.
7244   ValueDecl *getLoopDecl() const { return LCDecl; }
7245   /// Return the reference expression to loop counter variable.
7246   Expr *getLoopDeclRefExpr() const { return LCRef; }
7247   /// Source range of the loop init.
7248   SourceRange getInitSrcRange() const { return InitSrcRange; }
7249   /// Source range of the loop condition.
7250   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7251   /// Source range of the loop increment.
7252   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7253   /// True if the step should be subtracted.
7254   bool shouldSubtractStep() const { return SubtractStep; }
7255   /// True, if the compare operator is strict (<, > or !=).
7256   bool isStrictTestOp() const { return TestIsStrictOp; }
7257   /// Build the expression to calculate the number of iterations.
7258   Expr *buildNumIterations(
7259       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7260       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7261   /// Build the precondition expression for the loops.
7262   Expr *
7263   buildPreCond(Scope *S, Expr *Cond,
7264                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7265   /// Build reference expression to the counter be used for codegen.
7266   DeclRefExpr *
7267   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7268                   DSAStackTy &DSA) const;
7269   /// Build reference expression to the private counter be used for
7270   /// codegen.
7271   Expr *buildPrivateCounterVar() const;
7272   /// Build initialization of the counter be used for codegen.
7273   Expr *buildCounterInit() const;
7274   /// Build step of the counter be used for codegen.
7275   Expr *buildCounterStep() const;
7276   /// Build loop data with counter value for depend clauses in ordered
7277   /// directives.
7278   Expr *
7279   buildOrderedLoopData(Scope *S, Expr *Counter,
7280                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7281                        SourceLocation Loc, Expr *Inc = nullptr,
7282                        OverloadedOperatorKind OOK = OO_Amp);
7283   /// Builds the minimum value for the loop counter.
7284   std::pair<Expr *, Expr *> buildMinMaxValues(
7285       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7286   /// Builds final condition for the non-rectangular loops.
7287   Expr *buildFinalCondition(Scope *S) const;
7288   /// Return true if any expression is dependent.
7289   bool dependent() const;
7290   /// Returns true if the initializer forms non-rectangular loop.
7291   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7292   /// Returns true if the condition forms non-rectangular loop.
7293   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7294   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7295   unsigned getLoopDependentIdx() const {
7296     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7297   }
7298 
7299 private:
7300   /// Check the right-hand side of an assignment in the increment
7301   /// expression.
7302   bool checkAndSetIncRHS(Expr *RHS);
7303   /// Helper to set loop counter variable and its initializer.
7304   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7305                       bool EmitDiags);
7306   /// Helper to set upper bound.
7307   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7308              SourceRange SR, SourceLocation SL);
7309   /// Helper to set loop increment.
7310   bool setStep(Expr *NewStep, bool Subtract);
7311 };
7312 
7313 bool OpenMPIterationSpaceChecker::dependent() const {
7314   if (!LCDecl) {
7315     assert(!LB && !UB && !Step);
7316     return false;
7317   }
7318   return LCDecl->getType()->isDependentType() ||
7319          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7320          (Step && Step->isValueDependent());
7321 }
7322 
7323 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7324                                                  Expr *NewLCRefExpr,
7325                                                  Expr *NewLB, bool EmitDiags) {
7326   // State consistency checking to ensure correct usage.
7327   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7328          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7329   if (!NewLCDecl || !NewLB)
7330     return true;
7331   LCDecl = getCanonicalDecl(NewLCDecl);
7332   LCRef = NewLCRefExpr;
7333   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7334     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7335       if ((Ctor->isCopyOrMoveConstructor() ||
7336            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7337           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7338         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7339   LB = NewLB;
7340   if (EmitDiags)
7341     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7342   return false;
7343 }
7344 
7345 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7346                                         llvm::Optional<bool> LessOp,
7347                                         bool StrictOp, SourceRange SR,
7348                                         SourceLocation SL) {
7349   // State consistency checking to ensure correct usage.
7350   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7351          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7352   if (!NewUB)
7353     return true;
7354   UB = NewUB;
7355   if (LessOp)
7356     TestIsLessOp = LessOp;
7357   TestIsStrictOp = StrictOp;
7358   ConditionSrcRange = SR;
7359   ConditionLoc = SL;
7360   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7361   return false;
7362 }
7363 
7364 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7365   // State consistency checking to ensure correct usage.
7366   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7367   if (!NewStep)
7368     return true;
7369   if (!NewStep->isValueDependent()) {
7370     // Check that the step is integer expression.
7371     SourceLocation StepLoc = NewStep->getBeginLoc();
7372     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7373         StepLoc, getExprAsWritten(NewStep));
7374     if (Val.isInvalid())
7375       return true;
7376     NewStep = Val.get();
7377 
7378     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7379     //  If test-expr is of form var relational-op b and relational-op is < or
7380     //  <= then incr-expr must cause var to increase on each iteration of the
7381     //  loop. If test-expr is of form var relational-op b and relational-op is
7382     //  > or >= then incr-expr must cause var to decrease on each iteration of
7383     //  the loop.
7384     //  If test-expr is of form b relational-op var and relational-op is < or
7385     //  <= then incr-expr must cause var to decrease on each iteration of the
7386     //  loop. If test-expr is of form b relational-op var and relational-op is
7387     //  > or >= then incr-expr must cause var to increase on each iteration of
7388     //  the loop.
7389     Optional<llvm::APSInt> Result =
7390         NewStep->getIntegerConstantExpr(SemaRef.Context);
7391     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7392     bool IsConstNeg =
7393         Result && Result->isSigned() && (Subtract != Result->isNegative());
7394     bool IsConstPos =
7395         Result && Result->isSigned() && (Subtract == Result->isNegative());
7396     bool IsConstZero = Result && !Result->getBoolValue();
7397 
7398     // != with increment is treated as <; != with decrement is treated as >
7399     if (!TestIsLessOp.hasValue())
7400       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7401     if (UB && (IsConstZero ||
7402                (TestIsLessOp.getValue() ?
7403                   (IsConstNeg || (IsUnsigned && Subtract)) :
7404                   (IsConstPos || (IsUnsigned && !Subtract))))) {
7405       SemaRef.Diag(NewStep->getExprLoc(),
7406                    diag::err_omp_loop_incr_not_compatible)
7407           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7408       SemaRef.Diag(ConditionLoc,
7409                    diag::note_omp_loop_cond_requres_compatible_incr)
7410           << TestIsLessOp.getValue() << ConditionSrcRange;
7411       return true;
7412     }
7413     if (TestIsLessOp.getValue() == Subtract) {
7414       NewStep =
7415           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7416               .get();
7417       Subtract = !Subtract;
7418     }
7419   }
7420 
7421   Step = NewStep;
7422   SubtractStep = Subtract;
7423   return false;
7424 }
7425 
7426 namespace {
7427 /// Checker for the non-rectangular loops. Checks if the initializer or
7428 /// condition expression references loop counter variable.
7429 class LoopCounterRefChecker final
7430     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7431   Sema &SemaRef;
7432   DSAStackTy &Stack;
7433   const ValueDecl *CurLCDecl = nullptr;
7434   const ValueDecl *DepDecl = nullptr;
7435   const ValueDecl *PrevDepDecl = nullptr;
7436   bool IsInitializer = true;
7437   bool SupportsNonRectangular;
7438   unsigned BaseLoopId = 0;
7439   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7440     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7441       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7442           << (IsInitializer ? 0 : 1);
7443       return false;
7444     }
7445     const auto &&Data = Stack.isLoopControlVariable(VD);
7446     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7447     // The type of the loop iterator on which we depend may not have a random
7448     // access iterator type.
7449     if (Data.first && VD->getType()->isRecordType()) {
7450       SmallString<128> Name;
7451       llvm::raw_svector_ostream OS(Name);
7452       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7453                                /*Qualified=*/true);
7454       SemaRef.Diag(E->getExprLoc(),
7455                    diag::err_omp_wrong_dependency_iterator_type)
7456           << OS.str();
7457       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7458       return false;
7459     }
7460     if (Data.first && !SupportsNonRectangular) {
7461       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7462       return false;
7463     }
7464     if (Data.first &&
7465         (DepDecl || (PrevDepDecl &&
7466                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7467       if (!DepDecl && PrevDepDecl)
7468         DepDecl = PrevDepDecl;
7469       SmallString<128> Name;
7470       llvm::raw_svector_ostream OS(Name);
7471       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7472                                     /*Qualified=*/true);
7473       SemaRef.Diag(E->getExprLoc(),
7474                    diag::err_omp_invariant_or_linear_dependency)
7475           << OS.str();
7476       return false;
7477     }
7478     if (Data.first) {
7479       DepDecl = VD;
7480       BaseLoopId = Data.first;
7481     }
7482     return Data.first;
7483   }
7484 
7485 public:
7486   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7487     const ValueDecl *VD = E->getDecl();
7488     if (isa<VarDecl>(VD))
7489       return checkDecl(E, VD);
7490     return false;
7491   }
7492   bool VisitMemberExpr(const MemberExpr *E) {
7493     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7494       const ValueDecl *VD = E->getMemberDecl();
7495       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7496         return checkDecl(E, VD);
7497     }
7498     return false;
7499   }
7500   bool VisitStmt(const Stmt *S) {
7501     bool Res = false;
7502     for (const Stmt *Child : S->children())
7503       Res = (Child && Visit(Child)) || Res;
7504     return Res;
7505   }
7506   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7507                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7508                                  const ValueDecl *PrevDepDecl = nullptr,
7509                                  bool SupportsNonRectangular = true)
7510       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7511         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7512         SupportsNonRectangular(SupportsNonRectangular) {}
7513   unsigned getBaseLoopId() const {
7514     assert(CurLCDecl && "Expected loop dependency.");
7515     return BaseLoopId;
7516   }
7517   const ValueDecl *getDepDecl() const {
7518     assert(CurLCDecl && "Expected loop dependency.");
7519     return DepDecl;
7520   }
7521 };
7522 } // namespace
7523 
7524 Optional<unsigned>
7525 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7526                                                      bool IsInitializer) {
7527   // Check for the non-rectangular loops.
7528   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7529                                         DepDecl, SupportsNonRectangular);
7530   if (LoopStmtChecker.Visit(S)) {
7531     DepDecl = LoopStmtChecker.getDepDecl();
7532     return LoopStmtChecker.getBaseLoopId();
7533   }
7534   return llvm::None;
7535 }
7536 
7537 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7538   // Check init-expr for canonical loop form and save loop counter
7539   // variable - #Var and its initialization value - #LB.
7540   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7541   //   var = lb
7542   //   integer-type var = lb
7543   //   random-access-iterator-type var = lb
7544   //   pointer-type var = lb
7545   //
7546   if (!S) {
7547     if (EmitDiags) {
7548       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7549     }
7550     return true;
7551   }
7552   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7553     if (!ExprTemp->cleanupsHaveSideEffects())
7554       S = ExprTemp->getSubExpr();
7555 
7556   InitSrcRange = S->getSourceRange();
7557   if (Expr *E = dyn_cast<Expr>(S))
7558     S = E->IgnoreParens();
7559   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7560     if (BO->getOpcode() == BO_Assign) {
7561       Expr *LHS = BO->getLHS()->IgnoreParens();
7562       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7563         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7564           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7565             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7566                                   EmitDiags);
7567         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7568       }
7569       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7570         if (ME->isArrow() &&
7571             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7572           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7573                                 EmitDiags);
7574       }
7575     }
7576   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7577     if (DS->isSingleDecl()) {
7578       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7579         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7580           // Accept non-canonical init form here but emit ext. warning.
7581           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7582             SemaRef.Diag(S->getBeginLoc(),
7583                          diag::ext_omp_loop_not_canonical_init)
7584                 << S->getSourceRange();
7585           return setLCDeclAndLB(
7586               Var,
7587               buildDeclRefExpr(SemaRef, Var,
7588                                Var->getType().getNonReferenceType(),
7589                                DS->getBeginLoc()),
7590               Var->getInit(), EmitDiags);
7591         }
7592       }
7593     }
7594   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7595     if (CE->getOperator() == OO_Equal) {
7596       Expr *LHS = CE->getArg(0);
7597       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7598         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7599           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7600             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7601                                   EmitDiags);
7602         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7603       }
7604       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7605         if (ME->isArrow() &&
7606             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7607           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7608                                 EmitDiags);
7609       }
7610     }
7611   }
7612 
7613   if (dependent() || SemaRef.CurContext->isDependentContext())
7614     return false;
7615   if (EmitDiags) {
7616     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7617         << S->getSourceRange();
7618   }
7619   return true;
7620 }
7621 
7622 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7623 /// variable (which may be the loop variable) if possible.
7624 static const ValueDecl *getInitLCDecl(const Expr *E) {
7625   if (!E)
7626     return nullptr;
7627   E = getExprAsWritten(E);
7628   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7629     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7630       if ((Ctor->isCopyOrMoveConstructor() ||
7631            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7632           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7633         E = CE->getArg(0)->IgnoreParenImpCasts();
7634   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7635     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7636       return getCanonicalDecl(VD);
7637   }
7638   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7639     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7640       return getCanonicalDecl(ME->getMemberDecl());
7641   return nullptr;
7642 }
7643 
7644 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7645   // Check test-expr for canonical form, save upper-bound UB, flags for
7646   // less/greater and for strict/non-strict comparison.
7647   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7648   //   var relational-op b
7649   //   b relational-op var
7650   //
7651   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7652   if (!S) {
7653     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7654         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7655     return true;
7656   }
7657   Condition = S;
7658   S = getExprAsWritten(S);
7659   SourceLocation CondLoc = S->getBeginLoc();
7660   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7661     if (BO->isRelationalOp()) {
7662       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7663         return setUB(BO->getRHS(),
7664                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
7665                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7666                      BO->getSourceRange(), BO->getOperatorLoc());
7667       if (getInitLCDecl(BO->getRHS()) == LCDecl)
7668         return setUB(BO->getLHS(),
7669                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
7670                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7671                      BO->getSourceRange(), BO->getOperatorLoc());
7672     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
7673       return setUB(
7674           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
7675           /*LessOp=*/llvm::None,
7676           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
7677   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7678     if (CE->getNumArgs() == 2) {
7679       auto Op = CE->getOperator();
7680       switch (Op) {
7681       case OO_Greater:
7682       case OO_GreaterEqual:
7683       case OO_Less:
7684       case OO_LessEqual:
7685         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7686           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
7687                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7688                        CE->getOperatorLoc());
7689         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
7690           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
7691                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7692                        CE->getOperatorLoc());
7693         break;
7694       case OO_ExclaimEqual:
7695         if (IneqCondIsCanonical)
7696           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
7697                                                               : CE->getArg(0),
7698                        /*LessOp=*/llvm::None,
7699                        /*StrictOp=*/true, CE->getSourceRange(),
7700                        CE->getOperatorLoc());
7701         break;
7702       default:
7703         break;
7704       }
7705     }
7706   }
7707   if (dependent() || SemaRef.CurContext->isDependentContext())
7708     return false;
7709   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7710       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7711   return true;
7712 }
7713 
7714 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7715   // RHS of canonical loop form increment can be:
7716   //   var + incr
7717   //   incr + var
7718   //   var - incr
7719   //
7720   RHS = RHS->IgnoreParenImpCasts();
7721   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7722     if (BO->isAdditiveOp()) {
7723       bool IsAdd = BO->getOpcode() == BO_Add;
7724       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7725         return setStep(BO->getRHS(), !IsAdd);
7726       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7727         return setStep(BO->getLHS(), /*Subtract=*/false);
7728     }
7729   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7730     bool IsAdd = CE->getOperator() == OO_Plus;
7731     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7732       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7733         return setStep(CE->getArg(1), !IsAdd);
7734       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7735         return setStep(CE->getArg(0), /*Subtract=*/false);
7736     }
7737   }
7738   if (dependent() || SemaRef.CurContext->isDependentContext())
7739     return false;
7740   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7741       << RHS->getSourceRange() << LCDecl;
7742   return true;
7743 }
7744 
7745 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7746   // Check incr-expr for canonical loop form and return true if it
7747   // does not conform.
7748   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7749   //   ++var
7750   //   var++
7751   //   --var
7752   //   var--
7753   //   var += incr
7754   //   var -= incr
7755   //   var = var + incr
7756   //   var = incr + var
7757   //   var = var - incr
7758   //
7759   if (!S) {
7760     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7761     return true;
7762   }
7763   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7764     if (!ExprTemp->cleanupsHaveSideEffects())
7765       S = ExprTemp->getSubExpr();
7766 
7767   IncrementSrcRange = S->getSourceRange();
7768   S = S->IgnoreParens();
7769   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7770     if (UO->isIncrementDecrementOp() &&
7771         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7772       return setStep(SemaRef
7773                          .ActOnIntegerConstant(UO->getBeginLoc(),
7774                                                (UO->isDecrementOp() ? -1 : 1))
7775                          .get(),
7776                      /*Subtract=*/false);
7777   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7778     switch (BO->getOpcode()) {
7779     case BO_AddAssign:
7780     case BO_SubAssign:
7781       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7782         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7783       break;
7784     case BO_Assign:
7785       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7786         return checkAndSetIncRHS(BO->getRHS());
7787       break;
7788     default:
7789       break;
7790     }
7791   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7792     switch (CE->getOperator()) {
7793     case OO_PlusPlus:
7794     case OO_MinusMinus:
7795       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7796         return setStep(SemaRef
7797                            .ActOnIntegerConstant(
7798                                CE->getBeginLoc(),
7799                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
7800                            .get(),
7801                        /*Subtract=*/false);
7802       break;
7803     case OO_PlusEqual:
7804     case OO_MinusEqual:
7805       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7806         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
7807       break;
7808     case OO_Equal:
7809       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7810         return checkAndSetIncRHS(CE->getArg(1));
7811       break;
7812     default:
7813       break;
7814     }
7815   }
7816   if (dependent() || SemaRef.CurContext->isDependentContext())
7817     return false;
7818   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7819       << S->getSourceRange() << LCDecl;
7820   return true;
7821 }
7822 
7823 static ExprResult
7824 tryBuildCapture(Sema &SemaRef, Expr *Capture,
7825                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7826   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
7827     return Capture;
7828   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
7829     return SemaRef.PerformImplicitConversion(
7830         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
7831         /*AllowExplicit=*/true);
7832   auto I = Captures.find(Capture);
7833   if (I != Captures.end())
7834     return buildCapture(SemaRef, Capture, I->second);
7835   DeclRefExpr *Ref = nullptr;
7836   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
7837   Captures[Capture] = Ref;
7838   return Res;
7839 }
7840 
7841 /// Calculate number of iterations, transforming to unsigned, if number of
7842 /// iterations may be larger than the original type.
7843 static Expr *
7844 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
7845                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
7846                   bool TestIsStrictOp, bool RoundToStep,
7847                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7848   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7849   if (!NewStep.isUsable())
7850     return nullptr;
7851   llvm::APSInt LRes, SRes;
7852   bool IsLowerConst = false, IsStepConst = false;
7853   if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) {
7854     LRes = *Res;
7855     IsLowerConst = true;
7856   }
7857   if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) {
7858     SRes = *Res;
7859     IsStepConst = true;
7860   }
7861   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
7862                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
7863                           (TestIsStrictOp && LRes.isStrictlyPositive()));
7864   bool NeedToReorganize = false;
7865   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
7866   if (!NoNeedToConvert && IsLowerConst &&
7867       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
7868     NoNeedToConvert = true;
7869     if (RoundToStep) {
7870       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
7871                         ? LRes.getBitWidth()
7872                         : SRes.getBitWidth();
7873       LRes = LRes.extend(BW + 1);
7874       LRes.setIsSigned(true);
7875       SRes = SRes.extend(BW + 1);
7876       SRes.setIsSigned(true);
7877       LRes -= SRes;
7878       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
7879       LRes = LRes.trunc(BW);
7880     }
7881     if (TestIsStrictOp) {
7882       unsigned BW = LRes.getBitWidth();
7883       LRes = LRes.extend(BW + 1);
7884       LRes.setIsSigned(true);
7885       ++LRes;
7886       NoNeedToConvert =
7887           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
7888       // truncate to the original bitwidth.
7889       LRes = LRes.trunc(BW);
7890     }
7891     NeedToReorganize = NoNeedToConvert;
7892   }
7893   llvm::APSInt URes;
7894   bool IsUpperConst = false;
7895   if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) {
7896     URes = *Res;
7897     IsUpperConst = true;
7898   }
7899   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
7900       (!RoundToStep || IsStepConst)) {
7901     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
7902                                                           : URes.getBitWidth();
7903     LRes = LRes.extend(BW + 1);
7904     LRes.setIsSigned(true);
7905     URes = URes.extend(BW + 1);
7906     URes.setIsSigned(true);
7907     URes -= LRes;
7908     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
7909     NeedToReorganize = NoNeedToConvert;
7910   }
7911   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
7912   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
7913   // unsigned.
7914   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
7915       !LCTy->isDependentType() && LCTy->isIntegerType()) {
7916     QualType LowerTy = Lower->getType();
7917     QualType UpperTy = Upper->getType();
7918     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
7919     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
7920     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
7921         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
7922       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
7923           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
7924       Upper =
7925           SemaRef
7926               .PerformImplicitConversion(
7927                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7928                   CastType, Sema::AA_Converting)
7929               .get();
7930       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7931       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7932     }
7933   }
7934   if (!Lower || !Upper || NewStep.isInvalid())
7935     return nullptr;
7936 
7937   ExprResult Diff;
7938   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7939   // 1]).
7940   if (NeedToReorganize) {
7941     Diff = Lower;
7942 
7943     if (RoundToStep) {
7944       // Lower - Step
7945       Diff =
7946           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7947       if (!Diff.isUsable())
7948         return nullptr;
7949     }
7950 
7951     // Lower - Step [+ 1]
7952     if (TestIsStrictOp)
7953       Diff = SemaRef.BuildBinOp(
7954           S, DefaultLoc, BO_Add, Diff.get(),
7955           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7956     if (!Diff.isUsable())
7957       return nullptr;
7958 
7959     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7960     if (!Diff.isUsable())
7961       return nullptr;
7962 
7963     // Upper - (Lower - Step [+ 1]).
7964     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7965     if (!Diff.isUsable())
7966       return nullptr;
7967   } else {
7968     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7969 
7970     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7971       // BuildBinOp already emitted error, this one is to point user to upper
7972       // and lower bound, and to tell what is passed to 'operator-'.
7973       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7974           << Upper->getSourceRange() << Lower->getSourceRange();
7975       return nullptr;
7976     }
7977 
7978     if (!Diff.isUsable())
7979       return nullptr;
7980 
7981     // Upper - Lower [- 1]
7982     if (TestIsStrictOp)
7983       Diff = SemaRef.BuildBinOp(
7984           S, DefaultLoc, BO_Sub, Diff.get(),
7985           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7986     if (!Diff.isUsable())
7987       return nullptr;
7988 
7989     if (RoundToStep) {
7990       // Upper - Lower [- 1] + Step
7991       Diff =
7992           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7993       if (!Diff.isUsable())
7994         return nullptr;
7995     }
7996   }
7997 
7998   // Parentheses (for dumping/debugging purposes only).
7999   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8000   if (!Diff.isUsable())
8001     return nullptr;
8002 
8003   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8004   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8005   if (!Diff.isUsable())
8006     return nullptr;
8007 
8008   return Diff.get();
8009 }
8010 
8011 /// Build the expression to calculate the number of iterations.
8012 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8013     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8014     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8015   QualType VarType = LCDecl->getType().getNonReferenceType();
8016   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8017       !SemaRef.getLangOpts().CPlusPlus)
8018     return nullptr;
8019   Expr *LBVal = LB;
8020   Expr *UBVal = UB;
8021   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8022   // max(LB(MinVal), LB(MaxVal))
8023   if (InitDependOnLC) {
8024     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8025     if (!IS.MinValue || !IS.MaxValue)
8026       return nullptr;
8027     // OuterVar = Min
8028     ExprResult MinValue =
8029         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8030     if (!MinValue.isUsable())
8031       return nullptr;
8032 
8033     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8034                                              IS.CounterVar, MinValue.get());
8035     if (!LBMinVal.isUsable())
8036       return nullptr;
8037     // OuterVar = Min, LBVal
8038     LBMinVal =
8039         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8040     if (!LBMinVal.isUsable())
8041       return nullptr;
8042     // (OuterVar = Min, LBVal)
8043     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8044     if (!LBMinVal.isUsable())
8045       return nullptr;
8046 
8047     // OuterVar = Max
8048     ExprResult MaxValue =
8049         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8050     if (!MaxValue.isUsable())
8051       return nullptr;
8052 
8053     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8054                                              IS.CounterVar, MaxValue.get());
8055     if (!LBMaxVal.isUsable())
8056       return nullptr;
8057     // OuterVar = Max, LBVal
8058     LBMaxVal =
8059         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8060     if (!LBMaxVal.isUsable())
8061       return nullptr;
8062     // (OuterVar = Max, LBVal)
8063     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8064     if (!LBMaxVal.isUsable())
8065       return nullptr;
8066 
8067     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8068     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8069     if (!LBMin || !LBMax)
8070       return nullptr;
8071     // LB(MinVal) < LB(MaxVal)
8072     ExprResult MinLessMaxRes =
8073         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8074     if (!MinLessMaxRes.isUsable())
8075       return nullptr;
8076     Expr *MinLessMax =
8077         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8078     if (!MinLessMax)
8079       return nullptr;
8080     if (TestIsLessOp.getValue()) {
8081       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8082       // LB(MaxVal))
8083       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8084                                                     MinLessMax, LBMin, LBMax);
8085       if (!MinLB.isUsable())
8086         return nullptr;
8087       LBVal = MinLB.get();
8088     } else {
8089       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8090       // LB(MaxVal))
8091       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8092                                                     MinLessMax, LBMax, LBMin);
8093       if (!MaxLB.isUsable())
8094         return nullptr;
8095       LBVal = MaxLB.get();
8096     }
8097   }
8098   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8099   // min(UB(MinVal), UB(MaxVal))
8100   if (CondDependOnLC) {
8101     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8102     if (!IS.MinValue || !IS.MaxValue)
8103       return nullptr;
8104     // OuterVar = Min
8105     ExprResult MinValue =
8106         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8107     if (!MinValue.isUsable())
8108       return nullptr;
8109 
8110     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8111                                              IS.CounterVar, MinValue.get());
8112     if (!UBMinVal.isUsable())
8113       return nullptr;
8114     // OuterVar = Min, UBVal
8115     UBMinVal =
8116         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8117     if (!UBMinVal.isUsable())
8118       return nullptr;
8119     // (OuterVar = Min, UBVal)
8120     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8121     if (!UBMinVal.isUsable())
8122       return nullptr;
8123 
8124     // OuterVar = Max
8125     ExprResult MaxValue =
8126         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8127     if (!MaxValue.isUsable())
8128       return nullptr;
8129 
8130     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8131                                              IS.CounterVar, MaxValue.get());
8132     if (!UBMaxVal.isUsable())
8133       return nullptr;
8134     // OuterVar = Max, UBVal
8135     UBMaxVal =
8136         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8137     if (!UBMaxVal.isUsable())
8138       return nullptr;
8139     // (OuterVar = Max, UBVal)
8140     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8141     if (!UBMaxVal.isUsable())
8142       return nullptr;
8143 
8144     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8145     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8146     if (!UBMin || !UBMax)
8147       return nullptr;
8148     // UB(MinVal) > UB(MaxVal)
8149     ExprResult MinGreaterMaxRes =
8150         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8151     if (!MinGreaterMaxRes.isUsable())
8152       return nullptr;
8153     Expr *MinGreaterMax =
8154         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8155     if (!MinGreaterMax)
8156       return nullptr;
8157     if (TestIsLessOp.getValue()) {
8158       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8159       // UB(MaxVal))
8160       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8161           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8162       if (!MaxUB.isUsable())
8163         return nullptr;
8164       UBVal = MaxUB.get();
8165     } else {
8166       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8167       // UB(MaxVal))
8168       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8169           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8170       if (!MinUB.isUsable())
8171         return nullptr;
8172       UBVal = MinUB.get();
8173     }
8174   }
8175   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8176   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8177   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8178   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8179   if (!Upper || !Lower)
8180     return nullptr;
8181 
8182   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8183                                       Step, VarType, TestIsStrictOp,
8184                                       /*RoundToStep=*/true, Captures);
8185   if (!Diff.isUsable())
8186     return nullptr;
8187 
8188   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8189   QualType Type = Diff.get()->getType();
8190   ASTContext &C = SemaRef.Context;
8191   bool UseVarType = VarType->hasIntegerRepresentation() &&
8192                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8193   if (!Type->isIntegerType() || UseVarType) {
8194     unsigned NewSize =
8195         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8196     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8197                                : Type->hasSignedIntegerRepresentation();
8198     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8199     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8200       Diff = SemaRef.PerformImplicitConversion(
8201           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8202       if (!Diff.isUsable())
8203         return nullptr;
8204     }
8205   }
8206   if (LimitedType) {
8207     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8208     if (NewSize != C.getTypeSize(Type)) {
8209       if (NewSize < C.getTypeSize(Type)) {
8210         assert(NewSize == 64 && "incorrect loop var size");
8211         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8212             << InitSrcRange << ConditionSrcRange;
8213       }
8214       QualType NewType = C.getIntTypeForBitwidth(
8215           NewSize, Type->hasSignedIntegerRepresentation() ||
8216                        C.getTypeSize(Type) < NewSize);
8217       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8218         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8219                                                  Sema::AA_Converting, true);
8220         if (!Diff.isUsable())
8221           return nullptr;
8222       }
8223     }
8224   }
8225 
8226   return Diff.get();
8227 }
8228 
8229 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8230     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8231   // Do not build for iterators, they cannot be used in non-rectangular loop
8232   // nests.
8233   if (LCDecl->getType()->isRecordType())
8234     return std::make_pair(nullptr, nullptr);
8235   // If we subtract, the min is in the condition, otherwise the min is in the
8236   // init value.
8237   Expr *MinExpr = nullptr;
8238   Expr *MaxExpr = nullptr;
8239   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8240   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8241   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8242                                            : CondDependOnLC.hasValue();
8243   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8244                                            : InitDependOnLC.hasValue();
8245   Expr *Lower =
8246       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8247   Expr *Upper =
8248       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8249   if (!Upper || !Lower)
8250     return std::make_pair(nullptr, nullptr);
8251 
8252   if (TestIsLessOp.getValue())
8253     MinExpr = Lower;
8254   else
8255     MaxExpr = Upper;
8256 
8257   // Build minimum/maximum value based on number of iterations.
8258   QualType VarType = LCDecl->getType().getNonReferenceType();
8259 
8260   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8261                                       Step, VarType, TestIsStrictOp,
8262                                       /*RoundToStep=*/false, Captures);
8263   if (!Diff.isUsable())
8264     return std::make_pair(nullptr, nullptr);
8265 
8266   // ((Upper - Lower [- 1]) / Step) * Step
8267   // Parentheses (for dumping/debugging purposes only).
8268   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8269   if (!Diff.isUsable())
8270     return std::make_pair(nullptr, nullptr);
8271 
8272   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8273   if (!NewStep.isUsable())
8274     return std::make_pair(nullptr, nullptr);
8275   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8276   if (!Diff.isUsable())
8277     return std::make_pair(nullptr, nullptr);
8278 
8279   // Parentheses (for dumping/debugging purposes only).
8280   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8281   if (!Diff.isUsable())
8282     return std::make_pair(nullptr, nullptr);
8283 
8284   // Convert to the ptrdiff_t, if original type is pointer.
8285   if (VarType->isAnyPointerType() &&
8286       !SemaRef.Context.hasSameType(
8287           Diff.get()->getType(),
8288           SemaRef.Context.getUnsignedPointerDiffType())) {
8289     Diff = SemaRef.PerformImplicitConversion(
8290         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8291         Sema::AA_Converting, /*AllowExplicit=*/true);
8292   }
8293   if (!Diff.isUsable())
8294     return std::make_pair(nullptr, nullptr);
8295 
8296   if (TestIsLessOp.getValue()) {
8297     // MinExpr = Lower;
8298     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8299     Diff = SemaRef.BuildBinOp(
8300         S, DefaultLoc, BO_Add,
8301         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8302         Diff.get());
8303     if (!Diff.isUsable())
8304       return std::make_pair(nullptr, nullptr);
8305   } else {
8306     // MaxExpr = Upper;
8307     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8308     Diff = SemaRef.BuildBinOp(
8309         S, DefaultLoc, BO_Sub,
8310         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8311         Diff.get());
8312     if (!Diff.isUsable())
8313       return std::make_pair(nullptr, nullptr);
8314   }
8315 
8316   // Convert to the original type.
8317   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8318     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8319                                              Sema::AA_Converting,
8320                                              /*AllowExplicit=*/true);
8321   if (!Diff.isUsable())
8322     return std::make_pair(nullptr, nullptr);
8323 
8324   Sema::TentativeAnalysisScope Trap(SemaRef);
8325   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8326   if (!Diff.isUsable())
8327     return std::make_pair(nullptr, nullptr);
8328 
8329   if (TestIsLessOp.getValue())
8330     MaxExpr = Diff.get();
8331   else
8332     MinExpr = Diff.get();
8333 
8334   return std::make_pair(MinExpr, MaxExpr);
8335 }
8336 
8337 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8338   if (InitDependOnLC || CondDependOnLC)
8339     return Condition;
8340   return nullptr;
8341 }
8342 
8343 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8344     Scope *S, Expr *Cond,
8345     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8346   // Do not build a precondition when the condition/initialization is dependent
8347   // to prevent pessimistic early loop exit.
8348   // TODO: this can be improved by calculating min/max values but not sure that
8349   // it will be very effective.
8350   if (CondDependOnLC || InitDependOnLC)
8351     return SemaRef.PerformImplicitConversion(
8352         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8353         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8354         /*AllowExplicit=*/true).get();
8355 
8356   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8357   Sema::TentativeAnalysisScope Trap(SemaRef);
8358 
8359   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8360   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8361   if (!NewLB.isUsable() || !NewUB.isUsable())
8362     return nullptr;
8363 
8364   ExprResult CondExpr =
8365       SemaRef.BuildBinOp(S, DefaultLoc,
8366                          TestIsLessOp.getValue() ?
8367                            (TestIsStrictOp ? BO_LT : BO_LE) :
8368                            (TestIsStrictOp ? BO_GT : BO_GE),
8369                          NewLB.get(), NewUB.get());
8370   if (CondExpr.isUsable()) {
8371     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8372                                                 SemaRef.Context.BoolTy))
8373       CondExpr = SemaRef.PerformImplicitConversion(
8374           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8375           /*AllowExplicit=*/true);
8376   }
8377 
8378   // Otherwise use original loop condition and evaluate it in runtime.
8379   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8380 }
8381 
8382 /// Build reference expression to the counter be used for codegen.
8383 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8384     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8385     DSAStackTy &DSA) const {
8386   auto *VD = dyn_cast<VarDecl>(LCDecl);
8387   if (!VD) {
8388     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8389     DeclRefExpr *Ref = buildDeclRefExpr(
8390         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8391     const DSAStackTy::DSAVarData Data =
8392         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8393     // If the loop control decl is explicitly marked as private, do not mark it
8394     // as captured again.
8395     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8396       Captures.insert(std::make_pair(LCRef, Ref));
8397     return Ref;
8398   }
8399   return cast<DeclRefExpr>(LCRef);
8400 }
8401 
8402 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8403   if (LCDecl && !LCDecl->isInvalidDecl()) {
8404     QualType Type = LCDecl->getType().getNonReferenceType();
8405     VarDecl *PrivateVar = buildVarDecl(
8406         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8407         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8408         isa<VarDecl>(LCDecl)
8409             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8410             : nullptr);
8411     if (PrivateVar->isInvalidDecl())
8412       return nullptr;
8413     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8414   }
8415   return nullptr;
8416 }
8417 
8418 /// Build initialization of the counter to be used for codegen.
8419 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8420 
8421 /// Build step of the counter be used for codegen.
8422 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8423 
8424 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8425     Scope *S, Expr *Counter,
8426     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8427     Expr *Inc, OverloadedOperatorKind OOK) {
8428   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8429   if (!Cnt)
8430     return nullptr;
8431   if (Inc) {
8432     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8433            "Expected only + or - operations for depend clauses.");
8434     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8435     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8436     if (!Cnt)
8437       return nullptr;
8438   }
8439   QualType VarType = LCDecl->getType().getNonReferenceType();
8440   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8441       !SemaRef.getLangOpts().CPlusPlus)
8442     return nullptr;
8443   // Upper - Lower
8444   Expr *Upper = TestIsLessOp.getValue()
8445                     ? Cnt
8446                     : tryBuildCapture(SemaRef, LB, Captures).get();
8447   Expr *Lower = TestIsLessOp.getValue()
8448                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8449                     : Cnt;
8450   if (!Upper || !Lower)
8451     return nullptr;
8452 
8453   ExprResult Diff = calculateNumIters(
8454       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8455       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8456   if (!Diff.isUsable())
8457     return nullptr;
8458 
8459   return Diff.get();
8460 }
8461 } // namespace
8462 
8463 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8464   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8465   assert(Init && "Expected loop in canonical form.");
8466   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8467   if (AssociatedLoops > 0 &&
8468       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8469     DSAStack->loopStart();
8470     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8471                                     *DSAStack, ForLoc);
8472     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8473       if (ValueDecl *D = ISC.getLoopDecl()) {
8474         auto *VD = dyn_cast<VarDecl>(D);
8475         DeclRefExpr *PrivateRef = nullptr;
8476         if (!VD) {
8477           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8478             VD = Private;
8479           } else {
8480             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8481                                       /*WithInit=*/false);
8482             VD = cast<VarDecl>(PrivateRef->getDecl());
8483           }
8484         }
8485         DSAStack->addLoopControlVariable(D, VD);
8486         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8487         if (LD != D->getCanonicalDecl()) {
8488           DSAStack->resetPossibleLoopCounter();
8489           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8490             MarkDeclarationsReferencedInExpr(
8491                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8492                                  Var->getType().getNonLValueExprType(Context),
8493                                  ForLoc, /*RefersToCapture=*/true));
8494         }
8495         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8496         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8497         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8498         // associated for-loop of a simd construct with just one associated
8499         // for-loop may be listed in a linear clause with a constant-linear-step
8500         // that is the increment of the associated for-loop. The loop iteration
8501         // variable(s) in the associated for-loop(s) of a for or parallel for
8502         // construct may be listed in a private or lastprivate clause.
8503         DSAStackTy::DSAVarData DVar =
8504             DSAStack->getTopDSA(D, /*FromParent=*/false);
8505         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8506         // is declared in the loop and it is predetermined as a private.
8507         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8508         OpenMPClauseKind PredeterminedCKind =
8509             isOpenMPSimdDirective(DKind)
8510                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8511                 : OMPC_private;
8512         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8513               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8514               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8515                                          DVar.CKind != OMPC_private))) ||
8516              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8517                DKind == OMPD_master_taskloop ||
8518                DKind == OMPD_parallel_master_taskloop ||
8519                isOpenMPDistributeDirective(DKind)) &&
8520               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8521               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8522             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8523           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8524               << getOpenMPClauseName(DVar.CKind)
8525               << getOpenMPDirectiveName(DKind)
8526               << getOpenMPClauseName(PredeterminedCKind);
8527           if (DVar.RefExpr == nullptr)
8528             DVar.CKind = PredeterminedCKind;
8529           reportOriginalDsa(*this, DSAStack, D, DVar,
8530                             /*IsLoopIterVar=*/true);
8531         } else if (LoopDeclRefExpr) {
8532           // Make the loop iteration variable private (for worksharing
8533           // constructs), linear (for simd directives with the only one
8534           // associated loop) or lastprivate (for simd directives with several
8535           // collapsed or ordered loops).
8536           if (DVar.CKind == OMPC_unknown)
8537             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8538                              PrivateRef);
8539         }
8540       }
8541     }
8542     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8543   }
8544 }
8545 
8546 /// Called on a for stmt to check and extract its iteration space
8547 /// for further processing (such as collapsing).
8548 static bool checkOpenMPIterationSpace(
8549     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8550     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8551     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8552     Expr *OrderedLoopCountExpr,
8553     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8554     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8555     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8556   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8557   // OpenMP [2.9.1, Canonical Loop Form]
8558   //   for (init-expr; test-expr; incr-expr) structured-block
8559   //   for (range-decl: range-expr) structured-block
8560   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8561     S = CanonLoop->getLoopStmt();
8562   auto *For = dyn_cast_or_null<ForStmt>(S);
8563   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8564   // Ranged for is supported only in OpenMP 5.0.
8565   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8566     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8567         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8568         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8569         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8570     if (TotalNestedLoopCount > 1) {
8571       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8572         SemaRef.Diag(DSA.getConstructLoc(),
8573                      diag::note_omp_collapse_ordered_expr)
8574             << 2 << CollapseLoopCountExpr->getSourceRange()
8575             << OrderedLoopCountExpr->getSourceRange();
8576       else if (CollapseLoopCountExpr)
8577         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8578                      diag::note_omp_collapse_ordered_expr)
8579             << 0 << CollapseLoopCountExpr->getSourceRange();
8580       else
8581         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8582                      diag::note_omp_collapse_ordered_expr)
8583             << 1 << OrderedLoopCountExpr->getSourceRange();
8584     }
8585     return true;
8586   }
8587   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8588          "No loop body.");
8589 
8590   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8591                                   For ? For->getForLoc() : CXXFor->getForLoc());
8592 
8593   // Check init.
8594   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8595   if (ISC.checkAndSetInit(Init))
8596     return true;
8597 
8598   bool HasErrors = false;
8599 
8600   // Check loop variable's type.
8601   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8602     // OpenMP [2.6, Canonical Loop Form]
8603     // Var is one of the following:
8604     //   A variable of signed or unsigned integer type.
8605     //   For C++, a variable of a random access iterator type.
8606     //   For C, a variable of a pointer type.
8607     QualType VarType = LCDecl->getType().getNonReferenceType();
8608     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8609         !VarType->isPointerType() &&
8610         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8611       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8612           << SemaRef.getLangOpts().CPlusPlus;
8613       HasErrors = true;
8614     }
8615 
8616     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8617     // a Construct
8618     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8619     // parallel for construct is (are) private.
8620     // The loop iteration variable in the associated for-loop of a simd
8621     // construct with just one associated for-loop is linear with a
8622     // constant-linear-step that is the increment of the associated for-loop.
8623     // Exclude loop var from the list of variables with implicitly defined data
8624     // sharing attributes.
8625     VarsWithImplicitDSA.erase(LCDecl);
8626 
8627     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8628 
8629     // Check test-expr.
8630     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8631 
8632     // Check incr-expr.
8633     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8634   }
8635 
8636   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8637     return HasErrors;
8638 
8639   // Build the loop's iteration space representation.
8640   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8641       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8642   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8643       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8644                              (isOpenMPWorksharingDirective(DKind) ||
8645                               isOpenMPTaskLoopDirective(DKind) ||
8646                               isOpenMPDistributeDirective(DKind) ||
8647                               isOpenMPLoopTransformationDirective(DKind)),
8648                              Captures);
8649   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8650       ISC.buildCounterVar(Captures, DSA);
8651   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8652       ISC.buildPrivateCounterVar();
8653   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8654   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8655   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8656   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8657       ISC.getConditionSrcRange();
8658   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8659       ISC.getIncrementSrcRange();
8660   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8661   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8662       ISC.isStrictTestOp();
8663   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8664            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8665       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8666   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8667       ISC.buildFinalCondition(DSA.getCurScope());
8668   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8669       ISC.doesInitDependOnLC();
8670   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8671       ISC.doesCondDependOnLC();
8672   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8673       ISC.getLoopDependentIdx();
8674 
8675   HasErrors |=
8676       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8677        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8678        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8679        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8680        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8681        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8682   if (!HasErrors && DSA.isOrderedRegion()) {
8683     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8684       if (CurrentNestedLoopCount <
8685           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8686         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8687             CurrentNestedLoopCount,
8688             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8689         DSA.getOrderedRegionParam().second->setLoopCounter(
8690             CurrentNestedLoopCount,
8691             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8692       }
8693     }
8694     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8695       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8696         // Erroneous case - clause has some problems.
8697         continue;
8698       }
8699       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8700           Pair.second.size() <= CurrentNestedLoopCount) {
8701         // Erroneous case - clause has some problems.
8702         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8703         continue;
8704       }
8705       Expr *CntValue;
8706       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8707         CntValue = ISC.buildOrderedLoopData(
8708             DSA.getCurScope(),
8709             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8710             Pair.first->getDependencyLoc());
8711       else
8712         CntValue = ISC.buildOrderedLoopData(
8713             DSA.getCurScope(),
8714             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8715             Pair.first->getDependencyLoc(),
8716             Pair.second[CurrentNestedLoopCount].first,
8717             Pair.second[CurrentNestedLoopCount].second);
8718       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8719     }
8720   }
8721 
8722   return HasErrors;
8723 }
8724 
8725 /// Build 'VarRef = Start.
8726 static ExprResult
8727 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8728                  ExprResult Start, bool IsNonRectangularLB,
8729                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8730   // Build 'VarRef = Start.
8731   ExprResult NewStart = IsNonRectangularLB
8732                             ? Start.get()
8733                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8734   if (!NewStart.isUsable())
8735     return ExprError();
8736   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8737                                    VarRef.get()->getType())) {
8738     NewStart = SemaRef.PerformImplicitConversion(
8739         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8740         /*AllowExplicit=*/true);
8741     if (!NewStart.isUsable())
8742       return ExprError();
8743   }
8744 
8745   ExprResult Init =
8746       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8747   return Init;
8748 }
8749 
8750 /// Build 'VarRef = Start + Iter * Step'.
8751 static ExprResult buildCounterUpdate(
8752     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8753     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8754     bool IsNonRectangularLB,
8755     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8756   // Add parentheses (for debugging purposes only).
8757   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8758   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8759       !Step.isUsable())
8760     return ExprError();
8761 
8762   ExprResult NewStep = Step;
8763   if (Captures)
8764     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8765   if (NewStep.isInvalid())
8766     return ExprError();
8767   ExprResult Update =
8768       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8769   if (!Update.isUsable())
8770     return ExprError();
8771 
8772   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8773   // 'VarRef = Start (+|-) Iter * Step'.
8774   if (!Start.isUsable())
8775     return ExprError();
8776   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8777   if (!NewStart.isUsable())
8778     return ExprError();
8779   if (Captures && !IsNonRectangularLB)
8780     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
8781   if (NewStart.isInvalid())
8782     return ExprError();
8783 
8784   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
8785   ExprResult SavedUpdate = Update;
8786   ExprResult UpdateVal;
8787   if (VarRef.get()->getType()->isOverloadableType() ||
8788       NewStart.get()->getType()->isOverloadableType() ||
8789       Update.get()->getType()->isOverloadableType()) {
8790     Sema::TentativeAnalysisScope Trap(SemaRef);
8791 
8792     Update =
8793         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8794     if (Update.isUsable()) {
8795       UpdateVal =
8796           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
8797                              VarRef.get(), SavedUpdate.get());
8798       if (UpdateVal.isUsable()) {
8799         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
8800                                             UpdateVal.get());
8801       }
8802     }
8803   }
8804 
8805   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
8806   if (!Update.isUsable() || !UpdateVal.isUsable()) {
8807     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
8808                                 NewStart.get(), SavedUpdate.get());
8809     if (!Update.isUsable())
8810       return ExprError();
8811 
8812     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
8813                                      VarRef.get()->getType())) {
8814       Update = SemaRef.PerformImplicitConversion(
8815           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
8816       if (!Update.isUsable())
8817         return ExprError();
8818     }
8819 
8820     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
8821   }
8822   return Update;
8823 }
8824 
8825 /// Convert integer expression \a E to make it have at least \a Bits
8826 /// bits.
8827 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
8828   if (E == nullptr)
8829     return ExprError();
8830   ASTContext &C = SemaRef.Context;
8831   QualType OldType = E->getType();
8832   unsigned HasBits = C.getTypeSize(OldType);
8833   if (HasBits >= Bits)
8834     return ExprResult(E);
8835   // OK to convert to signed, because new type has more bits than old.
8836   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
8837   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
8838                                            true);
8839 }
8840 
8841 /// Check if the given expression \a E is a constant integer that fits
8842 /// into \a Bits bits.
8843 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
8844   if (E == nullptr)
8845     return false;
8846   if (Optional<llvm::APSInt> Result =
8847           E->getIntegerConstantExpr(SemaRef.Context))
8848     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
8849   return false;
8850 }
8851 
8852 /// Build preinits statement for the given declarations.
8853 static Stmt *buildPreInits(ASTContext &Context,
8854                            MutableArrayRef<Decl *> PreInits) {
8855   if (!PreInits.empty()) {
8856     return new (Context) DeclStmt(
8857         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
8858         SourceLocation(), SourceLocation());
8859   }
8860   return nullptr;
8861 }
8862 
8863 /// Build preinits statement for the given declarations.
8864 static Stmt *
8865 buildPreInits(ASTContext &Context,
8866               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8867   if (!Captures.empty()) {
8868     SmallVector<Decl *, 16> PreInits;
8869     for (const auto &Pair : Captures)
8870       PreInits.push_back(Pair.second->getDecl());
8871     return buildPreInits(Context, PreInits);
8872   }
8873   return nullptr;
8874 }
8875 
8876 /// Build postupdate expression for the given list of postupdates expressions.
8877 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
8878   Expr *PostUpdate = nullptr;
8879   if (!PostUpdates.empty()) {
8880     for (Expr *E : PostUpdates) {
8881       Expr *ConvE = S.BuildCStyleCastExpr(
8882                          E->getExprLoc(),
8883                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
8884                          E->getExprLoc(), E)
8885                         .get();
8886       PostUpdate = PostUpdate
8887                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
8888                                               PostUpdate, ConvE)
8889                              .get()
8890                        : ConvE;
8891     }
8892   }
8893   return PostUpdate;
8894 }
8895 
8896 /// Called on a for stmt to check itself and nested loops (if any).
8897 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
8898 /// number of collapsed loops otherwise.
8899 static unsigned
8900 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
8901                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
8902                 DSAStackTy &DSA,
8903                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8904                 OMPLoopBasedDirective::HelperExprs &Built) {
8905   unsigned NestedLoopCount = 1;
8906   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
8907                                     !isOpenMPLoopTransformationDirective(DKind);
8908 
8909   if (CollapseLoopCountExpr) {
8910     // Found 'collapse' clause - calculate collapse number.
8911     Expr::EvalResult Result;
8912     if (!CollapseLoopCountExpr->isValueDependent() &&
8913         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
8914       NestedLoopCount = Result.Val.getInt().getLimitedValue();
8915     } else {
8916       Built.clear(/*Size=*/1);
8917       return 1;
8918     }
8919   }
8920   unsigned OrderedLoopCount = 1;
8921   if (OrderedLoopCountExpr) {
8922     // Found 'ordered' clause - calculate collapse number.
8923     Expr::EvalResult EVResult;
8924     if (!OrderedLoopCountExpr->isValueDependent() &&
8925         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
8926                                             SemaRef.getASTContext())) {
8927       llvm::APSInt Result = EVResult.Val.getInt();
8928       if (Result.getLimitedValue() < NestedLoopCount) {
8929         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8930                      diag::err_omp_wrong_ordered_loop_count)
8931             << OrderedLoopCountExpr->getSourceRange();
8932         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8933                      diag::note_collapse_loop_count)
8934             << CollapseLoopCountExpr->getSourceRange();
8935       }
8936       OrderedLoopCount = Result.getLimitedValue();
8937     } else {
8938       Built.clear(/*Size=*/1);
8939       return 1;
8940     }
8941   }
8942   // This is helper routine for loop directives (e.g., 'for', 'simd',
8943   // 'for simd', etc.).
8944   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8945   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
8946   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
8947   if (!OMPLoopBasedDirective::doForAllLoops(
8948           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
8949           SupportsNonPerfectlyNested, NumLoops,
8950           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
8951            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
8952            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
8953             if (checkOpenMPIterationSpace(
8954                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8955                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
8956                     VarsWithImplicitDSA, IterSpaces, Captures))
8957               return true;
8958             if (Cnt > 0 && Cnt >= NestedLoopCount &&
8959                 IterSpaces[Cnt].CounterVar) {
8960               // Handle initialization of captured loop iterator variables.
8961               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8962               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8963                 Captures[DRE] = DRE;
8964               }
8965             }
8966             return false;
8967           },
8968           [&SemaRef, &Captures](OMPLoopBasedDirective *Transform) {
8969             Stmt *DependentPreInits =
8970                 cast<OMPTileDirective>(Transform)->getPreInits();
8971             if (!DependentPreInits)
8972               return;
8973             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
8974               auto *D = cast<VarDecl>(C);
8975               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
8976                                                   Transform->getBeginLoc());
8977               Captures[Ref] = Ref;
8978             }
8979           }))
8980     return 0;
8981 
8982   Built.clear(/* size */ NestedLoopCount);
8983 
8984   if (SemaRef.CurContext->isDependentContext())
8985     return NestedLoopCount;
8986 
8987   // An example of what is generated for the following code:
8988   //
8989   //   #pragma omp simd collapse(2) ordered(2)
8990   //   for (i = 0; i < NI; ++i)
8991   //     for (k = 0; k < NK; ++k)
8992   //       for (j = J0; j < NJ; j+=2) {
8993   //         <loop body>
8994   //       }
8995   //
8996   // We generate the code below.
8997   // Note: the loop body may be outlined in CodeGen.
8998   // Note: some counters may be C++ classes, operator- is used to find number of
8999   // iterations and operator+= to calculate counter value.
9000   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9001   // or i64 is currently supported).
9002   //
9003   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9004   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9005   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9006   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9007   //     // similar updates for vars in clauses (e.g. 'linear')
9008   //     <loop body (using local i and j)>
9009   //   }
9010   //   i = NI; // assign final values of counters
9011   //   j = NJ;
9012   //
9013 
9014   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9015   // the iteration counts of the collapsed for loops.
9016   // Precondition tests if there is at least one iteration (all conditions are
9017   // true).
9018   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9019   Expr *N0 = IterSpaces[0].NumIterations;
9020   ExprResult LastIteration32 =
9021       widenIterationCount(/*Bits=*/32,
9022                           SemaRef
9023                               .PerformImplicitConversion(
9024                                   N0->IgnoreImpCasts(), N0->getType(),
9025                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9026                               .get(),
9027                           SemaRef);
9028   ExprResult LastIteration64 = widenIterationCount(
9029       /*Bits=*/64,
9030       SemaRef
9031           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9032                                      Sema::AA_Converting,
9033                                      /*AllowExplicit=*/true)
9034           .get(),
9035       SemaRef);
9036 
9037   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9038     return NestedLoopCount;
9039 
9040   ASTContext &C = SemaRef.Context;
9041   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9042 
9043   Scope *CurScope = DSA.getCurScope();
9044   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9045     if (PreCond.isUsable()) {
9046       PreCond =
9047           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9048                              PreCond.get(), IterSpaces[Cnt].PreCond);
9049     }
9050     Expr *N = IterSpaces[Cnt].NumIterations;
9051     SourceLocation Loc = N->getExprLoc();
9052     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9053     if (LastIteration32.isUsable())
9054       LastIteration32 = SemaRef.BuildBinOp(
9055           CurScope, Loc, BO_Mul, LastIteration32.get(),
9056           SemaRef
9057               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9058                                          Sema::AA_Converting,
9059                                          /*AllowExplicit=*/true)
9060               .get());
9061     if (LastIteration64.isUsable())
9062       LastIteration64 = SemaRef.BuildBinOp(
9063           CurScope, Loc, BO_Mul, LastIteration64.get(),
9064           SemaRef
9065               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9066                                          Sema::AA_Converting,
9067                                          /*AllowExplicit=*/true)
9068               .get());
9069   }
9070 
9071   // Choose either the 32-bit or 64-bit version.
9072   ExprResult LastIteration = LastIteration64;
9073   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9074       (LastIteration32.isUsable() &&
9075        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9076        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9077         fitsInto(
9078             /*Bits=*/32,
9079             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9080             LastIteration64.get(), SemaRef))))
9081     LastIteration = LastIteration32;
9082   QualType VType = LastIteration.get()->getType();
9083   QualType RealVType = VType;
9084   QualType StrideVType = VType;
9085   if (isOpenMPTaskLoopDirective(DKind)) {
9086     VType =
9087         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9088     StrideVType =
9089         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9090   }
9091 
9092   if (!LastIteration.isUsable())
9093     return 0;
9094 
9095   // Save the number of iterations.
9096   ExprResult NumIterations = LastIteration;
9097   {
9098     LastIteration = SemaRef.BuildBinOp(
9099         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9100         LastIteration.get(),
9101         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9102     if (!LastIteration.isUsable())
9103       return 0;
9104   }
9105 
9106   // Calculate the last iteration number beforehand instead of doing this on
9107   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9108   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9109   ExprResult CalcLastIteration;
9110   if (!IsConstant) {
9111     ExprResult SaveRef =
9112         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9113     LastIteration = SaveRef;
9114 
9115     // Prepare SaveRef + 1.
9116     NumIterations = SemaRef.BuildBinOp(
9117         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9118         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9119     if (!NumIterations.isUsable())
9120       return 0;
9121   }
9122 
9123   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9124 
9125   // Build variables passed into runtime, necessary for worksharing directives.
9126   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9127   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9128       isOpenMPDistributeDirective(DKind) ||
9129       isOpenMPLoopTransformationDirective(DKind)) {
9130     // Lower bound variable, initialized with zero.
9131     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9132     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9133     SemaRef.AddInitializerToDecl(LBDecl,
9134                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9135                                  /*DirectInit*/ false);
9136 
9137     // Upper bound variable, initialized with last iteration number.
9138     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9139     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9140     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9141                                  /*DirectInit*/ false);
9142 
9143     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9144     // This will be used to implement clause 'lastprivate'.
9145     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9146     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9147     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9148     SemaRef.AddInitializerToDecl(ILDecl,
9149                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9150                                  /*DirectInit*/ false);
9151 
9152     // Stride variable returned by runtime (we initialize it to 1 by default).
9153     VarDecl *STDecl =
9154         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9155     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9156     SemaRef.AddInitializerToDecl(STDecl,
9157                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9158                                  /*DirectInit*/ false);
9159 
9160     // Build expression: UB = min(UB, LastIteration)
9161     // It is necessary for CodeGen of directives with static scheduling.
9162     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9163                                                 UB.get(), LastIteration.get());
9164     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9165         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9166         LastIteration.get(), UB.get());
9167     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9168                              CondOp.get());
9169     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9170 
9171     // If we have a combined directive that combines 'distribute', 'for' or
9172     // 'simd' we need to be able to access the bounds of the schedule of the
9173     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9174     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9175     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9176       // Lower bound variable, initialized with zero.
9177       VarDecl *CombLBDecl =
9178           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9179       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9180       SemaRef.AddInitializerToDecl(
9181           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9182           /*DirectInit*/ false);
9183 
9184       // Upper bound variable, initialized with last iteration number.
9185       VarDecl *CombUBDecl =
9186           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9187       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9188       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9189                                    /*DirectInit*/ false);
9190 
9191       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9192           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9193       ExprResult CombCondOp =
9194           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9195                                      LastIteration.get(), CombUB.get());
9196       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9197                                    CombCondOp.get());
9198       CombEUB =
9199           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9200 
9201       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9202       // We expect to have at least 2 more parameters than the 'parallel'
9203       // directive does - the lower and upper bounds of the previous schedule.
9204       assert(CD->getNumParams() >= 4 &&
9205              "Unexpected number of parameters in loop combined directive");
9206 
9207       // Set the proper type for the bounds given what we learned from the
9208       // enclosed loops.
9209       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9210       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9211 
9212       // Previous lower and upper bounds are obtained from the region
9213       // parameters.
9214       PrevLB =
9215           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9216       PrevUB =
9217           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9218     }
9219   }
9220 
9221   // Build the iteration variable and its initialization before loop.
9222   ExprResult IV;
9223   ExprResult Init, CombInit;
9224   {
9225     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9226     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9227     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9228                  isOpenMPTaskLoopDirective(DKind) ||
9229                  isOpenMPDistributeDirective(DKind) ||
9230                  isOpenMPLoopTransformationDirective(DKind))
9231                     ? LB.get()
9232                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9233     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9234     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9235 
9236     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9237       Expr *CombRHS =
9238           (isOpenMPWorksharingDirective(DKind) ||
9239            isOpenMPTaskLoopDirective(DKind) ||
9240            isOpenMPDistributeDirective(DKind))
9241               ? CombLB.get()
9242               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9243       CombInit =
9244           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9245       CombInit =
9246           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9247     }
9248   }
9249 
9250   bool UseStrictCompare =
9251       RealVType->hasUnsignedIntegerRepresentation() &&
9252       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9253         return LIS.IsStrictCompare;
9254       });
9255   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9256   // unsigned IV)) for worksharing loops.
9257   SourceLocation CondLoc = AStmt->getBeginLoc();
9258   Expr *BoundUB = UB.get();
9259   if (UseStrictCompare) {
9260     BoundUB =
9261         SemaRef
9262             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9263                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9264             .get();
9265     BoundUB =
9266         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9267   }
9268   ExprResult Cond =
9269       (isOpenMPWorksharingDirective(DKind) ||
9270        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9271        isOpenMPLoopTransformationDirective(DKind))
9272           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9273                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9274                                BoundUB)
9275           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9276                                NumIterations.get());
9277   ExprResult CombDistCond;
9278   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9279     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9280                                       NumIterations.get());
9281   }
9282 
9283   ExprResult CombCond;
9284   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9285     Expr *BoundCombUB = CombUB.get();
9286     if (UseStrictCompare) {
9287       BoundCombUB =
9288           SemaRef
9289               .BuildBinOp(
9290                   CurScope, CondLoc, BO_Add, BoundCombUB,
9291                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9292               .get();
9293       BoundCombUB =
9294           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9295               .get();
9296     }
9297     CombCond =
9298         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9299                            IV.get(), BoundCombUB);
9300   }
9301   // Loop increment (IV = IV + 1)
9302   SourceLocation IncLoc = AStmt->getBeginLoc();
9303   ExprResult Inc =
9304       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9305                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9306   if (!Inc.isUsable())
9307     return 0;
9308   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9309   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9310   if (!Inc.isUsable())
9311     return 0;
9312 
9313   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9314   // Used for directives with static scheduling.
9315   // In combined construct, add combined version that use CombLB and CombUB
9316   // base variables for the update
9317   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9318   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9319       isOpenMPDistributeDirective(DKind) ||
9320       isOpenMPLoopTransformationDirective(DKind)) {
9321     // LB + ST
9322     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9323     if (!NextLB.isUsable())
9324       return 0;
9325     // LB = LB + ST
9326     NextLB =
9327         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9328     NextLB =
9329         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9330     if (!NextLB.isUsable())
9331       return 0;
9332     // UB + ST
9333     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9334     if (!NextUB.isUsable())
9335       return 0;
9336     // UB = UB + ST
9337     NextUB =
9338         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9339     NextUB =
9340         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9341     if (!NextUB.isUsable())
9342       return 0;
9343     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9344       CombNextLB =
9345           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9346       if (!NextLB.isUsable())
9347         return 0;
9348       // LB = LB + ST
9349       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9350                                       CombNextLB.get());
9351       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9352                                                /*DiscardedValue*/ false);
9353       if (!CombNextLB.isUsable())
9354         return 0;
9355       // UB + ST
9356       CombNextUB =
9357           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9358       if (!CombNextUB.isUsable())
9359         return 0;
9360       // UB = UB + ST
9361       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9362                                       CombNextUB.get());
9363       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9364                                                /*DiscardedValue*/ false);
9365       if (!CombNextUB.isUsable())
9366         return 0;
9367     }
9368   }
9369 
9370   // Create increment expression for distribute loop when combined in a same
9371   // directive with for as IV = IV + ST; ensure upper bound expression based
9372   // on PrevUB instead of NumIterations - used to implement 'for' when found
9373   // in combination with 'distribute', like in 'distribute parallel for'
9374   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9375   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9376   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9377     DistCond = SemaRef.BuildBinOp(
9378         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9379     assert(DistCond.isUsable() && "distribute cond expr was not built");
9380 
9381     DistInc =
9382         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9383     assert(DistInc.isUsable() && "distribute inc expr was not built");
9384     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9385                                  DistInc.get());
9386     DistInc =
9387         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9388     assert(DistInc.isUsable() && "distribute inc expr was not built");
9389 
9390     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9391     // construct
9392     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9393     ExprResult IsUBGreater =
9394         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
9395     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9396         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
9397     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9398                                  CondOp.get());
9399     PrevEUB =
9400         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9401 
9402     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9403     // parallel for is in combination with a distribute directive with
9404     // schedule(static, 1)
9405     Expr *BoundPrevUB = PrevUB.get();
9406     if (UseStrictCompare) {
9407       BoundPrevUB =
9408           SemaRef
9409               .BuildBinOp(
9410                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9411                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9412               .get();
9413       BoundPrevUB =
9414           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9415               .get();
9416     }
9417     ParForInDistCond =
9418         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9419                            IV.get(), BoundPrevUB);
9420   }
9421 
9422   // Build updates and final values of the loop counters.
9423   bool HasErrors = false;
9424   Built.Counters.resize(NestedLoopCount);
9425   Built.Inits.resize(NestedLoopCount);
9426   Built.Updates.resize(NestedLoopCount);
9427   Built.Finals.resize(NestedLoopCount);
9428   Built.DependentCounters.resize(NestedLoopCount);
9429   Built.DependentInits.resize(NestedLoopCount);
9430   Built.FinalsConditions.resize(NestedLoopCount);
9431   {
9432     // We implement the following algorithm for obtaining the
9433     // original loop iteration variable values based on the
9434     // value of the collapsed loop iteration variable IV.
9435     //
9436     // Let n+1 be the number of collapsed loops in the nest.
9437     // Iteration variables (I0, I1, .... In)
9438     // Iteration counts (N0, N1, ... Nn)
9439     //
9440     // Acc = IV;
9441     //
9442     // To compute Ik for loop k, 0 <= k <= n, generate:
9443     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9444     //    Ik = Acc / Prod;
9445     //    Acc -= Ik * Prod;
9446     //
9447     ExprResult Acc = IV;
9448     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9449       LoopIterationSpace &IS = IterSpaces[Cnt];
9450       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9451       ExprResult Iter;
9452 
9453       // Compute prod
9454       ExprResult Prod =
9455           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9456       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
9457         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9458                                   IterSpaces[K].NumIterations);
9459 
9460       // Iter = Acc / Prod
9461       // If there is at least one more inner loop to avoid
9462       // multiplication by 1.
9463       if (Cnt + 1 < NestedLoopCount)
9464         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
9465                                   Acc.get(), Prod.get());
9466       else
9467         Iter = Acc;
9468       if (!Iter.isUsable()) {
9469         HasErrors = true;
9470         break;
9471       }
9472 
9473       // Update Acc:
9474       // Acc -= Iter * Prod
9475       // Check if there is at least one more inner loop to avoid
9476       // multiplication by 1.
9477       if (Cnt + 1 < NestedLoopCount)
9478         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
9479                                   Iter.get(), Prod.get());
9480       else
9481         Prod = Iter;
9482       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
9483                                Acc.get(), Prod.get());
9484 
9485       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9486       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9487       DeclRefExpr *CounterVar = buildDeclRefExpr(
9488           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9489           /*RefersToCapture=*/true);
9490       ExprResult Init =
9491           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9492                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9493       if (!Init.isUsable()) {
9494         HasErrors = true;
9495         break;
9496       }
9497       ExprResult Update = buildCounterUpdate(
9498           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9499           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9500       if (!Update.isUsable()) {
9501         HasErrors = true;
9502         break;
9503       }
9504 
9505       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9506       ExprResult Final =
9507           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9508                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9509                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9510       if (!Final.isUsable()) {
9511         HasErrors = true;
9512         break;
9513       }
9514 
9515       if (!Update.isUsable() || !Final.isUsable()) {
9516         HasErrors = true;
9517         break;
9518       }
9519       // Save results
9520       Built.Counters[Cnt] = IS.CounterVar;
9521       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9522       Built.Inits[Cnt] = Init.get();
9523       Built.Updates[Cnt] = Update.get();
9524       Built.Finals[Cnt] = Final.get();
9525       Built.DependentCounters[Cnt] = nullptr;
9526       Built.DependentInits[Cnt] = nullptr;
9527       Built.FinalsConditions[Cnt] = nullptr;
9528       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9529         Built.DependentCounters[Cnt] =
9530             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9531         Built.DependentInits[Cnt] =
9532             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9533         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9534       }
9535     }
9536   }
9537 
9538   if (HasErrors)
9539     return 0;
9540 
9541   // Save results
9542   Built.IterationVarRef = IV.get();
9543   Built.LastIteration = LastIteration.get();
9544   Built.NumIterations = NumIterations.get();
9545   Built.CalcLastIteration = SemaRef
9546                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9547                                                      /*DiscardedValue=*/false)
9548                                 .get();
9549   Built.PreCond = PreCond.get();
9550   Built.PreInits = buildPreInits(C, Captures);
9551   Built.Cond = Cond.get();
9552   Built.Init = Init.get();
9553   Built.Inc = Inc.get();
9554   Built.LB = LB.get();
9555   Built.UB = UB.get();
9556   Built.IL = IL.get();
9557   Built.ST = ST.get();
9558   Built.EUB = EUB.get();
9559   Built.NLB = NextLB.get();
9560   Built.NUB = NextUB.get();
9561   Built.PrevLB = PrevLB.get();
9562   Built.PrevUB = PrevUB.get();
9563   Built.DistInc = DistInc.get();
9564   Built.PrevEUB = PrevEUB.get();
9565   Built.DistCombinedFields.LB = CombLB.get();
9566   Built.DistCombinedFields.UB = CombUB.get();
9567   Built.DistCombinedFields.EUB = CombEUB.get();
9568   Built.DistCombinedFields.Init = CombInit.get();
9569   Built.DistCombinedFields.Cond = CombCond.get();
9570   Built.DistCombinedFields.NLB = CombNextLB.get();
9571   Built.DistCombinedFields.NUB = CombNextUB.get();
9572   Built.DistCombinedFields.DistCond = CombDistCond.get();
9573   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9574 
9575   return NestedLoopCount;
9576 }
9577 
9578 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9579   auto CollapseClauses =
9580       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9581   if (CollapseClauses.begin() != CollapseClauses.end())
9582     return (*CollapseClauses.begin())->getNumForLoops();
9583   return nullptr;
9584 }
9585 
9586 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9587   auto OrderedClauses =
9588       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9589   if (OrderedClauses.begin() != OrderedClauses.end())
9590     return (*OrderedClauses.begin())->getNumForLoops();
9591   return nullptr;
9592 }
9593 
9594 static bool checkSimdlenSafelenSpecified(Sema &S,
9595                                          const ArrayRef<OMPClause *> Clauses) {
9596   const OMPSafelenClause *Safelen = nullptr;
9597   const OMPSimdlenClause *Simdlen = nullptr;
9598 
9599   for (const OMPClause *Clause : Clauses) {
9600     if (Clause->getClauseKind() == OMPC_safelen)
9601       Safelen = cast<OMPSafelenClause>(Clause);
9602     else if (Clause->getClauseKind() == OMPC_simdlen)
9603       Simdlen = cast<OMPSimdlenClause>(Clause);
9604     if (Safelen && Simdlen)
9605       break;
9606   }
9607 
9608   if (Simdlen && Safelen) {
9609     const Expr *SimdlenLength = Simdlen->getSimdlen();
9610     const Expr *SafelenLength = Safelen->getSafelen();
9611     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9612         SimdlenLength->isInstantiationDependent() ||
9613         SimdlenLength->containsUnexpandedParameterPack())
9614       return false;
9615     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9616         SafelenLength->isInstantiationDependent() ||
9617         SafelenLength->containsUnexpandedParameterPack())
9618       return false;
9619     Expr::EvalResult SimdlenResult, SafelenResult;
9620     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9621     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9622     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9623     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9624     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9625     // If both simdlen and safelen clauses are specified, the value of the
9626     // simdlen parameter must be less than or equal to the value of the safelen
9627     // parameter.
9628     if (SimdlenRes > SafelenRes) {
9629       S.Diag(SimdlenLength->getExprLoc(),
9630              diag::err_omp_wrong_simdlen_safelen_values)
9631           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9632       return true;
9633     }
9634   }
9635   return false;
9636 }
9637 
9638 StmtResult
9639 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9640                                SourceLocation StartLoc, SourceLocation EndLoc,
9641                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9642   if (!AStmt)
9643     return StmtError();
9644 
9645   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9646   OMPLoopBasedDirective::HelperExprs B;
9647   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9648   // define the nested loops number.
9649   unsigned NestedLoopCount = checkOpenMPLoop(
9650       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9651       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9652   if (NestedLoopCount == 0)
9653     return StmtError();
9654 
9655   assert((CurContext->isDependentContext() || B.builtAll()) &&
9656          "omp simd loop exprs were not built");
9657 
9658   if (!CurContext->isDependentContext()) {
9659     // Finalize the clauses that need pre-built expressions for CodeGen.
9660     for (OMPClause *C : Clauses) {
9661       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9662         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9663                                      B.NumIterations, *this, CurScope,
9664                                      DSAStack))
9665           return StmtError();
9666     }
9667   }
9668 
9669   if (checkSimdlenSafelenSpecified(*this, Clauses))
9670     return StmtError();
9671 
9672   setFunctionHasBranchProtectedScope();
9673   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9674                                   Clauses, AStmt, B);
9675 }
9676 
9677 StmtResult
9678 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9679                               SourceLocation StartLoc, SourceLocation EndLoc,
9680                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9681   if (!AStmt)
9682     return StmtError();
9683 
9684   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9685   OMPLoopBasedDirective::HelperExprs B;
9686   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9687   // define the nested loops number.
9688   unsigned NestedLoopCount = checkOpenMPLoop(
9689       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9690       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9691   if (NestedLoopCount == 0)
9692     return StmtError();
9693 
9694   assert((CurContext->isDependentContext() || B.builtAll()) &&
9695          "omp for loop exprs were not built");
9696 
9697   if (!CurContext->isDependentContext()) {
9698     // Finalize the clauses that need pre-built expressions for CodeGen.
9699     for (OMPClause *C : Clauses) {
9700       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9701         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9702                                      B.NumIterations, *this, CurScope,
9703                                      DSAStack))
9704           return StmtError();
9705     }
9706   }
9707 
9708   setFunctionHasBranchProtectedScope();
9709   return OMPForDirective::Create(
9710       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9711       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9712 }
9713 
9714 StmtResult Sema::ActOnOpenMPForSimdDirective(
9715     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9716     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9717   if (!AStmt)
9718     return StmtError();
9719 
9720   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9721   OMPLoopBasedDirective::HelperExprs B;
9722   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9723   // define the nested loops number.
9724   unsigned NestedLoopCount =
9725       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9726                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9727                       VarsWithImplicitDSA, B);
9728   if (NestedLoopCount == 0)
9729     return StmtError();
9730 
9731   assert((CurContext->isDependentContext() || B.builtAll()) &&
9732          "omp for simd loop exprs were not built");
9733 
9734   if (!CurContext->isDependentContext()) {
9735     // Finalize the clauses that need pre-built expressions for CodeGen.
9736     for (OMPClause *C : Clauses) {
9737       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9738         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9739                                      B.NumIterations, *this, CurScope,
9740                                      DSAStack))
9741           return StmtError();
9742     }
9743   }
9744 
9745   if (checkSimdlenSafelenSpecified(*this, Clauses))
9746     return StmtError();
9747 
9748   setFunctionHasBranchProtectedScope();
9749   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9750                                      Clauses, AStmt, B);
9751 }
9752 
9753 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9754                                               Stmt *AStmt,
9755                                               SourceLocation StartLoc,
9756                                               SourceLocation EndLoc) {
9757   if (!AStmt)
9758     return StmtError();
9759 
9760   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9761   auto BaseStmt = AStmt;
9762   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9763     BaseStmt = CS->getCapturedStmt();
9764   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9765     auto S = C->children();
9766     if (S.begin() == S.end())
9767       return StmtError();
9768     // All associated statements must be '#pragma omp section' except for
9769     // the first one.
9770     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9771       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9772         if (SectionStmt)
9773           Diag(SectionStmt->getBeginLoc(),
9774                diag::err_omp_sections_substmt_not_section);
9775         return StmtError();
9776       }
9777       cast<OMPSectionDirective>(SectionStmt)
9778           ->setHasCancel(DSAStack->isCancelRegion());
9779     }
9780   } else {
9781     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
9782     return StmtError();
9783   }
9784 
9785   setFunctionHasBranchProtectedScope();
9786 
9787   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9788                                       DSAStack->getTaskgroupReductionRef(),
9789                                       DSAStack->isCancelRegion());
9790 }
9791 
9792 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
9793                                              SourceLocation StartLoc,
9794                                              SourceLocation EndLoc) {
9795   if (!AStmt)
9796     return StmtError();
9797 
9798   setFunctionHasBranchProtectedScope();
9799   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
9800 
9801   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
9802                                      DSAStack->isCancelRegion());
9803 }
9804 
9805 static Expr *getDirectCallExpr(Expr *E) {
9806   E = E->IgnoreParenCasts()->IgnoreImplicit();
9807   if (auto *CE = dyn_cast<CallExpr>(E))
9808     if (CE->getDirectCallee())
9809       return E;
9810   return nullptr;
9811 }
9812 
9813 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
9814                                               Stmt *AStmt,
9815                                               SourceLocation StartLoc,
9816                                               SourceLocation EndLoc) {
9817   if (!AStmt)
9818     return StmtError();
9819 
9820   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
9821 
9822   // 5.1 OpenMP
9823   // expression-stmt : an expression statement with one of the following forms:
9824   //   expression = target-call ( [expression-list] );
9825   //   target-call ( [expression-list] );
9826 
9827   SourceLocation TargetCallLoc;
9828 
9829   if (!CurContext->isDependentContext()) {
9830     Expr *TargetCall = nullptr;
9831 
9832     auto *E = dyn_cast<Expr>(S);
9833     if (!E) {
9834       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9835       return StmtError();
9836     }
9837 
9838     E = E->IgnoreParenCasts()->IgnoreImplicit();
9839 
9840     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
9841       if (BO->getOpcode() == BO_Assign)
9842         TargetCall = getDirectCallExpr(BO->getRHS());
9843     } else {
9844       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
9845         if (COCE->getOperator() == OO_Equal)
9846           TargetCall = getDirectCallExpr(COCE->getArg(1));
9847       if (!TargetCall)
9848         TargetCall = getDirectCallExpr(E);
9849     }
9850     if (!TargetCall) {
9851       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9852       return StmtError();
9853     }
9854     TargetCallLoc = TargetCall->getExprLoc();
9855   }
9856 
9857   setFunctionHasBranchProtectedScope();
9858 
9859   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9860                                       TargetCallLoc);
9861 }
9862 
9863 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9864                                             Stmt *AStmt,
9865                                             SourceLocation StartLoc,
9866                                             SourceLocation EndLoc) {
9867   if (!AStmt)
9868     return StmtError();
9869 
9870   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9871 
9872   setFunctionHasBranchProtectedScope();
9873 
9874   // OpenMP [2.7.3, single Construct, Restrictions]
9875   // The copyprivate clause must not be used with the nowait clause.
9876   const OMPClause *Nowait = nullptr;
9877   const OMPClause *Copyprivate = nullptr;
9878   for (const OMPClause *Clause : Clauses) {
9879     if (Clause->getClauseKind() == OMPC_nowait)
9880       Nowait = Clause;
9881     else if (Clause->getClauseKind() == OMPC_copyprivate)
9882       Copyprivate = Clause;
9883     if (Copyprivate && Nowait) {
9884       Diag(Copyprivate->getBeginLoc(),
9885            diag::err_omp_single_copyprivate_with_nowait);
9886       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
9887       return StmtError();
9888     }
9889   }
9890 
9891   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9892 }
9893 
9894 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
9895                                             SourceLocation StartLoc,
9896                                             SourceLocation EndLoc) {
9897   if (!AStmt)
9898     return StmtError();
9899 
9900   setFunctionHasBranchProtectedScope();
9901 
9902   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
9903 }
9904 
9905 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
9906                                             Stmt *AStmt,
9907                                             SourceLocation StartLoc,
9908                                             SourceLocation EndLoc) {
9909   if (!AStmt)
9910     return StmtError();
9911 
9912   setFunctionHasBranchProtectedScope();
9913 
9914   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9915 }
9916 
9917 StmtResult Sema::ActOnOpenMPCriticalDirective(
9918     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
9919     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
9920   if (!AStmt)
9921     return StmtError();
9922 
9923   bool ErrorFound = false;
9924   llvm::APSInt Hint;
9925   SourceLocation HintLoc;
9926   bool DependentHint = false;
9927   for (const OMPClause *C : Clauses) {
9928     if (C->getClauseKind() == OMPC_hint) {
9929       if (!DirName.getName()) {
9930         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
9931         ErrorFound = true;
9932       }
9933       Expr *E = cast<OMPHintClause>(C)->getHint();
9934       if (E->isTypeDependent() || E->isValueDependent() ||
9935           E->isInstantiationDependent()) {
9936         DependentHint = true;
9937       } else {
9938         Hint = E->EvaluateKnownConstInt(Context);
9939         HintLoc = C->getBeginLoc();
9940       }
9941     }
9942   }
9943   if (ErrorFound)
9944     return StmtError();
9945   const auto Pair = DSAStack->getCriticalWithHint(DirName);
9946   if (Pair.first && DirName.getName() && !DependentHint) {
9947     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
9948       Diag(StartLoc, diag::err_omp_critical_with_hint);
9949       if (HintLoc.isValid())
9950         Diag(HintLoc, diag::note_omp_critical_hint_here)
9951             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
9952       else
9953         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
9954       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
9955         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
9956             << 1
9957             << C->getHint()->EvaluateKnownConstInt(Context).toString(
9958                    /*Radix=*/10, /*Signed=*/false);
9959       } else {
9960         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
9961       }
9962     }
9963   }
9964 
9965   setFunctionHasBranchProtectedScope();
9966 
9967   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
9968                                            Clauses, AStmt);
9969   if (!Pair.first && DirName.getName() && !DependentHint)
9970     DSAStack->addCriticalWithHint(Dir, Hint);
9971   return Dir;
9972 }
9973 
9974 StmtResult Sema::ActOnOpenMPParallelForDirective(
9975     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9976     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9977   if (!AStmt)
9978     return StmtError();
9979 
9980   auto *CS = cast<CapturedStmt>(AStmt);
9981   // 1.2.2 OpenMP Language Terminology
9982   // Structured block - An executable statement with a single entry at the
9983   // top and a single exit at the bottom.
9984   // The point of exit cannot be a branch out of the structured block.
9985   // longjmp() and throw() must not violate the entry/exit criteria.
9986   CS->getCapturedDecl()->setNothrow();
9987 
9988   OMPLoopBasedDirective::HelperExprs B;
9989   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9990   // define the nested loops number.
9991   unsigned NestedLoopCount =
9992       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
9993                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9994                       VarsWithImplicitDSA, B);
9995   if (NestedLoopCount == 0)
9996     return StmtError();
9997 
9998   assert((CurContext->isDependentContext() || B.builtAll()) &&
9999          "omp parallel for loop exprs were not built");
10000 
10001   if (!CurContext->isDependentContext()) {
10002     // Finalize the clauses that need pre-built expressions for CodeGen.
10003     for (OMPClause *C : Clauses) {
10004       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10005         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10006                                      B.NumIterations, *this, CurScope,
10007                                      DSAStack))
10008           return StmtError();
10009     }
10010   }
10011 
10012   setFunctionHasBranchProtectedScope();
10013   return OMPParallelForDirective::Create(
10014       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10015       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10016 }
10017 
10018 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10019     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10020     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10021   if (!AStmt)
10022     return StmtError();
10023 
10024   auto *CS = cast<CapturedStmt>(AStmt);
10025   // 1.2.2 OpenMP Language Terminology
10026   // Structured block - An executable statement with a single entry at the
10027   // top and a single exit at the bottom.
10028   // The point of exit cannot be a branch out of the structured block.
10029   // longjmp() and throw() must not violate the entry/exit criteria.
10030   CS->getCapturedDecl()->setNothrow();
10031 
10032   OMPLoopBasedDirective::HelperExprs B;
10033   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10034   // define the nested loops number.
10035   unsigned NestedLoopCount =
10036       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10037                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10038                       VarsWithImplicitDSA, B);
10039   if (NestedLoopCount == 0)
10040     return StmtError();
10041 
10042   if (!CurContext->isDependentContext()) {
10043     // Finalize the clauses that need pre-built expressions for CodeGen.
10044     for (OMPClause *C : Clauses) {
10045       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10046         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10047                                      B.NumIterations, *this, CurScope,
10048                                      DSAStack))
10049           return StmtError();
10050     }
10051   }
10052 
10053   if (checkSimdlenSafelenSpecified(*this, Clauses))
10054     return StmtError();
10055 
10056   setFunctionHasBranchProtectedScope();
10057   return OMPParallelForSimdDirective::Create(
10058       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10059 }
10060 
10061 StmtResult
10062 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10063                                          Stmt *AStmt, SourceLocation StartLoc,
10064                                          SourceLocation EndLoc) {
10065   if (!AStmt)
10066     return StmtError();
10067 
10068   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10069   auto *CS = cast<CapturedStmt>(AStmt);
10070   // 1.2.2 OpenMP Language Terminology
10071   // Structured block - An executable statement with a single entry at the
10072   // top and a single exit at the bottom.
10073   // The point of exit cannot be a branch out of the structured block.
10074   // longjmp() and throw() must not violate the entry/exit criteria.
10075   CS->getCapturedDecl()->setNothrow();
10076 
10077   setFunctionHasBranchProtectedScope();
10078 
10079   return OMPParallelMasterDirective::Create(
10080       Context, StartLoc, EndLoc, Clauses, AStmt,
10081       DSAStack->getTaskgroupReductionRef());
10082 }
10083 
10084 StmtResult
10085 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10086                                            Stmt *AStmt, SourceLocation StartLoc,
10087                                            SourceLocation EndLoc) {
10088   if (!AStmt)
10089     return StmtError();
10090 
10091   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10092   auto BaseStmt = AStmt;
10093   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10094     BaseStmt = CS->getCapturedStmt();
10095   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10096     auto S = C->children();
10097     if (S.begin() == S.end())
10098       return StmtError();
10099     // All associated statements must be '#pragma omp section' except for
10100     // the first one.
10101     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10102       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10103         if (SectionStmt)
10104           Diag(SectionStmt->getBeginLoc(),
10105                diag::err_omp_parallel_sections_substmt_not_section);
10106         return StmtError();
10107       }
10108       cast<OMPSectionDirective>(SectionStmt)
10109           ->setHasCancel(DSAStack->isCancelRegion());
10110     }
10111   } else {
10112     Diag(AStmt->getBeginLoc(),
10113          diag::err_omp_parallel_sections_not_compound_stmt);
10114     return StmtError();
10115   }
10116 
10117   setFunctionHasBranchProtectedScope();
10118 
10119   return OMPParallelSectionsDirective::Create(
10120       Context, StartLoc, EndLoc, Clauses, AStmt,
10121       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10122 }
10123 
10124 /// detach and mergeable clauses are mutially exclusive, check for it.
10125 static bool checkDetachMergeableClauses(Sema &S,
10126                                         ArrayRef<OMPClause *> Clauses) {
10127   const OMPClause *PrevClause = nullptr;
10128   bool ErrorFound = false;
10129   for (const OMPClause *C : Clauses) {
10130     if (C->getClauseKind() == OMPC_detach ||
10131         C->getClauseKind() == OMPC_mergeable) {
10132       if (!PrevClause) {
10133         PrevClause = C;
10134       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10135         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10136             << getOpenMPClauseName(C->getClauseKind())
10137             << getOpenMPClauseName(PrevClause->getClauseKind());
10138         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10139             << getOpenMPClauseName(PrevClause->getClauseKind());
10140         ErrorFound = true;
10141       }
10142     }
10143   }
10144   return ErrorFound;
10145 }
10146 
10147 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10148                                           Stmt *AStmt, SourceLocation StartLoc,
10149                                           SourceLocation EndLoc) {
10150   if (!AStmt)
10151     return StmtError();
10152 
10153   // OpenMP 5.0, 2.10.1 task Construct
10154   // If a detach clause appears on the directive, then a mergeable clause cannot
10155   // appear on the same directive.
10156   if (checkDetachMergeableClauses(*this, Clauses))
10157     return StmtError();
10158 
10159   auto *CS = cast<CapturedStmt>(AStmt);
10160   // 1.2.2 OpenMP Language Terminology
10161   // Structured block - An executable statement with a single entry at the
10162   // top and a single exit at the bottom.
10163   // The point of exit cannot be a branch out of the structured block.
10164   // longjmp() and throw() must not violate the entry/exit criteria.
10165   CS->getCapturedDecl()->setNothrow();
10166 
10167   setFunctionHasBranchProtectedScope();
10168 
10169   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10170                                   DSAStack->isCancelRegion());
10171 }
10172 
10173 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10174                                                SourceLocation EndLoc) {
10175   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10176 }
10177 
10178 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10179                                              SourceLocation EndLoc) {
10180   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10181 }
10182 
10183 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10184                                               SourceLocation EndLoc) {
10185   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
10186 }
10187 
10188 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10189                                                Stmt *AStmt,
10190                                                SourceLocation StartLoc,
10191                                                SourceLocation EndLoc) {
10192   if (!AStmt)
10193     return StmtError();
10194 
10195   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10196 
10197   setFunctionHasBranchProtectedScope();
10198 
10199   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10200                                        AStmt,
10201                                        DSAStack->getTaskgroupReductionRef());
10202 }
10203 
10204 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10205                                            SourceLocation StartLoc,
10206                                            SourceLocation EndLoc) {
10207   OMPFlushClause *FC = nullptr;
10208   OMPClause *OrderClause = nullptr;
10209   for (OMPClause *C : Clauses) {
10210     if (C->getClauseKind() == OMPC_flush)
10211       FC = cast<OMPFlushClause>(C);
10212     else
10213       OrderClause = C;
10214   }
10215   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10216   SourceLocation MemOrderLoc;
10217   for (const OMPClause *C : Clauses) {
10218     if (C->getClauseKind() == OMPC_acq_rel ||
10219         C->getClauseKind() == OMPC_acquire ||
10220         C->getClauseKind() == OMPC_release) {
10221       if (MemOrderKind != OMPC_unknown) {
10222         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10223             << getOpenMPDirectiveName(OMPD_flush) << 1
10224             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10225         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10226             << getOpenMPClauseName(MemOrderKind);
10227       } else {
10228         MemOrderKind = C->getClauseKind();
10229         MemOrderLoc = C->getBeginLoc();
10230       }
10231     }
10232   }
10233   if (FC && OrderClause) {
10234     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10235         << getOpenMPClauseName(OrderClause->getClauseKind());
10236     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10237         << getOpenMPClauseName(OrderClause->getClauseKind());
10238     return StmtError();
10239   }
10240   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10241 }
10242 
10243 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10244                                             SourceLocation StartLoc,
10245                                             SourceLocation EndLoc) {
10246   if (Clauses.empty()) {
10247     Diag(StartLoc, diag::err_omp_depobj_expected);
10248     return StmtError();
10249   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10250     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10251     return StmtError();
10252   }
10253   // Only depobj expression and another single clause is allowed.
10254   if (Clauses.size() > 2) {
10255     Diag(Clauses[2]->getBeginLoc(),
10256          diag::err_omp_depobj_single_clause_expected);
10257     return StmtError();
10258   } else if (Clauses.size() < 1) {
10259     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10260     return StmtError();
10261   }
10262   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10263 }
10264 
10265 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10266                                           SourceLocation StartLoc,
10267                                           SourceLocation EndLoc) {
10268   // Check that exactly one clause is specified.
10269   if (Clauses.size() != 1) {
10270     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10271          diag::err_omp_scan_single_clause_expected);
10272     return StmtError();
10273   }
10274   // Check that scan directive is used in the scopeof the OpenMP loop body.
10275   if (Scope *S = DSAStack->getCurScope()) {
10276     Scope *ParentS = S->getParent();
10277     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10278         !ParentS->getBreakParent()->isOpenMPLoopScope())
10279       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10280                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10281   }
10282   // Check that only one instance of scan directives is used in the same outer
10283   // region.
10284   if (DSAStack->doesParentHasScanDirective()) {
10285     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10286     Diag(DSAStack->getParentScanDirectiveLoc(),
10287          diag::note_omp_previous_directive)
10288         << "scan";
10289     return StmtError();
10290   }
10291   DSAStack->setParentHasScanDirective(StartLoc);
10292   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10293 }
10294 
10295 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10296                                              Stmt *AStmt,
10297                                              SourceLocation StartLoc,
10298                                              SourceLocation EndLoc) {
10299   const OMPClause *DependFound = nullptr;
10300   const OMPClause *DependSourceClause = nullptr;
10301   const OMPClause *DependSinkClause = nullptr;
10302   bool ErrorFound = false;
10303   const OMPThreadsClause *TC = nullptr;
10304   const OMPSIMDClause *SC = nullptr;
10305   for (const OMPClause *C : Clauses) {
10306     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10307       DependFound = C;
10308       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10309         if (DependSourceClause) {
10310           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10311               << getOpenMPDirectiveName(OMPD_ordered)
10312               << getOpenMPClauseName(OMPC_depend) << 2;
10313           ErrorFound = true;
10314         } else {
10315           DependSourceClause = C;
10316         }
10317         if (DependSinkClause) {
10318           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10319               << 0;
10320           ErrorFound = true;
10321         }
10322       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10323         if (DependSourceClause) {
10324           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10325               << 1;
10326           ErrorFound = true;
10327         }
10328         DependSinkClause = C;
10329       }
10330     } else if (C->getClauseKind() == OMPC_threads) {
10331       TC = cast<OMPThreadsClause>(C);
10332     } else if (C->getClauseKind() == OMPC_simd) {
10333       SC = cast<OMPSIMDClause>(C);
10334     }
10335   }
10336   if (!ErrorFound && !SC &&
10337       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10338     // OpenMP [2.8.1,simd Construct, Restrictions]
10339     // An ordered construct with the simd clause is the only OpenMP construct
10340     // that can appear in the simd region.
10341     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10342         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10343     ErrorFound = true;
10344   } else if (DependFound && (TC || SC)) {
10345     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10346         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10347     ErrorFound = true;
10348   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10349     Diag(DependFound->getBeginLoc(),
10350          diag::err_omp_ordered_directive_without_param);
10351     ErrorFound = true;
10352   } else if (TC || Clauses.empty()) {
10353     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10354       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10355       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10356           << (TC != nullptr);
10357       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10358       ErrorFound = true;
10359     }
10360   }
10361   if ((!AStmt && !DependFound) || ErrorFound)
10362     return StmtError();
10363 
10364   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10365   // During execution of an iteration of a worksharing-loop or a loop nest
10366   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10367   // must not execute more than one ordered region corresponding to an ordered
10368   // construct without a depend clause.
10369   if (!DependFound) {
10370     if (DSAStack->doesParentHasOrderedDirective()) {
10371       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10372       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10373            diag::note_omp_previous_directive)
10374           << "ordered";
10375       return StmtError();
10376     }
10377     DSAStack->setParentHasOrderedDirective(StartLoc);
10378   }
10379 
10380   if (AStmt) {
10381     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10382 
10383     setFunctionHasBranchProtectedScope();
10384   }
10385 
10386   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10387 }
10388 
10389 namespace {
10390 /// Helper class for checking expression in 'omp atomic [update]'
10391 /// construct.
10392 class OpenMPAtomicUpdateChecker {
10393   /// Error results for atomic update expressions.
10394   enum ExprAnalysisErrorCode {
10395     /// A statement is not an expression statement.
10396     NotAnExpression,
10397     /// Expression is not builtin binary or unary operation.
10398     NotABinaryOrUnaryExpression,
10399     /// Unary operation is not post-/pre- increment/decrement operation.
10400     NotAnUnaryIncDecExpression,
10401     /// An expression is not of scalar type.
10402     NotAScalarType,
10403     /// A binary operation is not an assignment operation.
10404     NotAnAssignmentOp,
10405     /// RHS part of the binary operation is not a binary expression.
10406     NotABinaryExpression,
10407     /// RHS part is not additive/multiplicative/shift/biwise binary
10408     /// expression.
10409     NotABinaryOperator,
10410     /// RHS binary operation does not have reference to the updated LHS
10411     /// part.
10412     NotAnUpdateExpression,
10413     /// No errors is found.
10414     NoError
10415   };
10416   /// Reference to Sema.
10417   Sema &SemaRef;
10418   /// A location for note diagnostics (when error is found).
10419   SourceLocation NoteLoc;
10420   /// 'x' lvalue part of the source atomic expression.
10421   Expr *X;
10422   /// 'expr' rvalue part of the source atomic expression.
10423   Expr *E;
10424   /// Helper expression of the form
10425   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10426   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10427   Expr *UpdateExpr;
10428   /// Is 'x' a LHS in a RHS part of full update expression. It is
10429   /// important for non-associative operations.
10430   bool IsXLHSInRHSPart;
10431   BinaryOperatorKind Op;
10432   SourceLocation OpLoc;
10433   /// true if the source expression is a postfix unary operation, false
10434   /// if it is a prefix unary operation.
10435   bool IsPostfixUpdate;
10436 
10437 public:
10438   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10439       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10440         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10441   /// Check specified statement that it is suitable for 'atomic update'
10442   /// constructs and extract 'x', 'expr' and Operation from the original
10443   /// expression. If DiagId and NoteId == 0, then only check is performed
10444   /// without error notification.
10445   /// \param DiagId Diagnostic which should be emitted if error is found.
10446   /// \param NoteId Diagnostic note for the main error message.
10447   /// \return true if statement is not an update expression, false otherwise.
10448   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10449   /// Return the 'x' lvalue part of the source atomic expression.
10450   Expr *getX() const { return X; }
10451   /// Return the 'expr' rvalue part of the source atomic expression.
10452   Expr *getExpr() const { return E; }
10453   /// Return the update expression used in calculation of the updated
10454   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10455   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10456   Expr *getUpdateExpr() const { return UpdateExpr; }
10457   /// Return true if 'x' is LHS in RHS part of full update expression,
10458   /// false otherwise.
10459   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10460 
10461   /// true if the source expression is a postfix unary operation, false
10462   /// if it is a prefix unary operation.
10463   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10464 
10465 private:
10466   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10467                             unsigned NoteId = 0);
10468 };
10469 } // namespace
10470 
10471 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10472     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10473   ExprAnalysisErrorCode ErrorFound = NoError;
10474   SourceLocation ErrorLoc, NoteLoc;
10475   SourceRange ErrorRange, NoteRange;
10476   // Allowed constructs are:
10477   //  x = x binop expr;
10478   //  x = expr binop x;
10479   if (AtomicBinOp->getOpcode() == BO_Assign) {
10480     X = AtomicBinOp->getLHS();
10481     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10482             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10483       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10484           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10485           AtomicInnerBinOp->isBitwiseOp()) {
10486         Op = AtomicInnerBinOp->getOpcode();
10487         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10488         Expr *LHS = AtomicInnerBinOp->getLHS();
10489         Expr *RHS = AtomicInnerBinOp->getRHS();
10490         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10491         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10492                                           /*Canonical=*/true);
10493         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10494                                             /*Canonical=*/true);
10495         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10496                                             /*Canonical=*/true);
10497         if (XId == LHSId) {
10498           E = RHS;
10499           IsXLHSInRHSPart = true;
10500         } else if (XId == RHSId) {
10501           E = LHS;
10502           IsXLHSInRHSPart = false;
10503         } else {
10504           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10505           ErrorRange = AtomicInnerBinOp->getSourceRange();
10506           NoteLoc = X->getExprLoc();
10507           NoteRange = X->getSourceRange();
10508           ErrorFound = NotAnUpdateExpression;
10509         }
10510       } else {
10511         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10512         ErrorRange = AtomicInnerBinOp->getSourceRange();
10513         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10514         NoteRange = SourceRange(NoteLoc, NoteLoc);
10515         ErrorFound = NotABinaryOperator;
10516       }
10517     } else {
10518       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10519       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10520       ErrorFound = NotABinaryExpression;
10521     }
10522   } else {
10523     ErrorLoc = AtomicBinOp->getExprLoc();
10524     ErrorRange = AtomicBinOp->getSourceRange();
10525     NoteLoc = AtomicBinOp->getOperatorLoc();
10526     NoteRange = SourceRange(NoteLoc, NoteLoc);
10527     ErrorFound = NotAnAssignmentOp;
10528   }
10529   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10530     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10531     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10532     return true;
10533   }
10534   if (SemaRef.CurContext->isDependentContext())
10535     E = X = UpdateExpr = nullptr;
10536   return ErrorFound != NoError;
10537 }
10538 
10539 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10540                                                unsigned NoteId) {
10541   ExprAnalysisErrorCode ErrorFound = NoError;
10542   SourceLocation ErrorLoc, NoteLoc;
10543   SourceRange ErrorRange, NoteRange;
10544   // Allowed constructs are:
10545   //  x++;
10546   //  x--;
10547   //  ++x;
10548   //  --x;
10549   //  x binop= expr;
10550   //  x = x binop expr;
10551   //  x = expr binop x;
10552   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10553     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10554     if (AtomicBody->getType()->isScalarType() ||
10555         AtomicBody->isInstantiationDependent()) {
10556       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10557               AtomicBody->IgnoreParenImpCasts())) {
10558         // Check for Compound Assignment Operation
10559         Op = BinaryOperator::getOpForCompoundAssignment(
10560             AtomicCompAssignOp->getOpcode());
10561         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10562         E = AtomicCompAssignOp->getRHS();
10563         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10564         IsXLHSInRHSPart = true;
10565       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10566                      AtomicBody->IgnoreParenImpCasts())) {
10567         // Check for Binary Operation
10568         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10569           return true;
10570       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10571                      AtomicBody->IgnoreParenImpCasts())) {
10572         // Check for Unary Operation
10573         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10574           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10575           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10576           OpLoc = AtomicUnaryOp->getOperatorLoc();
10577           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10578           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10579           IsXLHSInRHSPart = true;
10580         } else {
10581           ErrorFound = NotAnUnaryIncDecExpression;
10582           ErrorLoc = AtomicUnaryOp->getExprLoc();
10583           ErrorRange = AtomicUnaryOp->getSourceRange();
10584           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10585           NoteRange = SourceRange(NoteLoc, NoteLoc);
10586         }
10587       } else if (!AtomicBody->isInstantiationDependent()) {
10588         ErrorFound = NotABinaryOrUnaryExpression;
10589         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10590         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10591       }
10592     } else {
10593       ErrorFound = NotAScalarType;
10594       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10595       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10596     }
10597   } else {
10598     ErrorFound = NotAnExpression;
10599     NoteLoc = ErrorLoc = S->getBeginLoc();
10600     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10601   }
10602   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10603     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10604     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10605     return true;
10606   }
10607   if (SemaRef.CurContext->isDependentContext())
10608     E = X = UpdateExpr = nullptr;
10609   if (ErrorFound == NoError && E && X) {
10610     // Build an update expression of form 'OpaqueValueExpr(x) binop
10611     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10612     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10613     auto *OVEX = new (SemaRef.getASTContext())
10614         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
10615     auto *OVEExpr = new (SemaRef.getASTContext())
10616         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
10617     ExprResult Update =
10618         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10619                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10620     if (Update.isInvalid())
10621       return true;
10622     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10623                                                Sema::AA_Casting);
10624     if (Update.isInvalid())
10625       return true;
10626     UpdateExpr = Update.get();
10627   }
10628   return ErrorFound != NoError;
10629 }
10630 
10631 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10632                                             Stmt *AStmt,
10633                                             SourceLocation StartLoc,
10634                                             SourceLocation EndLoc) {
10635   // Register location of the first atomic directive.
10636   DSAStack->addAtomicDirectiveLoc(StartLoc);
10637   if (!AStmt)
10638     return StmtError();
10639 
10640   // 1.2.2 OpenMP Language Terminology
10641   // Structured block - An executable statement with a single entry at the
10642   // top and a single exit at the bottom.
10643   // The point of exit cannot be a branch out of the structured block.
10644   // longjmp() and throw() must not violate the entry/exit criteria.
10645   OpenMPClauseKind AtomicKind = OMPC_unknown;
10646   SourceLocation AtomicKindLoc;
10647   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10648   SourceLocation MemOrderLoc;
10649   for (const OMPClause *C : Clauses) {
10650     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
10651         C->getClauseKind() == OMPC_update ||
10652         C->getClauseKind() == OMPC_capture) {
10653       if (AtomicKind != OMPC_unknown) {
10654         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10655             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10656         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10657             << getOpenMPClauseName(AtomicKind);
10658       } else {
10659         AtomicKind = C->getClauseKind();
10660         AtomicKindLoc = C->getBeginLoc();
10661       }
10662     }
10663     if (C->getClauseKind() == OMPC_seq_cst ||
10664         C->getClauseKind() == OMPC_acq_rel ||
10665         C->getClauseKind() == OMPC_acquire ||
10666         C->getClauseKind() == OMPC_release ||
10667         C->getClauseKind() == OMPC_relaxed) {
10668       if (MemOrderKind != OMPC_unknown) {
10669         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10670             << getOpenMPDirectiveName(OMPD_atomic) << 0
10671             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10672         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10673             << getOpenMPClauseName(MemOrderKind);
10674       } else {
10675         MemOrderKind = C->getClauseKind();
10676         MemOrderLoc = C->getBeginLoc();
10677       }
10678     }
10679   }
10680   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10681   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10682   // release.
10683   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10684   // acquire.
10685   // If atomic-clause is update or not present then memory-order-clause must not
10686   // be acq_rel or acquire.
10687   if ((AtomicKind == OMPC_read &&
10688        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10689       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10690         AtomicKind == OMPC_unknown) &&
10691        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10692     SourceLocation Loc = AtomicKindLoc;
10693     if (AtomicKind == OMPC_unknown)
10694       Loc = StartLoc;
10695     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10696         << getOpenMPClauseName(AtomicKind)
10697         << (AtomicKind == OMPC_unknown ? 1 : 0)
10698         << getOpenMPClauseName(MemOrderKind);
10699     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10700         << getOpenMPClauseName(MemOrderKind);
10701   }
10702 
10703   Stmt *Body = AStmt;
10704   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10705     Body = EWC->getSubExpr();
10706 
10707   Expr *X = nullptr;
10708   Expr *V = nullptr;
10709   Expr *E = nullptr;
10710   Expr *UE = nullptr;
10711   bool IsXLHSInRHSPart = false;
10712   bool IsPostfixUpdate = false;
10713   // OpenMP [2.12.6, atomic Construct]
10714   // In the next expressions:
10715   // * x and v (as applicable) are both l-value expressions with scalar type.
10716   // * During the execution of an atomic region, multiple syntactic
10717   // occurrences of x must designate the same storage location.
10718   // * Neither of v and expr (as applicable) may access the storage location
10719   // designated by x.
10720   // * Neither of x and expr (as applicable) may access the storage location
10721   // designated by v.
10722   // * expr is an expression with scalar type.
10723   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
10724   // * binop, binop=, ++, and -- are not overloaded operators.
10725   // * The expression x binop expr must be numerically equivalent to x binop
10726   // (expr). This requirement is satisfied if the operators in expr have
10727   // precedence greater than binop, or by using parentheses around expr or
10728   // subexpressions of expr.
10729   // * The expression expr binop x must be numerically equivalent to (expr)
10730   // binop x. This requirement is satisfied if the operators in expr have
10731   // precedence equal to or greater than binop, or by using parentheses around
10732   // expr or subexpressions of expr.
10733   // * For forms that allow multiple occurrences of x, the number of times
10734   // that x is evaluated is unspecified.
10735   if (AtomicKind == OMPC_read) {
10736     enum {
10737       NotAnExpression,
10738       NotAnAssignmentOp,
10739       NotAScalarType,
10740       NotAnLValue,
10741       NoError
10742     } ErrorFound = NoError;
10743     SourceLocation ErrorLoc, NoteLoc;
10744     SourceRange ErrorRange, NoteRange;
10745     // If clause is read:
10746     //  v = x;
10747     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10748       const auto *AtomicBinOp =
10749           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10750       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10751         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10752         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
10753         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10754             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
10755           if (!X->isLValue() || !V->isLValue()) {
10756             const Expr *NotLValueExpr = X->isLValue() ? V : X;
10757             ErrorFound = NotAnLValue;
10758             ErrorLoc = AtomicBinOp->getExprLoc();
10759             ErrorRange = AtomicBinOp->getSourceRange();
10760             NoteLoc = NotLValueExpr->getExprLoc();
10761             NoteRange = NotLValueExpr->getSourceRange();
10762           }
10763         } else if (!X->isInstantiationDependent() ||
10764                    !V->isInstantiationDependent()) {
10765           const Expr *NotScalarExpr =
10766               (X->isInstantiationDependent() || X->getType()->isScalarType())
10767                   ? V
10768                   : X;
10769           ErrorFound = NotAScalarType;
10770           ErrorLoc = AtomicBinOp->getExprLoc();
10771           ErrorRange = AtomicBinOp->getSourceRange();
10772           NoteLoc = NotScalarExpr->getExprLoc();
10773           NoteRange = NotScalarExpr->getSourceRange();
10774         }
10775       } else if (!AtomicBody->isInstantiationDependent()) {
10776         ErrorFound = NotAnAssignmentOp;
10777         ErrorLoc = AtomicBody->getExprLoc();
10778         ErrorRange = AtomicBody->getSourceRange();
10779         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10780                               : AtomicBody->getExprLoc();
10781         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10782                                 : AtomicBody->getSourceRange();
10783       }
10784     } else {
10785       ErrorFound = NotAnExpression;
10786       NoteLoc = ErrorLoc = Body->getBeginLoc();
10787       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10788     }
10789     if (ErrorFound != NoError) {
10790       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
10791           << ErrorRange;
10792       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10793                                                       << NoteRange;
10794       return StmtError();
10795     }
10796     if (CurContext->isDependentContext())
10797       V = X = nullptr;
10798   } else if (AtomicKind == OMPC_write) {
10799     enum {
10800       NotAnExpression,
10801       NotAnAssignmentOp,
10802       NotAScalarType,
10803       NotAnLValue,
10804       NoError
10805     } ErrorFound = NoError;
10806     SourceLocation ErrorLoc, NoteLoc;
10807     SourceRange ErrorRange, NoteRange;
10808     // If clause is write:
10809     //  x = expr;
10810     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10811       const auto *AtomicBinOp =
10812           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10813       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10814         X = AtomicBinOp->getLHS();
10815         E = AtomicBinOp->getRHS();
10816         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10817             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
10818           if (!X->isLValue()) {
10819             ErrorFound = NotAnLValue;
10820             ErrorLoc = AtomicBinOp->getExprLoc();
10821             ErrorRange = AtomicBinOp->getSourceRange();
10822             NoteLoc = X->getExprLoc();
10823             NoteRange = X->getSourceRange();
10824           }
10825         } else if (!X->isInstantiationDependent() ||
10826                    !E->isInstantiationDependent()) {
10827           const Expr *NotScalarExpr =
10828               (X->isInstantiationDependent() || X->getType()->isScalarType())
10829                   ? E
10830                   : X;
10831           ErrorFound = NotAScalarType;
10832           ErrorLoc = AtomicBinOp->getExprLoc();
10833           ErrorRange = AtomicBinOp->getSourceRange();
10834           NoteLoc = NotScalarExpr->getExprLoc();
10835           NoteRange = NotScalarExpr->getSourceRange();
10836         }
10837       } else if (!AtomicBody->isInstantiationDependent()) {
10838         ErrorFound = NotAnAssignmentOp;
10839         ErrorLoc = AtomicBody->getExprLoc();
10840         ErrorRange = AtomicBody->getSourceRange();
10841         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10842                               : AtomicBody->getExprLoc();
10843         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10844                                 : AtomicBody->getSourceRange();
10845       }
10846     } else {
10847       ErrorFound = NotAnExpression;
10848       NoteLoc = ErrorLoc = Body->getBeginLoc();
10849       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10850     }
10851     if (ErrorFound != NoError) {
10852       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
10853           << ErrorRange;
10854       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10855                                                       << NoteRange;
10856       return StmtError();
10857     }
10858     if (CurContext->isDependentContext())
10859       E = X = nullptr;
10860   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
10861     // If clause is update:
10862     //  x++;
10863     //  x--;
10864     //  ++x;
10865     //  --x;
10866     //  x binop= expr;
10867     //  x = x binop expr;
10868     //  x = expr binop x;
10869     OpenMPAtomicUpdateChecker Checker(*this);
10870     if (Checker.checkStatement(
10871             Body, (AtomicKind == OMPC_update)
10872                       ? diag::err_omp_atomic_update_not_expression_statement
10873                       : diag::err_omp_atomic_not_expression_statement,
10874             diag::note_omp_atomic_update))
10875       return StmtError();
10876     if (!CurContext->isDependentContext()) {
10877       E = Checker.getExpr();
10878       X = Checker.getX();
10879       UE = Checker.getUpdateExpr();
10880       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10881     }
10882   } else if (AtomicKind == OMPC_capture) {
10883     enum {
10884       NotAnAssignmentOp,
10885       NotACompoundStatement,
10886       NotTwoSubstatements,
10887       NotASpecificExpression,
10888       NoError
10889     } ErrorFound = NoError;
10890     SourceLocation ErrorLoc, NoteLoc;
10891     SourceRange ErrorRange, NoteRange;
10892     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10893       // If clause is a capture:
10894       //  v = x++;
10895       //  v = x--;
10896       //  v = ++x;
10897       //  v = --x;
10898       //  v = x binop= expr;
10899       //  v = x = x binop expr;
10900       //  v = x = expr binop x;
10901       const auto *AtomicBinOp =
10902           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10903       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10904         V = AtomicBinOp->getLHS();
10905         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10906         OpenMPAtomicUpdateChecker Checker(*this);
10907         if (Checker.checkStatement(
10908                 Body, diag::err_omp_atomic_capture_not_expression_statement,
10909                 diag::note_omp_atomic_update))
10910           return StmtError();
10911         E = Checker.getExpr();
10912         X = Checker.getX();
10913         UE = Checker.getUpdateExpr();
10914         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10915         IsPostfixUpdate = Checker.isPostfixUpdate();
10916       } else if (!AtomicBody->isInstantiationDependent()) {
10917         ErrorLoc = AtomicBody->getExprLoc();
10918         ErrorRange = AtomicBody->getSourceRange();
10919         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10920                               : AtomicBody->getExprLoc();
10921         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10922                                 : AtomicBody->getSourceRange();
10923         ErrorFound = NotAnAssignmentOp;
10924       }
10925       if (ErrorFound != NoError) {
10926         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
10927             << ErrorRange;
10928         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10929         return StmtError();
10930       }
10931       if (CurContext->isDependentContext())
10932         UE = V = E = X = nullptr;
10933     } else {
10934       // If clause is a capture:
10935       //  { v = x; x = expr; }
10936       //  { v = x; x++; }
10937       //  { v = x; x--; }
10938       //  { v = x; ++x; }
10939       //  { v = x; --x; }
10940       //  { v = x; x binop= expr; }
10941       //  { v = x; x = x binop expr; }
10942       //  { v = x; x = expr binop x; }
10943       //  { x++; v = x; }
10944       //  { x--; v = x; }
10945       //  { ++x; v = x; }
10946       //  { --x; v = x; }
10947       //  { x binop= expr; v = x; }
10948       //  { x = x binop expr; v = x; }
10949       //  { x = expr binop x; v = x; }
10950       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
10951         // Check that this is { expr1; expr2; }
10952         if (CS->size() == 2) {
10953           Stmt *First = CS->body_front();
10954           Stmt *Second = CS->body_back();
10955           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
10956             First = EWC->getSubExpr()->IgnoreParenImpCasts();
10957           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
10958             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
10959           // Need to find what subexpression is 'v' and what is 'x'.
10960           OpenMPAtomicUpdateChecker Checker(*this);
10961           bool IsUpdateExprFound = !Checker.checkStatement(Second);
10962           BinaryOperator *BinOp = nullptr;
10963           if (IsUpdateExprFound) {
10964             BinOp = dyn_cast<BinaryOperator>(First);
10965             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10966           }
10967           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10968             //  { v = x; x++; }
10969             //  { v = x; x--; }
10970             //  { v = x; ++x; }
10971             //  { v = x; --x; }
10972             //  { v = x; x binop= expr; }
10973             //  { v = x; x = x binop expr; }
10974             //  { v = x; x = expr binop x; }
10975             // Check that the first expression has form v = x.
10976             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10977             llvm::FoldingSetNodeID XId, PossibleXId;
10978             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10979             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10980             IsUpdateExprFound = XId == PossibleXId;
10981             if (IsUpdateExprFound) {
10982               V = BinOp->getLHS();
10983               X = Checker.getX();
10984               E = Checker.getExpr();
10985               UE = Checker.getUpdateExpr();
10986               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10987               IsPostfixUpdate = true;
10988             }
10989           }
10990           if (!IsUpdateExprFound) {
10991             IsUpdateExprFound = !Checker.checkStatement(First);
10992             BinOp = nullptr;
10993             if (IsUpdateExprFound) {
10994               BinOp = dyn_cast<BinaryOperator>(Second);
10995               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10996             }
10997             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10998               //  { x++; v = x; }
10999               //  { x--; v = x; }
11000               //  { ++x; v = x; }
11001               //  { --x; v = x; }
11002               //  { x binop= expr; v = x; }
11003               //  { x = x binop expr; v = x; }
11004               //  { x = expr binop x; v = x; }
11005               // Check that the second expression has form v = x.
11006               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11007               llvm::FoldingSetNodeID XId, PossibleXId;
11008               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11009               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11010               IsUpdateExprFound = XId == PossibleXId;
11011               if (IsUpdateExprFound) {
11012                 V = BinOp->getLHS();
11013                 X = Checker.getX();
11014                 E = Checker.getExpr();
11015                 UE = Checker.getUpdateExpr();
11016                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11017                 IsPostfixUpdate = false;
11018               }
11019             }
11020           }
11021           if (!IsUpdateExprFound) {
11022             //  { v = x; x = expr; }
11023             auto *FirstExpr = dyn_cast<Expr>(First);
11024             auto *SecondExpr = dyn_cast<Expr>(Second);
11025             if (!FirstExpr || !SecondExpr ||
11026                 !(FirstExpr->isInstantiationDependent() ||
11027                   SecondExpr->isInstantiationDependent())) {
11028               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11029               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11030                 ErrorFound = NotAnAssignmentOp;
11031                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11032                                                 : First->getBeginLoc();
11033                 NoteRange = ErrorRange = FirstBinOp
11034                                              ? FirstBinOp->getSourceRange()
11035                                              : SourceRange(ErrorLoc, ErrorLoc);
11036               } else {
11037                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11038                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11039                   ErrorFound = NotAnAssignmentOp;
11040                   NoteLoc = ErrorLoc = SecondBinOp
11041                                            ? SecondBinOp->getOperatorLoc()
11042                                            : Second->getBeginLoc();
11043                   NoteRange = ErrorRange =
11044                       SecondBinOp ? SecondBinOp->getSourceRange()
11045                                   : SourceRange(ErrorLoc, ErrorLoc);
11046                 } else {
11047                   Expr *PossibleXRHSInFirst =
11048                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11049                   Expr *PossibleXLHSInSecond =
11050                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11051                   llvm::FoldingSetNodeID X1Id, X2Id;
11052                   PossibleXRHSInFirst->Profile(X1Id, Context,
11053                                                /*Canonical=*/true);
11054                   PossibleXLHSInSecond->Profile(X2Id, Context,
11055                                                 /*Canonical=*/true);
11056                   IsUpdateExprFound = X1Id == X2Id;
11057                   if (IsUpdateExprFound) {
11058                     V = FirstBinOp->getLHS();
11059                     X = SecondBinOp->getLHS();
11060                     E = SecondBinOp->getRHS();
11061                     UE = nullptr;
11062                     IsXLHSInRHSPart = false;
11063                     IsPostfixUpdate = true;
11064                   } else {
11065                     ErrorFound = NotASpecificExpression;
11066                     ErrorLoc = FirstBinOp->getExprLoc();
11067                     ErrorRange = FirstBinOp->getSourceRange();
11068                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11069                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11070                   }
11071                 }
11072               }
11073             }
11074           }
11075         } else {
11076           NoteLoc = ErrorLoc = Body->getBeginLoc();
11077           NoteRange = ErrorRange =
11078               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11079           ErrorFound = NotTwoSubstatements;
11080         }
11081       } else {
11082         NoteLoc = ErrorLoc = Body->getBeginLoc();
11083         NoteRange = ErrorRange =
11084             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11085         ErrorFound = NotACompoundStatement;
11086       }
11087       if (ErrorFound != NoError) {
11088         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11089             << ErrorRange;
11090         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11091         return StmtError();
11092       }
11093       if (CurContext->isDependentContext())
11094         UE = V = E = X = nullptr;
11095     }
11096   }
11097 
11098   setFunctionHasBranchProtectedScope();
11099 
11100   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11101                                     X, V, E, UE, IsXLHSInRHSPart,
11102                                     IsPostfixUpdate);
11103 }
11104 
11105 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11106                                             Stmt *AStmt,
11107                                             SourceLocation StartLoc,
11108                                             SourceLocation EndLoc) {
11109   if (!AStmt)
11110     return StmtError();
11111 
11112   auto *CS = cast<CapturedStmt>(AStmt);
11113   // 1.2.2 OpenMP Language Terminology
11114   // Structured block - An executable statement with a single entry at the
11115   // top and a single exit at the bottom.
11116   // The point of exit cannot be a branch out of the structured block.
11117   // longjmp() and throw() must not violate the entry/exit criteria.
11118   CS->getCapturedDecl()->setNothrow();
11119   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11120        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11121     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11122     // 1.2.2 OpenMP Language Terminology
11123     // Structured block - An executable statement with a single entry at the
11124     // top and a single exit at the bottom.
11125     // The point of exit cannot be a branch out of the structured block.
11126     // longjmp() and throw() must not violate the entry/exit criteria.
11127     CS->getCapturedDecl()->setNothrow();
11128   }
11129 
11130   // OpenMP [2.16, Nesting of Regions]
11131   // If specified, a teams construct must be contained within a target
11132   // construct. That target construct must contain no statements or directives
11133   // outside of the teams construct.
11134   if (DSAStack->hasInnerTeamsRegion()) {
11135     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11136     bool OMPTeamsFound = true;
11137     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11138       auto I = CS->body_begin();
11139       while (I != CS->body_end()) {
11140         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11141         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11142             OMPTeamsFound) {
11143 
11144           OMPTeamsFound = false;
11145           break;
11146         }
11147         ++I;
11148       }
11149       assert(I != CS->body_end() && "Not found statement");
11150       S = *I;
11151     } else {
11152       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11153       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11154     }
11155     if (!OMPTeamsFound) {
11156       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11157       Diag(DSAStack->getInnerTeamsRegionLoc(),
11158            diag::note_omp_nested_teams_construct_here);
11159       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11160           << isa<OMPExecutableDirective>(S);
11161       return StmtError();
11162     }
11163   }
11164 
11165   setFunctionHasBranchProtectedScope();
11166 
11167   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11168 }
11169 
11170 StmtResult
11171 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11172                                          Stmt *AStmt, SourceLocation StartLoc,
11173                                          SourceLocation EndLoc) {
11174   if (!AStmt)
11175     return StmtError();
11176 
11177   auto *CS = cast<CapturedStmt>(AStmt);
11178   // 1.2.2 OpenMP Language Terminology
11179   // Structured block - An executable statement with a single entry at the
11180   // top and a single exit at the bottom.
11181   // The point of exit cannot be a branch out of the structured block.
11182   // longjmp() and throw() must not violate the entry/exit criteria.
11183   CS->getCapturedDecl()->setNothrow();
11184   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11185        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11186     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11187     // 1.2.2 OpenMP Language Terminology
11188     // Structured block - An executable statement with a single entry at the
11189     // top and a single exit at the bottom.
11190     // The point of exit cannot be a branch out of the structured block.
11191     // longjmp() and throw() must not violate the entry/exit criteria.
11192     CS->getCapturedDecl()->setNothrow();
11193   }
11194 
11195   setFunctionHasBranchProtectedScope();
11196 
11197   return OMPTargetParallelDirective::Create(
11198       Context, StartLoc, EndLoc, Clauses, AStmt,
11199       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11200 }
11201 
11202 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11203     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11204     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11205   if (!AStmt)
11206     return StmtError();
11207 
11208   auto *CS = cast<CapturedStmt>(AStmt);
11209   // 1.2.2 OpenMP Language Terminology
11210   // Structured block - An executable statement with a single entry at the
11211   // top and a single exit at the bottom.
11212   // The point of exit cannot be a branch out of the structured block.
11213   // longjmp() and throw() must not violate the entry/exit criteria.
11214   CS->getCapturedDecl()->setNothrow();
11215   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11216        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11217     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11218     // 1.2.2 OpenMP Language Terminology
11219     // Structured block - An executable statement with a single entry at the
11220     // top and a single exit at the bottom.
11221     // The point of exit cannot be a branch out of the structured block.
11222     // longjmp() and throw() must not violate the entry/exit criteria.
11223     CS->getCapturedDecl()->setNothrow();
11224   }
11225 
11226   OMPLoopBasedDirective::HelperExprs B;
11227   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11228   // define the nested loops number.
11229   unsigned NestedLoopCount =
11230       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11231                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11232                       VarsWithImplicitDSA, B);
11233   if (NestedLoopCount == 0)
11234     return StmtError();
11235 
11236   assert((CurContext->isDependentContext() || B.builtAll()) &&
11237          "omp target parallel for loop exprs were not built");
11238 
11239   if (!CurContext->isDependentContext()) {
11240     // Finalize the clauses that need pre-built expressions for CodeGen.
11241     for (OMPClause *C : Clauses) {
11242       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11243         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11244                                      B.NumIterations, *this, CurScope,
11245                                      DSAStack))
11246           return StmtError();
11247     }
11248   }
11249 
11250   setFunctionHasBranchProtectedScope();
11251   return OMPTargetParallelForDirective::Create(
11252       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11253       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11254 }
11255 
11256 /// Check for existence of a map clause in the list of clauses.
11257 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11258                        const OpenMPClauseKind K) {
11259   return llvm::any_of(
11260       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11261 }
11262 
11263 template <typename... Params>
11264 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11265                        const Params... ClauseTypes) {
11266   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11267 }
11268 
11269 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11270                                                 Stmt *AStmt,
11271                                                 SourceLocation StartLoc,
11272                                                 SourceLocation EndLoc) {
11273   if (!AStmt)
11274     return StmtError();
11275 
11276   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11277 
11278   // OpenMP [2.12.2, target data Construct, Restrictions]
11279   // At least one map, use_device_addr or use_device_ptr clause must appear on
11280   // the directive.
11281   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11282       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11283     StringRef Expected;
11284     if (LangOpts.OpenMP < 50)
11285       Expected = "'map' or 'use_device_ptr'";
11286     else
11287       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11288     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11289         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11290     return StmtError();
11291   }
11292 
11293   setFunctionHasBranchProtectedScope();
11294 
11295   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11296                                         AStmt);
11297 }
11298 
11299 StmtResult
11300 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11301                                           SourceLocation StartLoc,
11302                                           SourceLocation EndLoc, Stmt *AStmt) {
11303   if (!AStmt)
11304     return StmtError();
11305 
11306   auto *CS = cast<CapturedStmt>(AStmt);
11307   // 1.2.2 OpenMP Language Terminology
11308   // Structured block - An executable statement with a single entry at the
11309   // top and a single exit at the bottom.
11310   // The point of exit cannot be a branch out of the structured block.
11311   // longjmp() and throw() must not violate the entry/exit criteria.
11312   CS->getCapturedDecl()->setNothrow();
11313   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11314        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11315     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11316     // 1.2.2 OpenMP Language Terminology
11317     // Structured block - An executable statement with a single entry at the
11318     // top and a single exit at the bottom.
11319     // The point of exit cannot be a branch out of the structured block.
11320     // longjmp() and throw() must not violate the entry/exit criteria.
11321     CS->getCapturedDecl()->setNothrow();
11322   }
11323 
11324   // OpenMP [2.10.2, Restrictions, p. 99]
11325   // At least one map clause must appear on the directive.
11326   if (!hasClauses(Clauses, OMPC_map)) {
11327     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11328         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11329     return StmtError();
11330   }
11331 
11332   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11333                                              AStmt);
11334 }
11335 
11336 StmtResult
11337 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11338                                          SourceLocation StartLoc,
11339                                          SourceLocation EndLoc, Stmt *AStmt) {
11340   if (!AStmt)
11341     return StmtError();
11342 
11343   auto *CS = cast<CapturedStmt>(AStmt);
11344   // 1.2.2 OpenMP Language Terminology
11345   // Structured block - An executable statement with a single entry at the
11346   // top and a single exit at the bottom.
11347   // The point of exit cannot be a branch out of the structured block.
11348   // longjmp() and throw() must not violate the entry/exit criteria.
11349   CS->getCapturedDecl()->setNothrow();
11350   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11351        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11352     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11353     // 1.2.2 OpenMP Language Terminology
11354     // Structured block - An executable statement with a single entry at the
11355     // top and a single exit at the bottom.
11356     // The point of exit cannot be a branch out of the structured block.
11357     // longjmp() and throw() must not violate the entry/exit criteria.
11358     CS->getCapturedDecl()->setNothrow();
11359   }
11360 
11361   // OpenMP [2.10.3, Restrictions, p. 102]
11362   // At least one map clause must appear on the directive.
11363   if (!hasClauses(Clauses, OMPC_map)) {
11364     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11365         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11366     return StmtError();
11367   }
11368 
11369   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11370                                             AStmt);
11371 }
11372 
11373 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11374                                                   SourceLocation StartLoc,
11375                                                   SourceLocation EndLoc,
11376                                                   Stmt *AStmt) {
11377   if (!AStmt)
11378     return StmtError();
11379 
11380   auto *CS = cast<CapturedStmt>(AStmt);
11381   // 1.2.2 OpenMP Language Terminology
11382   // Structured block - An executable statement with a single entry at the
11383   // top and a single exit at the bottom.
11384   // The point of exit cannot be a branch out of the structured block.
11385   // longjmp() and throw() must not violate the entry/exit criteria.
11386   CS->getCapturedDecl()->setNothrow();
11387   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11388        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11389     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11390     // 1.2.2 OpenMP Language Terminology
11391     // Structured block - An executable statement with a single entry at the
11392     // top and a single exit at the bottom.
11393     // The point of exit cannot be a branch out of the structured block.
11394     // longjmp() and throw() must not violate the entry/exit criteria.
11395     CS->getCapturedDecl()->setNothrow();
11396   }
11397 
11398   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11399     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11400     return StmtError();
11401   }
11402   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11403                                           AStmt);
11404 }
11405 
11406 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11407                                            Stmt *AStmt, SourceLocation StartLoc,
11408                                            SourceLocation EndLoc) {
11409   if (!AStmt)
11410     return StmtError();
11411 
11412   auto *CS = cast<CapturedStmt>(AStmt);
11413   // 1.2.2 OpenMP Language Terminology
11414   // Structured block - An executable statement with a single entry at the
11415   // top and a single exit at the bottom.
11416   // The point of exit cannot be a branch out of the structured block.
11417   // longjmp() and throw() must not violate the entry/exit criteria.
11418   CS->getCapturedDecl()->setNothrow();
11419 
11420   setFunctionHasBranchProtectedScope();
11421 
11422   DSAStack->setParentTeamsRegionLoc(StartLoc);
11423 
11424   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11425 }
11426 
11427 StmtResult
11428 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11429                                             SourceLocation EndLoc,
11430                                             OpenMPDirectiveKind CancelRegion) {
11431   if (DSAStack->isParentNowaitRegion()) {
11432     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11433     return StmtError();
11434   }
11435   if (DSAStack->isParentOrderedRegion()) {
11436     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11437     return StmtError();
11438   }
11439   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11440                                                CancelRegion);
11441 }
11442 
11443 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11444                                             SourceLocation StartLoc,
11445                                             SourceLocation EndLoc,
11446                                             OpenMPDirectiveKind CancelRegion) {
11447   if (DSAStack->isParentNowaitRegion()) {
11448     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11449     return StmtError();
11450   }
11451   if (DSAStack->isParentOrderedRegion()) {
11452     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11453     return StmtError();
11454   }
11455   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11456   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11457                                     CancelRegion);
11458 }
11459 
11460 static bool checkGrainsizeNumTasksClauses(Sema &S,
11461                                           ArrayRef<OMPClause *> Clauses) {
11462   const OMPClause *PrevClause = nullptr;
11463   bool ErrorFound = false;
11464   for (const OMPClause *C : Clauses) {
11465     if (C->getClauseKind() == OMPC_grainsize ||
11466         C->getClauseKind() == OMPC_num_tasks) {
11467       if (!PrevClause)
11468         PrevClause = C;
11469       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
11470         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
11471             << getOpenMPClauseName(C->getClauseKind())
11472             << getOpenMPClauseName(PrevClause->getClauseKind());
11473         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
11474             << getOpenMPClauseName(PrevClause->getClauseKind());
11475         ErrorFound = true;
11476       }
11477     }
11478   }
11479   return ErrorFound;
11480 }
11481 
11482 static bool checkReductionClauseWithNogroup(Sema &S,
11483                                             ArrayRef<OMPClause *> Clauses) {
11484   const OMPClause *ReductionClause = nullptr;
11485   const OMPClause *NogroupClause = nullptr;
11486   for (const OMPClause *C : Clauses) {
11487     if (C->getClauseKind() == OMPC_reduction) {
11488       ReductionClause = C;
11489       if (NogroupClause)
11490         break;
11491       continue;
11492     }
11493     if (C->getClauseKind() == OMPC_nogroup) {
11494       NogroupClause = C;
11495       if (ReductionClause)
11496         break;
11497       continue;
11498     }
11499   }
11500   if (ReductionClause && NogroupClause) {
11501     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11502         << SourceRange(NogroupClause->getBeginLoc(),
11503                        NogroupClause->getEndLoc());
11504     return true;
11505   }
11506   return false;
11507 }
11508 
11509 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11510     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11511     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11512   if (!AStmt)
11513     return StmtError();
11514 
11515   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11516   OMPLoopBasedDirective::HelperExprs B;
11517   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11518   // define the nested loops number.
11519   unsigned NestedLoopCount =
11520       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11521                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11522                       VarsWithImplicitDSA, B);
11523   if (NestedLoopCount == 0)
11524     return StmtError();
11525 
11526   assert((CurContext->isDependentContext() || B.builtAll()) &&
11527          "omp for loop exprs were not built");
11528 
11529   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11530   // The grainsize clause and num_tasks clause are mutually exclusive and may
11531   // not appear on the same taskloop directive.
11532   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11533     return StmtError();
11534   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11535   // If a reduction clause is present on the taskloop directive, the nogroup
11536   // clause must not be specified.
11537   if (checkReductionClauseWithNogroup(*this, Clauses))
11538     return StmtError();
11539 
11540   setFunctionHasBranchProtectedScope();
11541   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11542                                       NestedLoopCount, Clauses, AStmt, B,
11543                                       DSAStack->isCancelRegion());
11544 }
11545 
11546 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11547     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11548     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11549   if (!AStmt)
11550     return StmtError();
11551 
11552   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11553   OMPLoopBasedDirective::HelperExprs B;
11554   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11555   // define the nested loops number.
11556   unsigned NestedLoopCount =
11557       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11558                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11559                       VarsWithImplicitDSA, B);
11560   if (NestedLoopCount == 0)
11561     return StmtError();
11562 
11563   assert((CurContext->isDependentContext() || B.builtAll()) &&
11564          "omp for loop exprs were not built");
11565 
11566   if (!CurContext->isDependentContext()) {
11567     // Finalize the clauses that need pre-built expressions for CodeGen.
11568     for (OMPClause *C : Clauses) {
11569       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11570         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11571                                      B.NumIterations, *this, CurScope,
11572                                      DSAStack))
11573           return StmtError();
11574     }
11575   }
11576 
11577   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11578   // The grainsize clause and num_tasks clause are mutually exclusive and may
11579   // not appear on the same taskloop directive.
11580   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11581     return StmtError();
11582   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11583   // If a reduction clause is present on the taskloop directive, the nogroup
11584   // clause must not be specified.
11585   if (checkReductionClauseWithNogroup(*this, Clauses))
11586     return StmtError();
11587   if (checkSimdlenSafelenSpecified(*this, Clauses))
11588     return StmtError();
11589 
11590   setFunctionHasBranchProtectedScope();
11591   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11592                                           NestedLoopCount, Clauses, AStmt, B);
11593 }
11594 
11595 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11596     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11597     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11598   if (!AStmt)
11599     return StmtError();
11600 
11601   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11602   OMPLoopBasedDirective::HelperExprs B;
11603   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11604   // define the nested loops number.
11605   unsigned NestedLoopCount =
11606       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11607                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11608                       VarsWithImplicitDSA, B);
11609   if (NestedLoopCount == 0)
11610     return StmtError();
11611 
11612   assert((CurContext->isDependentContext() || B.builtAll()) &&
11613          "omp for loop exprs were not built");
11614 
11615   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11616   // The grainsize clause and num_tasks clause are mutually exclusive and may
11617   // not appear on the same taskloop directive.
11618   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11619     return StmtError();
11620   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11621   // If a reduction clause is present on the taskloop directive, the nogroup
11622   // clause must not be specified.
11623   if (checkReductionClauseWithNogroup(*this, Clauses))
11624     return StmtError();
11625 
11626   setFunctionHasBranchProtectedScope();
11627   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11628                                             NestedLoopCount, Clauses, AStmt, B,
11629                                             DSAStack->isCancelRegion());
11630 }
11631 
11632 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11633     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11634     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11635   if (!AStmt)
11636     return StmtError();
11637 
11638   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11639   OMPLoopBasedDirective::HelperExprs B;
11640   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11641   // define the nested loops number.
11642   unsigned NestedLoopCount =
11643       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11644                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11645                       VarsWithImplicitDSA, B);
11646   if (NestedLoopCount == 0)
11647     return StmtError();
11648 
11649   assert((CurContext->isDependentContext() || B.builtAll()) &&
11650          "omp for loop exprs were not built");
11651 
11652   if (!CurContext->isDependentContext()) {
11653     // Finalize the clauses that need pre-built expressions for CodeGen.
11654     for (OMPClause *C : Clauses) {
11655       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11656         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11657                                      B.NumIterations, *this, CurScope,
11658                                      DSAStack))
11659           return StmtError();
11660     }
11661   }
11662 
11663   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11664   // The grainsize clause and num_tasks clause are mutually exclusive and may
11665   // not appear on the same taskloop directive.
11666   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11667     return StmtError();
11668   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11669   // If a reduction clause is present on the taskloop directive, the nogroup
11670   // clause must not be specified.
11671   if (checkReductionClauseWithNogroup(*this, Clauses))
11672     return StmtError();
11673   if (checkSimdlenSafelenSpecified(*this, Clauses))
11674     return StmtError();
11675 
11676   setFunctionHasBranchProtectedScope();
11677   return OMPMasterTaskLoopSimdDirective::Create(
11678       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11679 }
11680 
11681 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11682     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11683     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11684   if (!AStmt)
11685     return StmtError();
11686 
11687   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11688   auto *CS = cast<CapturedStmt>(AStmt);
11689   // 1.2.2 OpenMP Language Terminology
11690   // Structured block - An executable statement with a single entry at the
11691   // top and a single exit at the bottom.
11692   // The point of exit cannot be a branch out of the structured block.
11693   // longjmp() and throw() must not violate the entry/exit criteria.
11694   CS->getCapturedDecl()->setNothrow();
11695   for (int ThisCaptureLevel =
11696            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11697        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11698     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11699     // 1.2.2 OpenMP Language Terminology
11700     // Structured block - An executable statement with a single entry at the
11701     // top and a single exit at the bottom.
11702     // The point of exit cannot be a branch out of the structured block.
11703     // longjmp() and throw() must not violate the entry/exit criteria.
11704     CS->getCapturedDecl()->setNothrow();
11705   }
11706 
11707   OMPLoopBasedDirective::HelperExprs B;
11708   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11709   // define the nested loops number.
11710   unsigned NestedLoopCount = checkOpenMPLoop(
11711       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11712       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11713       VarsWithImplicitDSA, B);
11714   if (NestedLoopCount == 0)
11715     return StmtError();
11716 
11717   assert((CurContext->isDependentContext() || B.builtAll()) &&
11718          "omp for loop exprs were not built");
11719 
11720   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11721   // The grainsize clause and num_tasks clause are mutually exclusive and may
11722   // not appear on the same taskloop directive.
11723   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11724     return StmtError();
11725   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11726   // If a reduction clause is present on the taskloop directive, the nogroup
11727   // clause must not be specified.
11728   if (checkReductionClauseWithNogroup(*this, Clauses))
11729     return StmtError();
11730 
11731   setFunctionHasBranchProtectedScope();
11732   return OMPParallelMasterTaskLoopDirective::Create(
11733       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11734       DSAStack->isCancelRegion());
11735 }
11736 
11737 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11738     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11739     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11740   if (!AStmt)
11741     return StmtError();
11742 
11743   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11744   auto *CS = cast<CapturedStmt>(AStmt);
11745   // 1.2.2 OpenMP Language Terminology
11746   // Structured block - An executable statement with a single entry at the
11747   // top and a single exit at the bottom.
11748   // The point of exit cannot be a branch out of the structured block.
11749   // longjmp() and throw() must not violate the entry/exit criteria.
11750   CS->getCapturedDecl()->setNothrow();
11751   for (int ThisCaptureLevel =
11752            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
11753        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11754     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11755     // 1.2.2 OpenMP Language Terminology
11756     // Structured block - An executable statement with a single entry at the
11757     // top and a single exit at the bottom.
11758     // The point of exit cannot be a branch out of the structured block.
11759     // longjmp() and throw() must not violate the entry/exit criteria.
11760     CS->getCapturedDecl()->setNothrow();
11761   }
11762 
11763   OMPLoopBasedDirective::HelperExprs B;
11764   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11765   // define the nested loops number.
11766   unsigned NestedLoopCount = checkOpenMPLoop(
11767       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11768       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11769       VarsWithImplicitDSA, B);
11770   if (NestedLoopCount == 0)
11771     return StmtError();
11772 
11773   assert((CurContext->isDependentContext() || B.builtAll()) &&
11774          "omp for loop exprs were not built");
11775 
11776   if (!CurContext->isDependentContext()) {
11777     // Finalize the clauses that need pre-built expressions for CodeGen.
11778     for (OMPClause *C : Clauses) {
11779       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11780         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11781                                      B.NumIterations, *this, CurScope,
11782                                      DSAStack))
11783           return StmtError();
11784     }
11785   }
11786 
11787   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11788   // The grainsize clause and num_tasks clause are mutually exclusive and may
11789   // not appear on the same taskloop directive.
11790   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11791     return StmtError();
11792   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11793   // If a reduction clause is present on the taskloop directive, the nogroup
11794   // clause must not be specified.
11795   if (checkReductionClauseWithNogroup(*this, Clauses))
11796     return StmtError();
11797   if (checkSimdlenSafelenSpecified(*this, Clauses))
11798     return StmtError();
11799 
11800   setFunctionHasBranchProtectedScope();
11801   return OMPParallelMasterTaskLoopSimdDirective::Create(
11802       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11803 }
11804 
11805 StmtResult Sema::ActOnOpenMPDistributeDirective(
11806     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11807     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11808   if (!AStmt)
11809     return StmtError();
11810 
11811   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11812   OMPLoopBasedDirective::HelperExprs B;
11813   // In presence of clause 'collapse' with number of loops, it will
11814   // define the nested loops number.
11815   unsigned NestedLoopCount =
11816       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
11817                       nullptr /*ordered not a clause on distribute*/, AStmt,
11818                       *this, *DSAStack, VarsWithImplicitDSA, B);
11819   if (NestedLoopCount == 0)
11820     return StmtError();
11821 
11822   assert((CurContext->isDependentContext() || B.builtAll()) &&
11823          "omp for loop exprs were not built");
11824 
11825   setFunctionHasBranchProtectedScope();
11826   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
11827                                         NestedLoopCount, Clauses, AStmt, B);
11828 }
11829 
11830 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
11831     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11832     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11833   if (!AStmt)
11834     return StmtError();
11835 
11836   auto *CS = cast<CapturedStmt>(AStmt);
11837   // 1.2.2 OpenMP Language Terminology
11838   // Structured block - An executable statement with a single entry at the
11839   // top and a single exit at the bottom.
11840   // The point of exit cannot be a branch out of the structured block.
11841   // longjmp() and throw() must not violate the entry/exit criteria.
11842   CS->getCapturedDecl()->setNothrow();
11843   for (int ThisCaptureLevel =
11844            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
11845        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11846     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11847     // 1.2.2 OpenMP Language Terminology
11848     // Structured block - An executable statement with a single entry at the
11849     // top and a single exit at the bottom.
11850     // The point of exit cannot be a branch out of the structured block.
11851     // longjmp() and throw() must not violate the entry/exit criteria.
11852     CS->getCapturedDecl()->setNothrow();
11853   }
11854 
11855   OMPLoopBasedDirective::HelperExprs B;
11856   // In presence of clause 'collapse' with number of loops, it will
11857   // define the nested loops number.
11858   unsigned NestedLoopCount = checkOpenMPLoop(
11859       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11860       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11861       VarsWithImplicitDSA, B);
11862   if (NestedLoopCount == 0)
11863     return StmtError();
11864 
11865   assert((CurContext->isDependentContext() || B.builtAll()) &&
11866          "omp for loop exprs were not built");
11867 
11868   setFunctionHasBranchProtectedScope();
11869   return OMPDistributeParallelForDirective::Create(
11870       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11871       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11872 }
11873 
11874 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
11875     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11876     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11877   if (!AStmt)
11878     return StmtError();
11879 
11880   auto *CS = cast<CapturedStmt>(AStmt);
11881   // 1.2.2 OpenMP Language Terminology
11882   // Structured block - An executable statement with a single entry at the
11883   // top and a single exit at the bottom.
11884   // The point of exit cannot be a branch out of the structured block.
11885   // longjmp() and throw() must not violate the entry/exit criteria.
11886   CS->getCapturedDecl()->setNothrow();
11887   for (int ThisCaptureLevel =
11888            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
11889        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11890     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11891     // 1.2.2 OpenMP Language Terminology
11892     // Structured block - An executable statement with a single entry at the
11893     // top and a single exit at the bottom.
11894     // The point of exit cannot be a branch out of the structured block.
11895     // longjmp() and throw() must not violate the entry/exit criteria.
11896     CS->getCapturedDecl()->setNothrow();
11897   }
11898 
11899   OMPLoopBasedDirective::HelperExprs B;
11900   // In presence of clause 'collapse' with number of loops, it will
11901   // define the nested loops number.
11902   unsigned NestedLoopCount = checkOpenMPLoop(
11903       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11904       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11905       VarsWithImplicitDSA, B);
11906   if (NestedLoopCount == 0)
11907     return StmtError();
11908 
11909   assert((CurContext->isDependentContext() || B.builtAll()) &&
11910          "omp for loop exprs were not built");
11911 
11912   if (!CurContext->isDependentContext()) {
11913     // Finalize the clauses that need pre-built expressions for CodeGen.
11914     for (OMPClause *C : Clauses) {
11915       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11916         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11917                                      B.NumIterations, *this, CurScope,
11918                                      DSAStack))
11919           return StmtError();
11920     }
11921   }
11922 
11923   if (checkSimdlenSafelenSpecified(*this, Clauses))
11924     return StmtError();
11925 
11926   setFunctionHasBranchProtectedScope();
11927   return OMPDistributeParallelForSimdDirective::Create(
11928       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11929 }
11930 
11931 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
11932     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11933     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11934   if (!AStmt)
11935     return StmtError();
11936 
11937   auto *CS = cast<CapturedStmt>(AStmt);
11938   // 1.2.2 OpenMP Language Terminology
11939   // Structured block - An executable statement with a single entry at the
11940   // top and a single exit at the bottom.
11941   // The point of exit cannot be a branch out of the structured block.
11942   // longjmp() and throw() must not violate the entry/exit criteria.
11943   CS->getCapturedDecl()->setNothrow();
11944   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
11945        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11946     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11947     // 1.2.2 OpenMP Language Terminology
11948     // Structured block - An executable statement with a single entry at the
11949     // top and a single exit at the bottom.
11950     // The point of exit cannot be a branch out of the structured block.
11951     // longjmp() and throw() must not violate the entry/exit criteria.
11952     CS->getCapturedDecl()->setNothrow();
11953   }
11954 
11955   OMPLoopBasedDirective::HelperExprs B;
11956   // In presence of clause 'collapse' with number of loops, it will
11957   // define the nested loops number.
11958   unsigned NestedLoopCount =
11959       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
11960                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11961                       *DSAStack, VarsWithImplicitDSA, B);
11962   if (NestedLoopCount == 0)
11963     return StmtError();
11964 
11965   assert((CurContext->isDependentContext() || B.builtAll()) &&
11966          "omp for loop exprs were not built");
11967 
11968   if (!CurContext->isDependentContext()) {
11969     // Finalize the clauses that need pre-built expressions for CodeGen.
11970     for (OMPClause *C : Clauses) {
11971       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11972         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11973                                      B.NumIterations, *this, CurScope,
11974                                      DSAStack))
11975           return StmtError();
11976     }
11977   }
11978 
11979   if (checkSimdlenSafelenSpecified(*this, Clauses))
11980     return StmtError();
11981 
11982   setFunctionHasBranchProtectedScope();
11983   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11984                                             NestedLoopCount, Clauses, AStmt, B);
11985 }
11986 
11987 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11988     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11989     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11990   if (!AStmt)
11991     return StmtError();
11992 
11993   auto *CS = cast<CapturedStmt>(AStmt);
11994   // 1.2.2 OpenMP Language Terminology
11995   // Structured block - An executable statement with a single entry at the
11996   // top and a single exit at the bottom.
11997   // The point of exit cannot be a branch out of the structured block.
11998   // longjmp() and throw() must not violate the entry/exit criteria.
11999   CS->getCapturedDecl()->setNothrow();
12000   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12001        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12002     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12003     // 1.2.2 OpenMP Language Terminology
12004     // Structured block - An executable statement with a single entry at the
12005     // top and a single exit at the bottom.
12006     // The point of exit cannot be a branch out of the structured block.
12007     // longjmp() and throw() must not violate the entry/exit criteria.
12008     CS->getCapturedDecl()->setNothrow();
12009   }
12010 
12011   OMPLoopBasedDirective::HelperExprs B;
12012   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12013   // define the nested loops number.
12014   unsigned NestedLoopCount = checkOpenMPLoop(
12015       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12016       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12017       VarsWithImplicitDSA, B);
12018   if (NestedLoopCount == 0)
12019     return StmtError();
12020 
12021   assert((CurContext->isDependentContext() || B.builtAll()) &&
12022          "omp target parallel for simd loop exprs were not built");
12023 
12024   if (!CurContext->isDependentContext()) {
12025     // Finalize the clauses that need pre-built expressions for CodeGen.
12026     for (OMPClause *C : Clauses) {
12027       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12028         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12029                                      B.NumIterations, *this, CurScope,
12030                                      DSAStack))
12031           return StmtError();
12032     }
12033   }
12034   if (checkSimdlenSafelenSpecified(*this, Clauses))
12035     return StmtError();
12036 
12037   setFunctionHasBranchProtectedScope();
12038   return OMPTargetParallelForSimdDirective::Create(
12039       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12040 }
12041 
12042 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12043     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12044     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12045   if (!AStmt)
12046     return StmtError();
12047 
12048   auto *CS = cast<CapturedStmt>(AStmt);
12049   // 1.2.2 OpenMP Language Terminology
12050   // Structured block - An executable statement with a single entry at the
12051   // top and a single exit at the bottom.
12052   // The point of exit cannot be a branch out of the structured block.
12053   // longjmp() and throw() must not violate the entry/exit criteria.
12054   CS->getCapturedDecl()->setNothrow();
12055   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12056        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12057     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12058     // 1.2.2 OpenMP Language Terminology
12059     // Structured block - An executable statement with a single entry at the
12060     // top and a single exit at the bottom.
12061     // The point of exit cannot be a branch out of the structured block.
12062     // longjmp() and throw() must not violate the entry/exit criteria.
12063     CS->getCapturedDecl()->setNothrow();
12064   }
12065 
12066   OMPLoopBasedDirective::HelperExprs B;
12067   // In presence of clause 'collapse' with number of loops, it will define the
12068   // nested loops number.
12069   unsigned NestedLoopCount =
12070       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12071                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12072                       VarsWithImplicitDSA, B);
12073   if (NestedLoopCount == 0)
12074     return StmtError();
12075 
12076   assert((CurContext->isDependentContext() || B.builtAll()) &&
12077          "omp target simd loop exprs were not built");
12078 
12079   if (!CurContext->isDependentContext()) {
12080     // Finalize the clauses that need pre-built expressions for CodeGen.
12081     for (OMPClause *C : Clauses) {
12082       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12083         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12084                                      B.NumIterations, *this, CurScope,
12085                                      DSAStack))
12086           return StmtError();
12087     }
12088   }
12089 
12090   if (checkSimdlenSafelenSpecified(*this, Clauses))
12091     return StmtError();
12092 
12093   setFunctionHasBranchProtectedScope();
12094   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12095                                         NestedLoopCount, Clauses, AStmt, B);
12096 }
12097 
12098 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12099     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12100     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12101   if (!AStmt)
12102     return StmtError();
12103 
12104   auto *CS = cast<CapturedStmt>(AStmt);
12105   // 1.2.2 OpenMP Language Terminology
12106   // Structured block - An executable statement with a single entry at the
12107   // top and a single exit at the bottom.
12108   // The point of exit cannot be a branch out of the structured block.
12109   // longjmp() and throw() must not violate the entry/exit criteria.
12110   CS->getCapturedDecl()->setNothrow();
12111   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12112        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12113     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12114     // 1.2.2 OpenMP Language Terminology
12115     // Structured block - An executable statement with a single entry at the
12116     // top and a single exit at the bottom.
12117     // The point of exit cannot be a branch out of the structured block.
12118     // longjmp() and throw() must not violate the entry/exit criteria.
12119     CS->getCapturedDecl()->setNothrow();
12120   }
12121 
12122   OMPLoopBasedDirective::HelperExprs B;
12123   // In presence of clause 'collapse' with number of loops, it will
12124   // define the nested loops number.
12125   unsigned NestedLoopCount =
12126       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12127                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12128                       *DSAStack, VarsWithImplicitDSA, B);
12129   if (NestedLoopCount == 0)
12130     return StmtError();
12131 
12132   assert((CurContext->isDependentContext() || B.builtAll()) &&
12133          "omp teams distribute loop exprs were not built");
12134 
12135   setFunctionHasBranchProtectedScope();
12136 
12137   DSAStack->setParentTeamsRegionLoc(StartLoc);
12138 
12139   return OMPTeamsDistributeDirective::Create(
12140       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12141 }
12142 
12143 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12144     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12145     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12146   if (!AStmt)
12147     return StmtError();
12148 
12149   auto *CS = cast<CapturedStmt>(AStmt);
12150   // 1.2.2 OpenMP Language Terminology
12151   // Structured block - An executable statement with a single entry at the
12152   // top and a single exit at the bottom.
12153   // The point of exit cannot be a branch out of the structured block.
12154   // longjmp() and throw() must not violate the entry/exit criteria.
12155   CS->getCapturedDecl()->setNothrow();
12156   for (int ThisCaptureLevel =
12157            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12158        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12159     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12160     // 1.2.2 OpenMP Language Terminology
12161     // Structured block - An executable statement with a single entry at the
12162     // top and a single exit at the bottom.
12163     // The point of exit cannot be a branch out of the structured block.
12164     // longjmp() and throw() must not violate the entry/exit criteria.
12165     CS->getCapturedDecl()->setNothrow();
12166   }
12167 
12168   OMPLoopBasedDirective::HelperExprs B;
12169   // In presence of clause 'collapse' with number of loops, it will
12170   // define the nested loops number.
12171   unsigned NestedLoopCount = checkOpenMPLoop(
12172       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12173       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12174       VarsWithImplicitDSA, B);
12175 
12176   if (NestedLoopCount == 0)
12177     return StmtError();
12178 
12179   assert((CurContext->isDependentContext() || B.builtAll()) &&
12180          "omp teams distribute simd loop exprs were not built");
12181 
12182   if (!CurContext->isDependentContext()) {
12183     // Finalize the clauses that need pre-built expressions for CodeGen.
12184     for (OMPClause *C : Clauses) {
12185       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12186         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12187                                      B.NumIterations, *this, CurScope,
12188                                      DSAStack))
12189           return StmtError();
12190     }
12191   }
12192 
12193   if (checkSimdlenSafelenSpecified(*this, Clauses))
12194     return StmtError();
12195 
12196   setFunctionHasBranchProtectedScope();
12197 
12198   DSAStack->setParentTeamsRegionLoc(StartLoc);
12199 
12200   return OMPTeamsDistributeSimdDirective::Create(
12201       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12202 }
12203 
12204 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12205     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12206     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12207   if (!AStmt)
12208     return StmtError();
12209 
12210   auto *CS = cast<CapturedStmt>(AStmt);
12211   // 1.2.2 OpenMP Language Terminology
12212   // Structured block - An executable statement with a single entry at the
12213   // top and a single exit at the bottom.
12214   // The point of exit cannot be a branch out of the structured block.
12215   // longjmp() and throw() must not violate the entry/exit criteria.
12216   CS->getCapturedDecl()->setNothrow();
12217 
12218   for (int ThisCaptureLevel =
12219            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12220        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12221     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12222     // 1.2.2 OpenMP Language Terminology
12223     // Structured block - An executable statement with a single entry at the
12224     // top and a single exit at the bottom.
12225     // The point of exit cannot be a branch out of the structured block.
12226     // longjmp() and throw() must not violate the entry/exit criteria.
12227     CS->getCapturedDecl()->setNothrow();
12228   }
12229 
12230   OMPLoopBasedDirective::HelperExprs B;
12231   // In presence of clause 'collapse' with number of loops, it will
12232   // define the nested loops number.
12233   unsigned NestedLoopCount = checkOpenMPLoop(
12234       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12235       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12236       VarsWithImplicitDSA, B);
12237 
12238   if (NestedLoopCount == 0)
12239     return StmtError();
12240 
12241   assert((CurContext->isDependentContext() || B.builtAll()) &&
12242          "omp for loop exprs were not built");
12243 
12244   if (!CurContext->isDependentContext()) {
12245     // Finalize the clauses that need pre-built expressions for CodeGen.
12246     for (OMPClause *C : Clauses) {
12247       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12248         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12249                                      B.NumIterations, *this, CurScope,
12250                                      DSAStack))
12251           return StmtError();
12252     }
12253   }
12254 
12255   if (checkSimdlenSafelenSpecified(*this, Clauses))
12256     return StmtError();
12257 
12258   setFunctionHasBranchProtectedScope();
12259 
12260   DSAStack->setParentTeamsRegionLoc(StartLoc);
12261 
12262   return OMPTeamsDistributeParallelForSimdDirective::Create(
12263       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12264 }
12265 
12266 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12267     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12268     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12269   if (!AStmt)
12270     return StmtError();
12271 
12272   auto *CS = cast<CapturedStmt>(AStmt);
12273   // 1.2.2 OpenMP Language Terminology
12274   // Structured block - An executable statement with a single entry at the
12275   // top and a single exit at the bottom.
12276   // The point of exit cannot be a branch out of the structured block.
12277   // longjmp() and throw() must not violate the entry/exit criteria.
12278   CS->getCapturedDecl()->setNothrow();
12279 
12280   for (int ThisCaptureLevel =
12281            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12282        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12283     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12284     // 1.2.2 OpenMP Language Terminology
12285     // Structured block - An executable statement with a single entry at the
12286     // top and a single exit at the bottom.
12287     // The point of exit cannot be a branch out of the structured block.
12288     // longjmp() and throw() must not violate the entry/exit criteria.
12289     CS->getCapturedDecl()->setNothrow();
12290   }
12291 
12292   OMPLoopBasedDirective::HelperExprs B;
12293   // In presence of clause 'collapse' with number of loops, it will
12294   // define the nested loops number.
12295   unsigned NestedLoopCount = checkOpenMPLoop(
12296       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12297       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12298       VarsWithImplicitDSA, B);
12299 
12300   if (NestedLoopCount == 0)
12301     return StmtError();
12302 
12303   assert((CurContext->isDependentContext() || B.builtAll()) &&
12304          "omp for loop exprs were not built");
12305 
12306   setFunctionHasBranchProtectedScope();
12307 
12308   DSAStack->setParentTeamsRegionLoc(StartLoc);
12309 
12310   return OMPTeamsDistributeParallelForDirective::Create(
12311       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12312       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12313 }
12314 
12315 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12316                                                  Stmt *AStmt,
12317                                                  SourceLocation StartLoc,
12318                                                  SourceLocation EndLoc) {
12319   if (!AStmt)
12320     return StmtError();
12321 
12322   auto *CS = cast<CapturedStmt>(AStmt);
12323   // 1.2.2 OpenMP Language Terminology
12324   // Structured block - An executable statement with a single entry at the
12325   // top and a single exit at the bottom.
12326   // The point of exit cannot be a branch out of the structured block.
12327   // longjmp() and throw() must not violate the entry/exit criteria.
12328   CS->getCapturedDecl()->setNothrow();
12329 
12330   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12331        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12332     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12333     // 1.2.2 OpenMP Language Terminology
12334     // Structured block - An executable statement with a single entry at the
12335     // top and a single exit at the bottom.
12336     // The point of exit cannot be a branch out of the structured block.
12337     // longjmp() and throw() must not violate the entry/exit criteria.
12338     CS->getCapturedDecl()->setNothrow();
12339   }
12340   setFunctionHasBranchProtectedScope();
12341 
12342   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12343                                          AStmt);
12344 }
12345 
12346 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12347     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12348     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12349   if (!AStmt)
12350     return StmtError();
12351 
12352   auto *CS = cast<CapturedStmt>(AStmt);
12353   // 1.2.2 OpenMP Language Terminology
12354   // Structured block - An executable statement with a single entry at the
12355   // top and a single exit at the bottom.
12356   // The point of exit cannot be a branch out of the structured block.
12357   // longjmp() and throw() must not violate the entry/exit criteria.
12358   CS->getCapturedDecl()->setNothrow();
12359   for (int ThisCaptureLevel =
12360            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12361        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12362     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12363     // 1.2.2 OpenMP Language Terminology
12364     // Structured block - An executable statement with a single entry at the
12365     // top and a single exit at the bottom.
12366     // The point of exit cannot be a branch out of the structured block.
12367     // longjmp() and throw() must not violate the entry/exit criteria.
12368     CS->getCapturedDecl()->setNothrow();
12369   }
12370 
12371   OMPLoopBasedDirective::HelperExprs B;
12372   // In presence of clause 'collapse' with number of loops, it will
12373   // define the nested loops number.
12374   unsigned NestedLoopCount = checkOpenMPLoop(
12375       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12376       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12377       VarsWithImplicitDSA, B);
12378   if (NestedLoopCount == 0)
12379     return StmtError();
12380 
12381   assert((CurContext->isDependentContext() || B.builtAll()) &&
12382          "omp target teams distribute loop exprs were not built");
12383 
12384   setFunctionHasBranchProtectedScope();
12385   return OMPTargetTeamsDistributeDirective::Create(
12386       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12387 }
12388 
12389 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12390     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12391     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12392   if (!AStmt)
12393     return StmtError();
12394 
12395   auto *CS = cast<CapturedStmt>(AStmt);
12396   // 1.2.2 OpenMP Language Terminology
12397   // Structured block - An executable statement with a single entry at the
12398   // top and a single exit at the bottom.
12399   // The point of exit cannot be a branch out of the structured block.
12400   // longjmp() and throw() must not violate the entry/exit criteria.
12401   CS->getCapturedDecl()->setNothrow();
12402   for (int ThisCaptureLevel =
12403            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12404        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12405     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12406     // 1.2.2 OpenMP Language Terminology
12407     // Structured block - An executable statement with a single entry at the
12408     // top and a single exit at the bottom.
12409     // The point of exit cannot be a branch out of the structured block.
12410     // longjmp() and throw() must not violate the entry/exit criteria.
12411     CS->getCapturedDecl()->setNothrow();
12412   }
12413 
12414   OMPLoopBasedDirective::HelperExprs B;
12415   // In presence of clause 'collapse' with number of loops, it will
12416   // define the nested loops number.
12417   unsigned NestedLoopCount = checkOpenMPLoop(
12418       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12419       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12420       VarsWithImplicitDSA, B);
12421   if (NestedLoopCount == 0)
12422     return StmtError();
12423 
12424   assert((CurContext->isDependentContext() || B.builtAll()) &&
12425          "omp target teams distribute parallel for loop exprs were not built");
12426 
12427   if (!CurContext->isDependentContext()) {
12428     // Finalize the clauses that need pre-built expressions for CodeGen.
12429     for (OMPClause *C : Clauses) {
12430       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12431         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12432                                      B.NumIterations, *this, CurScope,
12433                                      DSAStack))
12434           return StmtError();
12435     }
12436   }
12437 
12438   setFunctionHasBranchProtectedScope();
12439   return OMPTargetTeamsDistributeParallelForDirective::Create(
12440       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12441       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12442 }
12443 
12444 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12445     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12446     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12447   if (!AStmt)
12448     return StmtError();
12449 
12450   auto *CS = cast<CapturedStmt>(AStmt);
12451   // 1.2.2 OpenMP Language Terminology
12452   // Structured block - An executable statement with a single entry at the
12453   // top and a single exit at the bottom.
12454   // The point of exit cannot be a branch out of the structured block.
12455   // longjmp() and throw() must not violate the entry/exit criteria.
12456   CS->getCapturedDecl()->setNothrow();
12457   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12458            OMPD_target_teams_distribute_parallel_for_simd);
12459        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12460     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12461     // 1.2.2 OpenMP Language Terminology
12462     // Structured block - An executable statement with a single entry at the
12463     // top and a single exit at the bottom.
12464     // The point of exit cannot be a branch out of the structured block.
12465     // longjmp() and throw() must not violate the entry/exit criteria.
12466     CS->getCapturedDecl()->setNothrow();
12467   }
12468 
12469   OMPLoopBasedDirective::HelperExprs B;
12470   // In presence of clause 'collapse' with number of loops, it will
12471   // define the nested loops number.
12472   unsigned NestedLoopCount =
12473       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12474                       getCollapseNumberExpr(Clauses),
12475                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12476                       *DSAStack, VarsWithImplicitDSA, B);
12477   if (NestedLoopCount == 0)
12478     return StmtError();
12479 
12480   assert((CurContext->isDependentContext() || B.builtAll()) &&
12481          "omp target teams distribute parallel for simd loop exprs were not "
12482          "built");
12483 
12484   if (!CurContext->isDependentContext()) {
12485     // Finalize the clauses that need pre-built expressions for CodeGen.
12486     for (OMPClause *C : Clauses) {
12487       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12488         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12489                                      B.NumIterations, *this, CurScope,
12490                                      DSAStack))
12491           return StmtError();
12492     }
12493   }
12494 
12495   if (checkSimdlenSafelenSpecified(*this, Clauses))
12496     return StmtError();
12497 
12498   setFunctionHasBranchProtectedScope();
12499   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12500       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12501 }
12502 
12503 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12504     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12505     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12506   if (!AStmt)
12507     return StmtError();
12508 
12509   auto *CS = cast<CapturedStmt>(AStmt);
12510   // 1.2.2 OpenMP Language Terminology
12511   // Structured block - An executable statement with a single entry at the
12512   // top and a single exit at the bottom.
12513   // The point of exit cannot be a branch out of the structured block.
12514   // longjmp() and throw() must not violate the entry/exit criteria.
12515   CS->getCapturedDecl()->setNothrow();
12516   for (int ThisCaptureLevel =
12517            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12518        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12519     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12520     // 1.2.2 OpenMP Language Terminology
12521     // Structured block - An executable statement with a single entry at the
12522     // top and a single exit at the bottom.
12523     // The point of exit cannot be a branch out of the structured block.
12524     // longjmp() and throw() must not violate the entry/exit criteria.
12525     CS->getCapturedDecl()->setNothrow();
12526   }
12527 
12528   OMPLoopBasedDirective::HelperExprs B;
12529   // In presence of clause 'collapse' with number of loops, it will
12530   // define the nested loops number.
12531   unsigned NestedLoopCount = checkOpenMPLoop(
12532       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12533       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12534       VarsWithImplicitDSA, B);
12535   if (NestedLoopCount == 0)
12536     return StmtError();
12537 
12538   assert((CurContext->isDependentContext() || B.builtAll()) &&
12539          "omp target teams distribute simd loop exprs were not built");
12540 
12541   if (!CurContext->isDependentContext()) {
12542     // Finalize the clauses that need pre-built expressions for CodeGen.
12543     for (OMPClause *C : Clauses) {
12544       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12545         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12546                                      B.NumIterations, *this, CurScope,
12547                                      DSAStack))
12548           return StmtError();
12549     }
12550   }
12551 
12552   if (checkSimdlenSafelenSpecified(*this, Clauses))
12553     return StmtError();
12554 
12555   setFunctionHasBranchProtectedScope();
12556   return OMPTargetTeamsDistributeSimdDirective::Create(
12557       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12558 }
12559 
12560 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12561                                           Stmt *AStmt, SourceLocation StartLoc,
12562                                           SourceLocation EndLoc) {
12563   auto SizesClauses =
12564       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12565   if (SizesClauses.empty()) {
12566     // A missing 'sizes' clause is already reported by the parser.
12567     return StmtError();
12568   }
12569   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12570   unsigned NumLoops = SizesClause->getNumSizes();
12571 
12572   // Empty statement should only be possible if there already was an error.
12573   if (!AStmt)
12574     return StmtError();
12575 
12576   // Verify and diagnose loop nest.
12577   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12578   Stmt *Body = nullptr;
12579   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
12580       OriginalInits(1);
12581   if (!OMPLoopBasedDirective::doForAllLoops(
12582           AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false,
12583           NumLoops,
12584           [this, &LoopHelpers, &Body, &OriginalInits](unsigned Cnt,
12585                                                       Stmt *CurStmt) {
12586             VarsWithInheritedDSAType TmpDSA;
12587             unsigned SingleNumLoops =
12588                 checkOpenMPLoop(OMPD_tile, nullptr, nullptr, CurStmt, *this,
12589                                 *DSAStack, TmpDSA, LoopHelpers[Cnt]);
12590             if (SingleNumLoops == 0)
12591               return true;
12592             assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12593             if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12594               OriginalInits.back().push_back(For->getInit());
12595               Body = For->getBody();
12596             } else {
12597               assert(isa<CXXForRangeStmt>(CurStmt) &&
12598                      "Expected canonical for or range-based for loops.");
12599               auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12600               OriginalInits.back().push_back(CXXFor->getBeginStmt());
12601               Body = CXXFor->getBody();
12602             }
12603             OriginalInits.emplace_back();
12604             return false;
12605           },
12606           [&OriginalInits](OMPLoopBasedDirective *Transform) {
12607             Stmt *DependentPreInits =
12608                 cast<OMPTileDirective>(Transform)->getPreInits();
12609             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
12610               OriginalInits.back().push_back(C);
12611           }))
12612     return StmtError();
12613 
12614   // Delay tiling to when template is completely instantiated.
12615   if (CurContext->isDependentContext())
12616     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12617                                     NumLoops, AStmt, nullptr, nullptr);
12618 
12619   SmallVector<Decl *, 4> PreInits;
12620 
12621   // Create iteration variables for the generated loops.
12622   SmallVector<VarDecl *, 4> FloorIndVars;
12623   SmallVector<VarDecl *, 4> TileIndVars;
12624   FloorIndVars.resize(NumLoops);
12625   TileIndVars.resize(NumLoops);
12626   for (unsigned I = 0; I < NumLoops; ++I) {
12627     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12628 
12629     assert(LoopHelper.Counters.size() == 1 &&
12630            "Expect single-dimensional loop iteration space");
12631     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12632     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12633     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12634     QualType CntTy = IterVarRef->getType();
12635 
12636     // Iteration variable for the floor (i.e. outer) loop.
12637     {
12638       std::string FloorCntName =
12639           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12640       VarDecl *FloorCntDecl =
12641           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12642       FloorIndVars[I] = FloorCntDecl;
12643     }
12644 
12645     // Iteration variable for the tile (i.e. inner) loop.
12646     {
12647       std::string TileCntName =
12648           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12649 
12650       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12651       // used by the expressions to derive the original iteration variable's
12652       // value from the logical iteration number.
12653       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12654       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12655       TileIndVars[I] = TileCntDecl;
12656     }
12657     for (auto &P : OriginalInits[I]) {
12658       if (auto *D = P.dyn_cast<Decl *>())
12659         PreInits.push_back(D);
12660       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12661         PreInits.append(PI->decl_begin(), PI->decl_end());
12662     }
12663     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12664       PreInits.append(PI->decl_begin(), PI->decl_end());
12665     // Gather declarations for the data members used as counters.
12666     for (Expr *CounterRef : LoopHelper.Counters) {
12667       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12668       if (isa<OMPCapturedExprDecl>(CounterDecl))
12669         PreInits.push_back(CounterDecl);
12670     }
12671   }
12672 
12673   // Once the original iteration values are set, append the innermost body.
12674   Stmt *Inner = Body;
12675 
12676   // Create tile loops from the inside to the outside.
12677   for (int I = NumLoops - 1; I >= 0; --I) {
12678     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12679     Expr *NumIterations = LoopHelper.NumIterations;
12680     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12681     QualType CntTy = OrigCntVar->getType();
12682     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12683     Scope *CurScope = getCurScope();
12684 
12685     // Commonly used variables.
12686     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12687                                            OrigCntVar->getExprLoc());
12688     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12689                                             OrigCntVar->getExprLoc());
12690 
12691     // For init-statement: auto .tile.iv = .floor.iv
12692     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12693                          /*DirectInit=*/false);
12694     Decl *CounterDecl = TileIndVars[I];
12695     StmtResult InitStmt = new (Context)
12696         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12697                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12698     if (!InitStmt.isUsable())
12699       return StmtError();
12700 
12701     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
12702     // NumIterations)
12703     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12704                                       BO_Add, FloorIV, DimTileSize);
12705     if (!EndOfTile.isUsable())
12706       return StmtError();
12707     ExprResult IsPartialTile =
12708         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
12709                    NumIterations, EndOfTile.get());
12710     if (!IsPartialTile.isUsable())
12711       return StmtError();
12712     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
12713         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
12714         IsPartialTile.get(), NumIterations, EndOfTile.get());
12715     if (!MinTileAndIterSpace.isUsable())
12716       return StmtError();
12717     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12718                                      BO_LT, TileIV, MinTileAndIterSpace.get());
12719     if (!CondExpr.isUsable())
12720       return StmtError();
12721 
12722     // For incr-statement: ++.tile.iv
12723     ExprResult IncrStmt =
12724         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
12725     if (!IncrStmt.isUsable())
12726       return StmtError();
12727 
12728     // Statements to set the original iteration variable's value from the
12729     // logical iteration number.
12730     // Generated for loop is:
12731     // Original_for_init;
12732     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
12733     // NumIterations); ++.tile.iv) {
12734     //   Original_Body;
12735     //   Original_counter_update;
12736     // }
12737     // FIXME: If the innermost body is an loop itself, inserting these
12738     // statements stops it being recognized  as a perfectly nested loop (e.g.
12739     // for applying tiling again). If this is the case, sink the expressions
12740     // further into the inner loop.
12741     SmallVector<Stmt *, 4> BodyParts;
12742     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
12743     BodyParts.push_back(Inner);
12744     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
12745                                  Inner->getEndLoc());
12746     Inner = new (Context)
12747         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12748                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12749                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12750   }
12751 
12752   // Create floor loops from the inside to the outside.
12753   for (int I = NumLoops - 1; I >= 0; --I) {
12754     auto &LoopHelper = LoopHelpers[I];
12755     Expr *NumIterations = LoopHelper.NumIterations;
12756     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12757     QualType CntTy = OrigCntVar->getType();
12758     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12759     Scope *CurScope = getCurScope();
12760 
12761     // Commonly used variables.
12762     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12763                                             OrigCntVar->getExprLoc());
12764 
12765     // For init-statement: auto .floor.iv = 0
12766     AddInitializerToDecl(
12767         FloorIndVars[I],
12768         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
12769         /*DirectInit=*/false);
12770     Decl *CounterDecl = FloorIndVars[I];
12771     StmtResult InitStmt = new (Context)
12772         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12773                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12774     if (!InitStmt.isUsable())
12775       return StmtError();
12776 
12777     // For cond-expression: .floor.iv < NumIterations
12778     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12779                                      BO_LT, FloorIV, NumIterations);
12780     if (!CondExpr.isUsable())
12781       return StmtError();
12782 
12783     // For incr-statement: .floor.iv += DimTileSize
12784     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
12785                                      BO_AddAssign, FloorIV, DimTileSize);
12786     if (!IncrStmt.isUsable())
12787       return StmtError();
12788 
12789     Inner = new (Context)
12790         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12791                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12792                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12793   }
12794 
12795   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
12796                                   AStmt, Inner,
12797                                   buildPreInits(Context, PreInits));
12798 }
12799 
12800 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
12801                                              SourceLocation StartLoc,
12802                                              SourceLocation LParenLoc,
12803                                              SourceLocation EndLoc) {
12804   OMPClause *Res = nullptr;
12805   switch (Kind) {
12806   case OMPC_final:
12807     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
12808     break;
12809   case OMPC_num_threads:
12810     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
12811     break;
12812   case OMPC_safelen:
12813     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
12814     break;
12815   case OMPC_simdlen:
12816     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
12817     break;
12818   case OMPC_allocator:
12819     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
12820     break;
12821   case OMPC_collapse:
12822     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
12823     break;
12824   case OMPC_ordered:
12825     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
12826     break;
12827   case OMPC_num_teams:
12828     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
12829     break;
12830   case OMPC_thread_limit:
12831     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
12832     break;
12833   case OMPC_priority:
12834     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
12835     break;
12836   case OMPC_grainsize:
12837     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
12838     break;
12839   case OMPC_num_tasks:
12840     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
12841     break;
12842   case OMPC_hint:
12843     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
12844     break;
12845   case OMPC_depobj:
12846     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
12847     break;
12848   case OMPC_detach:
12849     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
12850     break;
12851   case OMPC_novariants:
12852     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
12853     break;
12854   case OMPC_nocontext:
12855     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
12856     break;
12857   case OMPC_filter:
12858     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
12859     break;
12860   case OMPC_device:
12861   case OMPC_if:
12862   case OMPC_default:
12863   case OMPC_proc_bind:
12864   case OMPC_schedule:
12865   case OMPC_private:
12866   case OMPC_firstprivate:
12867   case OMPC_lastprivate:
12868   case OMPC_shared:
12869   case OMPC_reduction:
12870   case OMPC_task_reduction:
12871   case OMPC_in_reduction:
12872   case OMPC_linear:
12873   case OMPC_aligned:
12874   case OMPC_copyin:
12875   case OMPC_copyprivate:
12876   case OMPC_nowait:
12877   case OMPC_untied:
12878   case OMPC_mergeable:
12879   case OMPC_threadprivate:
12880   case OMPC_sizes:
12881   case OMPC_allocate:
12882   case OMPC_flush:
12883   case OMPC_read:
12884   case OMPC_write:
12885   case OMPC_update:
12886   case OMPC_capture:
12887   case OMPC_seq_cst:
12888   case OMPC_acq_rel:
12889   case OMPC_acquire:
12890   case OMPC_release:
12891   case OMPC_relaxed:
12892   case OMPC_depend:
12893   case OMPC_threads:
12894   case OMPC_simd:
12895   case OMPC_map:
12896   case OMPC_nogroup:
12897   case OMPC_dist_schedule:
12898   case OMPC_defaultmap:
12899   case OMPC_unknown:
12900   case OMPC_uniform:
12901   case OMPC_to:
12902   case OMPC_from:
12903   case OMPC_use_device_ptr:
12904   case OMPC_use_device_addr:
12905   case OMPC_is_device_ptr:
12906   case OMPC_unified_address:
12907   case OMPC_unified_shared_memory:
12908   case OMPC_reverse_offload:
12909   case OMPC_dynamic_allocators:
12910   case OMPC_atomic_default_mem_order:
12911   case OMPC_device_type:
12912   case OMPC_match:
12913   case OMPC_nontemporal:
12914   case OMPC_order:
12915   case OMPC_destroy:
12916   case OMPC_inclusive:
12917   case OMPC_exclusive:
12918   case OMPC_uses_allocators:
12919   case OMPC_affinity:
12920   default:
12921     llvm_unreachable("Clause is not allowed.");
12922   }
12923   return Res;
12924 }
12925 
12926 // An OpenMP directive such as 'target parallel' has two captured regions:
12927 // for the 'target' and 'parallel' respectively.  This function returns
12928 // the region in which to capture expressions associated with a clause.
12929 // A return value of OMPD_unknown signifies that the expression should not
12930 // be captured.
12931 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
12932     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
12933     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
12934   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12935   switch (CKind) {
12936   case OMPC_if:
12937     switch (DKind) {
12938     case OMPD_target_parallel_for_simd:
12939       if (OpenMPVersion >= 50 &&
12940           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12941         CaptureRegion = OMPD_parallel;
12942         break;
12943       }
12944       LLVM_FALLTHROUGH;
12945     case OMPD_target_parallel:
12946     case OMPD_target_parallel_for:
12947       // If this clause applies to the nested 'parallel' region, capture within
12948       // the 'target' region, otherwise do not capture.
12949       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12950         CaptureRegion = OMPD_target;
12951       break;
12952     case OMPD_target_teams_distribute_parallel_for_simd:
12953       if (OpenMPVersion >= 50 &&
12954           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12955         CaptureRegion = OMPD_parallel;
12956         break;
12957       }
12958       LLVM_FALLTHROUGH;
12959     case OMPD_target_teams_distribute_parallel_for:
12960       // If this clause applies to the nested 'parallel' region, capture within
12961       // the 'teams' region, otherwise do not capture.
12962       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12963         CaptureRegion = OMPD_teams;
12964       break;
12965     case OMPD_teams_distribute_parallel_for_simd:
12966       if (OpenMPVersion >= 50 &&
12967           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12968         CaptureRegion = OMPD_parallel;
12969         break;
12970       }
12971       LLVM_FALLTHROUGH;
12972     case OMPD_teams_distribute_parallel_for:
12973       CaptureRegion = OMPD_teams;
12974       break;
12975     case OMPD_target_update:
12976     case OMPD_target_enter_data:
12977     case OMPD_target_exit_data:
12978       CaptureRegion = OMPD_task;
12979       break;
12980     case OMPD_parallel_master_taskloop:
12981       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
12982         CaptureRegion = OMPD_parallel;
12983       break;
12984     case OMPD_parallel_master_taskloop_simd:
12985       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
12986           NameModifier == OMPD_taskloop) {
12987         CaptureRegion = OMPD_parallel;
12988         break;
12989       }
12990       if (OpenMPVersion <= 45)
12991         break;
12992       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12993         CaptureRegion = OMPD_taskloop;
12994       break;
12995     case OMPD_parallel_for_simd:
12996       if (OpenMPVersion <= 45)
12997         break;
12998       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12999         CaptureRegion = OMPD_parallel;
13000       break;
13001     case OMPD_taskloop_simd:
13002     case OMPD_master_taskloop_simd:
13003       if (OpenMPVersion <= 45)
13004         break;
13005       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13006         CaptureRegion = OMPD_taskloop;
13007       break;
13008     case OMPD_distribute_parallel_for_simd:
13009       if (OpenMPVersion <= 45)
13010         break;
13011       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13012         CaptureRegion = OMPD_parallel;
13013       break;
13014     case OMPD_target_simd:
13015       if (OpenMPVersion >= 50 &&
13016           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13017         CaptureRegion = OMPD_target;
13018       break;
13019     case OMPD_teams_distribute_simd:
13020     case OMPD_target_teams_distribute_simd:
13021       if (OpenMPVersion >= 50 &&
13022           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13023         CaptureRegion = OMPD_teams;
13024       break;
13025     case OMPD_cancel:
13026     case OMPD_parallel:
13027     case OMPD_parallel_master:
13028     case OMPD_parallel_sections:
13029     case OMPD_parallel_for:
13030     case OMPD_target:
13031     case OMPD_target_teams:
13032     case OMPD_target_teams_distribute:
13033     case OMPD_distribute_parallel_for:
13034     case OMPD_task:
13035     case OMPD_taskloop:
13036     case OMPD_master_taskloop:
13037     case OMPD_target_data:
13038     case OMPD_simd:
13039     case OMPD_for_simd:
13040     case OMPD_distribute_simd:
13041       // Do not capture if-clause expressions.
13042       break;
13043     case OMPD_threadprivate:
13044     case OMPD_allocate:
13045     case OMPD_taskyield:
13046     case OMPD_barrier:
13047     case OMPD_taskwait:
13048     case OMPD_cancellation_point:
13049     case OMPD_flush:
13050     case OMPD_depobj:
13051     case OMPD_scan:
13052     case OMPD_declare_reduction:
13053     case OMPD_declare_mapper:
13054     case OMPD_declare_simd:
13055     case OMPD_declare_variant:
13056     case OMPD_begin_declare_variant:
13057     case OMPD_end_declare_variant:
13058     case OMPD_declare_target:
13059     case OMPD_end_declare_target:
13060     case OMPD_teams:
13061     case OMPD_tile:
13062     case OMPD_for:
13063     case OMPD_sections:
13064     case OMPD_section:
13065     case OMPD_single:
13066     case OMPD_master:
13067     case OMPD_masked:
13068     case OMPD_critical:
13069     case OMPD_taskgroup:
13070     case OMPD_distribute:
13071     case OMPD_ordered:
13072     case OMPD_atomic:
13073     case OMPD_teams_distribute:
13074     case OMPD_requires:
13075       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13076     case OMPD_unknown:
13077     default:
13078       llvm_unreachable("Unknown OpenMP directive");
13079     }
13080     break;
13081   case OMPC_num_threads:
13082     switch (DKind) {
13083     case OMPD_target_parallel:
13084     case OMPD_target_parallel_for:
13085     case OMPD_target_parallel_for_simd:
13086       CaptureRegion = OMPD_target;
13087       break;
13088     case OMPD_teams_distribute_parallel_for:
13089     case OMPD_teams_distribute_parallel_for_simd:
13090     case OMPD_target_teams_distribute_parallel_for:
13091     case OMPD_target_teams_distribute_parallel_for_simd:
13092       CaptureRegion = OMPD_teams;
13093       break;
13094     case OMPD_parallel:
13095     case OMPD_parallel_master:
13096     case OMPD_parallel_sections:
13097     case OMPD_parallel_for:
13098     case OMPD_parallel_for_simd:
13099     case OMPD_distribute_parallel_for:
13100     case OMPD_distribute_parallel_for_simd:
13101     case OMPD_parallel_master_taskloop:
13102     case OMPD_parallel_master_taskloop_simd:
13103       // Do not capture num_threads-clause expressions.
13104       break;
13105     case OMPD_target_data:
13106     case OMPD_target_enter_data:
13107     case OMPD_target_exit_data:
13108     case OMPD_target_update:
13109     case OMPD_target:
13110     case OMPD_target_simd:
13111     case OMPD_target_teams:
13112     case OMPD_target_teams_distribute:
13113     case OMPD_target_teams_distribute_simd:
13114     case OMPD_cancel:
13115     case OMPD_task:
13116     case OMPD_taskloop:
13117     case OMPD_taskloop_simd:
13118     case OMPD_master_taskloop:
13119     case OMPD_master_taskloop_simd:
13120     case OMPD_threadprivate:
13121     case OMPD_allocate:
13122     case OMPD_taskyield:
13123     case OMPD_barrier:
13124     case OMPD_taskwait:
13125     case OMPD_cancellation_point:
13126     case OMPD_flush:
13127     case OMPD_depobj:
13128     case OMPD_scan:
13129     case OMPD_declare_reduction:
13130     case OMPD_declare_mapper:
13131     case OMPD_declare_simd:
13132     case OMPD_declare_variant:
13133     case OMPD_begin_declare_variant:
13134     case OMPD_end_declare_variant:
13135     case OMPD_declare_target:
13136     case OMPD_end_declare_target:
13137     case OMPD_teams:
13138     case OMPD_simd:
13139     case OMPD_tile:
13140     case OMPD_for:
13141     case OMPD_for_simd:
13142     case OMPD_sections:
13143     case OMPD_section:
13144     case OMPD_single:
13145     case OMPD_master:
13146     case OMPD_masked:
13147     case OMPD_critical:
13148     case OMPD_taskgroup:
13149     case OMPD_distribute:
13150     case OMPD_ordered:
13151     case OMPD_atomic:
13152     case OMPD_distribute_simd:
13153     case OMPD_teams_distribute:
13154     case OMPD_teams_distribute_simd:
13155     case OMPD_requires:
13156       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13157     case OMPD_unknown:
13158     default:
13159       llvm_unreachable("Unknown OpenMP directive");
13160     }
13161     break;
13162   case OMPC_num_teams:
13163     switch (DKind) {
13164     case OMPD_target_teams:
13165     case OMPD_target_teams_distribute:
13166     case OMPD_target_teams_distribute_simd:
13167     case OMPD_target_teams_distribute_parallel_for:
13168     case OMPD_target_teams_distribute_parallel_for_simd:
13169       CaptureRegion = OMPD_target;
13170       break;
13171     case OMPD_teams_distribute_parallel_for:
13172     case OMPD_teams_distribute_parallel_for_simd:
13173     case OMPD_teams:
13174     case OMPD_teams_distribute:
13175     case OMPD_teams_distribute_simd:
13176       // Do not capture num_teams-clause expressions.
13177       break;
13178     case OMPD_distribute_parallel_for:
13179     case OMPD_distribute_parallel_for_simd:
13180     case OMPD_task:
13181     case OMPD_taskloop:
13182     case OMPD_taskloop_simd:
13183     case OMPD_master_taskloop:
13184     case OMPD_master_taskloop_simd:
13185     case OMPD_parallel_master_taskloop:
13186     case OMPD_parallel_master_taskloop_simd:
13187     case OMPD_target_data:
13188     case OMPD_target_enter_data:
13189     case OMPD_target_exit_data:
13190     case OMPD_target_update:
13191     case OMPD_cancel:
13192     case OMPD_parallel:
13193     case OMPD_parallel_master:
13194     case OMPD_parallel_sections:
13195     case OMPD_parallel_for:
13196     case OMPD_parallel_for_simd:
13197     case OMPD_target:
13198     case OMPD_target_simd:
13199     case OMPD_target_parallel:
13200     case OMPD_target_parallel_for:
13201     case OMPD_target_parallel_for_simd:
13202     case OMPD_threadprivate:
13203     case OMPD_allocate:
13204     case OMPD_taskyield:
13205     case OMPD_barrier:
13206     case OMPD_taskwait:
13207     case OMPD_cancellation_point:
13208     case OMPD_flush:
13209     case OMPD_depobj:
13210     case OMPD_scan:
13211     case OMPD_declare_reduction:
13212     case OMPD_declare_mapper:
13213     case OMPD_declare_simd:
13214     case OMPD_declare_variant:
13215     case OMPD_begin_declare_variant:
13216     case OMPD_end_declare_variant:
13217     case OMPD_declare_target:
13218     case OMPD_end_declare_target:
13219     case OMPD_simd:
13220     case OMPD_tile:
13221     case OMPD_for:
13222     case OMPD_for_simd:
13223     case OMPD_sections:
13224     case OMPD_section:
13225     case OMPD_single:
13226     case OMPD_master:
13227     case OMPD_masked:
13228     case OMPD_critical:
13229     case OMPD_taskgroup:
13230     case OMPD_distribute:
13231     case OMPD_ordered:
13232     case OMPD_atomic:
13233     case OMPD_distribute_simd:
13234     case OMPD_requires:
13235       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13236     case OMPD_unknown:
13237     default:
13238       llvm_unreachable("Unknown OpenMP directive");
13239     }
13240     break;
13241   case OMPC_thread_limit:
13242     switch (DKind) {
13243     case OMPD_target_teams:
13244     case OMPD_target_teams_distribute:
13245     case OMPD_target_teams_distribute_simd:
13246     case OMPD_target_teams_distribute_parallel_for:
13247     case OMPD_target_teams_distribute_parallel_for_simd:
13248       CaptureRegion = OMPD_target;
13249       break;
13250     case OMPD_teams_distribute_parallel_for:
13251     case OMPD_teams_distribute_parallel_for_simd:
13252     case OMPD_teams:
13253     case OMPD_teams_distribute:
13254     case OMPD_teams_distribute_simd:
13255       // Do not capture thread_limit-clause expressions.
13256       break;
13257     case OMPD_distribute_parallel_for:
13258     case OMPD_distribute_parallel_for_simd:
13259     case OMPD_task:
13260     case OMPD_taskloop:
13261     case OMPD_taskloop_simd:
13262     case OMPD_master_taskloop:
13263     case OMPD_master_taskloop_simd:
13264     case OMPD_parallel_master_taskloop:
13265     case OMPD_parallel_master_taskloop_simd:
13266     case OMPD_target_data:
13267     case OMPD_target_enter_data:
13268     case OMPD_target_exit_data:
13269     case OMPD_target_update:
13270     case OMPD_cancel:
13271     case OMPD_parallel:
13272     case OMPD_parallel_master:
13273     case OMPD_parallel_sections:
13274     case OMPD_parallel_for:
13275     case OMPD_parallel_for_simd:
13276     case OMPD_target:
13277     case OMPD_target_simd:
13278     case OMPD_target_parallel:
13279     case OMPD_target_parallel_for:
13280     case OMPD_target_parallel_for_simd:
13281     case OMPD_threadprivate:
13282     case OMPD_allocate:
13283     case OMPD_taskyield:
13284     case OMPD_barrier:
13285     case OMPD_taskwait:
13286     case OMPD_cancellation_point:
13287     case OMPD_flush:
13288     case OMPD_depobj:
13289     case OMPD_scan:
13290     case OMPD_declare_reduction:
13291     case OMPD_declare_mapper:
13292     case OMPD_declare_simd:
13293     case OMPD_declare_variant:
13294     case OMPD_begin_declare_variant:
13295     case OMPD_end_declare_variant:
13296     case OMPD_declare_target:
13297     case OMPD_end_declare_target:
13298     case OMPD_simd:
13299     case OMPD_tile:
13300     case OMPD_for:
13301     case OMPD_for_simd:
13302     case OMPD_sections:
13303     case OMPD_section:
13304     case OMPD_single:
13305     case OMPD_master:
13306     case OMPD_masked:
13307     case OMPD_critical:
13308     case OMPD_taskgroup:
13309     case OMPD_distribute:
13310     case OMPD_ordered:
13311     case OMPD_atomic:
13312     case OMPD_distribute_simd:
13313     case OMPD_requires:
13314       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13315     case OMPD_unknown:
13316     default:
13317       llvm_unreachable("Unknown OpenMP directive");
13318     }
13319     break;
13320   case OMPC_schedule:
13321     switch (DKind) {
13322     case OMPD_parallel_for:
13323     case OMPD_parallel_for_simd:
13324     case OMPD_distribute_parallel_for:
13325     case OMPD_distribute_parallel_for_simd:
13326     case OMPD_teams_distribute_parallel_for:
13327     case OMPD_teams_distribute_parallel_for_simd:
13328     case OMPD_target_parallel_for:
13329     case OMPD_target_parallel_for_simd:
13330     case OMPD_target_teams_distribute_parallel_for:
13331     case OMPD_target_teams_distribute_parallel_for_simd:
13332       CaptureRegion = OMPD_parallel;
13333       break;
13334     case OMPD_for:
13335     case OMPD_for_simd:
13336       // Do not capture schedule-clause expressions.
13337       break;
13338     case OMPD_task:
13339     case OMPD_taskloop:
13340     case OMPD_taskloop_simd:
13341     case OMPD_master_taskloop:
13342     case OMPD_master_taskloop_simd:
13343     case OMPD_parallel_master_taskloop:
13344     case OMPD_parallel_master_taskloop_simd:
13345     case OMPD_target_data:
13346     case OMPD_target_enter_data:
13347     case OMPD_target_exit_data:
13348     case OMPD_target_update:
13349     case OMPD_teams:
13350     case OMPD_teams_distribute:
13351     case OMPD_teams_distribute_simd:
13352     case OMPD_target_teams_distribute:
13353     case OMPD_target_teams_distribute_simd:
13354     case OMPD_target:
13355     case OMPD_target_simd:
13356     case OMPD_target_parallel:
13357     case OMPD_cancel:
13358     case OMPD_parallel:
13359     case OMPD_parallel_master:
13360     case OMPD_parallel_sections:
13361     case OMPD_threadprivate:
13362     case OMPD_allocate:
13363     case OMPD_taskyield:
13364     case OMPD_barrier:
13365     case OMPD_taskwait:
13366     case OMPD_cancellation_point:
13367     case OMPD_flush:
13368     case OMPD_depobj:
13369     case OMPD_scan:
13370     case OMPD_declare_reduction:
13371     case OMPD_declare_mapper:
13372     case OMPD_declare_simd:
13373     case OMPD_declare_variant:
13374     case OMPD_begin_declare_variant:
13375     case OMPD_end_declare_variant:
13376     case OMPD_declare_target:
13377     case OMPD_end_declare_target:
13378     case OMPD_simd:
13379     case OMPD_tile:
13380     case OMPD_sections:
13381     case OMPD_section:
13382     case OMPD_single:
13383     case OMPD_master:
13384     case OMPD_masked:
13385     case OMPD_critical:
13386     case OMPD_taskgroup:
13387     case OMPD_distribute:
13388     case OMPD_ordered:
13389     case OMPD_atomic:
13390     case OMPD_distribute_simd:
13391     case OMPD_target_teams:
13392     case OMPD_requires:
13393       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13394     case OMPD_unknown:
13395     default:
13396       llvm_unreachable("Unknown OpenMP directive");
13397     }
13398     break;
13399   case OMPC_dist_schedule:
13400     switch (DKind) {
13401     case OMPD_teams_distribute_parallel_for:
13402     case OMPD_teams_distribute_parallel_for_simd:
13403     case OMPD_teams_distribute:
13404     case OMPD_teams_distribute_simd:
13405     case OMPD_target_teams_distribute_parallel_for:
13406     case OMPD_target_teams_distribute_parallel_for_simd:
13407     case OMPD_target_teams_distribute:
13408     case OMPD_target_teams_distribute_simd:
13409       CaptureRegion = OMPD_teams;
13410       break;
13411     case OMPD_distribute_parallel_for:
13412     case OMPD_distribute_parallel_for_simd:
13413     case OMPD_distribute:
13414     case OMPD_distribute_simd:
13415       // Do not capture dist_schedule-clause expressions.
13416       break;
13417     case OMPD_parallel_for:
13418     case OMPD_parallel_for_simd:
13419     case OMPD_target_parallel_for_simd:
13420     case OMPD_target_parallel_for:
13421     case OMPD_task:
13422     case OMPD_taskloop:
13423     case OMPD_taskloop_simd:
13424     case OMPD_master_taskloop:
13425     case OMPD_master_taskloop_simd:
13426     case OMPD_parallel_master_taskloop:
13427     case OMPD_parallel_master_taskloop_simd:
13428     case OMPD_target_data:
13429     case OMPD_target_enter_data:
13430     case OMPD_target_exit_data:
13431     case OMPD_target_update:
13432     case OMPD_teams:
13433     case OMPD_target:
13434     case OMPD_target_simd:
13435     case OMPD_target_parallel:
13436     case OMPD_cancel:
13437     case OMPD_parallel:
13438     case OMPD_parallel_master:
13439     case OMPD_parallel_sections:
13440     case OMPD_threadprivate:
13441     case OMPD_allocate:
13442     case OMPD_taskyield:
13443     case OMPD_barrier:
13444     case OMPD_taskwait:
13445     case OMPD_cancellation_point:
13446     case OMPD_flush:
13447     case OMPD_depobj:
13448     case OMPD_scan:
13449     case OMPD_declare_reduction:
13450     case OMPD_declare_mapper:
13451     case OMPD_declare_simd:
13452     case OMPD_declare_variant:
13453     case OMPD_begin_declare_variant:
13454     case OMPD_end_declare_variant:
13455     case OMPD_declare_target:
13456     case OMPD_end_declare_target:
13457     case OMPD_simd:
13458     case OMPD_tile:
13459     case OMPD_for:
13460     case OMPD_for_simd:
13461     case OMPD_sections:
13462     case OMPD_section:
13463     case OMPD_single:
13464     case OMPD_master:
13465     case OMPD_masked:
13466     case OMPD_critical:
13467     case OMPD_taskgroup:
13468     case OMPD_ordered:
13469     case OMPD_atomic:
13470     case OMPD_target_teams:
13471     case OMPD_requires:
13472       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
13473     case OMPD_unknown:
13474     default:
13475       llvm_unreachable("Unknown OpenMP directive");
13476     }
13477     break;
13478   case OMPC_device:
13479     switch (DKind) {
13480     case OMPD_target_update:
13481     case OMPD_target_enter_data:
13482     case OMPD_target_exit_data:
13483     case OMPD_target:
13484     case OMPD_target_simd:
13485     case OMPD_target_teams:
13486     case OMPD_target_parallel:
13487     case OMPD_target_teams_distribute:
13488     case OMPD_target_teams_distribute_simd:
13489     case OMPD_target_parallel_for:
13490     case OMPD_target_parallel_for_simd:
13491     case OMPD_target_teams_distribute_parallel_for:
13492     case OMPD_target_teams_distribute_parallel_for_simd:
13493     case OMPD_dispatch:
13494       CaptureRegion = OMPD_task;
13495       break;
13496     case OMPD_target_data:
13497     case OMPD_interop:
13498       // Do not capture device-clause expressions.
13499       break;
13500     case OMPD_teams_distribute_parallel_for:
13501     case OMPD_teams_distribute_parallel_for_simd:
13502     case OMPD_teams:
13503     case OMPD_teams_distribute:
13504     case OMPD_teams_distribute_simd:
13505     case OMPD_distribute_parallel_for:
13506     case OMPD_distribute_parallel_for_simd:
13507     case OMPD_task:
13508     case OMPD_taskloop:
13509     case OMPD_taskloop_simd:
13510     case OMPD_master_taskloop:
13511     case OMPD_master_taskloop_simd:
13512     case OMPD_parallel_master_taskloop:
13513     case OMPD_parallel_master_taskloop_simd:
13514     case OMPD_cancel:
13515     case OMPD_parallel:
13516     case OMPD_parallel_master:
13517     case OMPD_parallel_sections:
13518     case OMPD_parallel_for:
13519     case OMPD_parallel_for_simd:
13520     case OMPD_threadprivate:
13521     case OMPD_allocate:
13522     case OMPD_taskyield:
13523     case OMPD_barrier:
13524     case OMPD_taskwait:
13525     case OMPD_cancellation_point:
13526     case OMPD_flush:
13527     case OMPD_depobj:
13528     case OMPD_scan:
13529     case OMPD_declare_reduction:
13530     case OMPD_declare_mapper:
13531     case OMPD_declare_simd:
13532     case OMPD_declare_variant:
13533     case OMPD_begin_declare_variant:
13534     case OMPD_end_declare_variant:
13535     case OMPD_declare_target:
13536     case OMPD_end_declare_target:
13537     case OMPD_simd:
13538     case OMPD_tile:
13539     case OMPD_for:
13540     case OMPD_for_simd:
13541     case OMPD_sections:
13542     case OMPD_section:
13543     case OMPD_single:
13544     case OMPD_master:
13545     case OMPD_masked:
13546     case OMPD_critical:
13547     case OMPD_taskgroup:
13548     case OMPD_distribute:
13549     case OMPD_ordered:
13550     case OMPD_atomic:
13551     case OMPD_distribute_simd:
13552     case OMPD_requires:
13553       llvm_unreachable("Unexpected OpenMP directive with device-clause");
13554     case OMPD_unknown:
13555     default:
13556       llvm_unreachable("Unknown OpenMP directive");
13557     }
13558     break;
13559   case OMPC_grainsize:
13560   case OMPC_num_tasks:
13561   case OMPC_final:
13562   case OMPC_priority:
13563     switch (DKind) {
13564     case OMPD_task:
13565     case OMPD_taskloop:
13566     case OMPD_taskloop_simd:
13567     case OMPD_master_taskloop:
13568     case OMPD_master_taskloop_simd:
13569       break;
13570     case OMPD_parallel_master_taskloop:
13571     case OMPD_parallel_master_taskloop_simd:
13572       CaptureRegion = OMPD_parallel;
13573       break;
13574     case OMPD_target_update:
13575     case OMPD_target_enter_data:
13576     case OMPD_target_exit_data:
13577     case OMPD_target:
13578     case OMPD_target_simd:
13579     case OMPD_target_teams:
13580     case OMPD_target_parallel:
13581     case OMPD_target_teams_distribute:
13582     case OMPD_target_teams_distribute_simd:
13583     case OMPD_target_parallel_for:
13584     case OMPD_target_parallel_for_simd:
13585     case OMPD_target_teams_distribute_parallel_for:
13586     case OMPD_target_teams_distribute_parallel_for_simd:
13587     case OMPD_target_data:
13588     case OMPD_teams_distribute_parallel_for:
13589     case OMPD_teams_distribute_parallel_for_simd:
13590     case OMPD_teams:
13591     case OMPD_teams_distribute:
13592     case OMPD_teams_distribute_simd:
13593     case OMPD_distribute_parallel_for:
13594     case OMPD_distribute_parallel_for_simd:
13595     case OMPD_cancel:
13596     case OMPD_parallel:
13597     case OMPD_parallel_master:
13598     case OMPD_parallel_sections:
13599     case OMPD_parallel_for:
13600     case OMPD_parallel_for_simd:
13601     case OMPD_threadprivate:
13602     case OMPD_allocate:
13603     case OMPD_taskyield:
13604     case OMPD_barrier:
13605     case OMPD_taskwait:
13606     case OMPD_cancellation_point:
13607     case OMPD_flush:
13608     case OMPD_depobj:
13609     case OMPD_scan:
13610     case OMPD_declare_reduction:
13611     case OMPD_declare_mapper:
13612     case OMPD_declare_simd:
13613     case OMPD_declare_variant:
13614     case OMPD_begin_declare_variant:
13615     case OMPD_end_declare_variant:
13616     case OMPD_declare_target:
13617     case OMPD_end_declare_target:
13618     case OMPD_simd:
13619     case OMPD_tile:
13620     case OMPD_for:
13621     case OMPD_for_simd:
13622     case OMPD_sections:
13623     case OMPD_section:
13624     case OMPD_single:
13625     case OMPD_master:
13626     case OMPD_masked:
13627     case OMPD_critical:
13628     case OMPD_taskgroup:
13629     case OMPD_distribute:
13630     case OMPD_ordered:
13631     case OMPD_atomic:
13632     case OMPD_distribute_simd:
13633     case OMPD_requires:
13634       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
13635     case OMPD_unknown:
13636     default:
13637       llvm_unreachable("Unknown OpenMP directive");
13638     }
13639     break;
13640   case OMPC_novariants:
13641   case OMPC_nocontext:
13642     switch (DKind) {
13643     case OMPD_dispatch:
13644       CaptureRegion = OMPD_task;
13645       break;
13646     default:
13647       llvm_unreachable("Unexpected OpenMP directive");
13648     }
13649     break;
13650   case OMPC_filter:
13651     // Do not capture filter-clause expressions.
13652     break;
13653   case OMPC_firstprivate:
13654   case OMPC_lastprivate:
13655   case OMPC_reduction:
13656   case OMPC_task_reduction:
13657   case OMPC_in_reduction:
13658   case OMPC_linear:
13659   case OMPC_default:
13660   case OMPC_proc_bind:
13661   case OMPC_safelen:
13662   case OMPC_simdlen:
13663   case OMPC_sizes:
13664   case OMPC_allocator:
13665   case OMPC_collapse:
13666   case OMPC_private:
13667   case OMPC_shared:
13668   case OMPC_aligned:
13669   case OMPC_copyin:
13670   case OMPC_copyprivate:
13671   case OMPC_ordered:
13672   case OMPC_nowait:
13673   case OMPC_untied:
13674   case OMPC_mergeable:
13675   case OMPC_threadprivate:
13676   case OMPC_allocate:
13677   case OMPC_flush:
13678   case OMPC_depobj:
13679   case OMPC_read:
13680   case OMPC_write:
13681   case OMPC_update:
13682   case OMPC_capture:
13683   case OMPC_seq_cst:
13684   case OMPC_acq_rel:
13685   case OMPC_acquire:
13686   case OMPC_release:
13687   case OMPC_relaxed:
13688   case OMPC_depend:
13689   case OMPC_threads:
13690   case OMPC_simd:
13691   case OMPC_map:
13692   case OMPC_nogroup:
13693   case OMPC_hint:
13694   case OMPC_defaultmap:
13695   case OMPC_unknown:
13696   case OMPC_uniform:
13697   case OMPC_to:
13698   case OMPC_from:
13699   case OMPC_use_device_ptr:
13700   case OMPC_use_device_addr:
13701   case OMPC_is_device_ptr:
13702   case OMPC_unified_address:
13703   case OMPC_unified_shared_memory:
13704   case OMPC_reverse_offload:
13705   case OMPC_dynamic_allocators:
13706   case OMPC_atomic_default_mem_order:
13707   case OMPC_device_type:
13708   case OMPC_match:
13709   case OMPC_nontemporal:
13710   case OMPC_order:
13711   case OMPC_destroy:
13712   case OMPC_detach:
13713   case OMPC_inclusive:
13714   case OMPC_exclusive:
13715   case OMPC_uses_allocators:
13716   case OMPC_affinity:
13717   default:
13718     llvm_unreachable("Unexpected OpenMP clause.");
13719   }
13720   return CaptureRegion;
13721 }
13722 
13723 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
13724                                      Expr *Condition, SourceLocation StartLoc,
13725                                      SourceLocation LParenLoc,
13726                                      SourceLocation NameModifierLoc,
13727                                      SourceLocation ColonLoc,
13728                                      SourceLocation EndLoc) {
13729   Expr *ValExpr = Condition;
13730   Stmt *HelperValStmt = nullptr;
13731   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13732   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
13733       !Condition->isInstantiationDependent() &&
13734       !Condition->containsUnexpandedParameterPack()) {
13735     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
13736     if (Val.isInvalid())
13737       return nullptr;
13738 
13739     ValExpr = Val.get();
13740 
13741     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13742     CaptureRegion = getOpenMPCaptureRegionForClause(
13743         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
13744     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13745       ValExpr = MakeFullExpr(ValExpr).get();
13746       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13747       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13748       HelperValStmt = buildPreInits(Context, Captures);
13749     }
13750   }
13751 
13752   return new (Context)
13753       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
13754                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
13755 }
13756 
13757 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
13758                                         SourceLocation StartLoc,
13759                                         SourceLocation LParenLoc,
13760                                         SourceLocation EndLoc) {
13761   Expr *ValExpr = Condition;
13762   Stmt *HelperValStmt = nullptr;
13763   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13764   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
13765       !Condition->isInstantiationDependent() &&
13766       !Condition->containsUnexpandedParameterPack()) {
13767     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
13768     if (Val.isInvalid())
13769       return nullptr;
13770 
13771     ValExpr = MakeFullExpr(Val.get()).get();
13772 
13773     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13774     CaptureRegion =
13775         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
13776     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13777       ValExpr = MakeFullExpr(ValExpr).get();
13778       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13779       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13780       HelperValStmt = buildPreInits(Context, Captures);
13781     }
13782   }
13783 
13784   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
13785                                       StartLoc, LParenLoc, EndLoc);
13786 }
13787 
13788 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
13789                                                         Expr *Op) {
13790   if (!Op)
13791     return ExprError();
13792 
13793   class IntConvertDiagnoser : public ICEConvertDiagnoser {
13794   public:
13795     IntConvertDiagnoser()
13796         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
13797     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13798                                          QualType T) override {
13799       return S.Diag(Loc, diag::err_omp_not_integral) << T;
13800     }
13801     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
13802                                              QualType T) override {
13803       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
13804     }
13805     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
13806                                                QualType T,
13807                                                QualType ConvTy) override {
13808       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
13809     }
13810     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
13811                                            QualType ConvTy) override {
13812       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
13813              << ConvTy->isEnumeralType() << ConvTy;
13814     }
13815     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
13816                                             QualType T) override {
13817       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
13818     }
13819     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
13820                                         QualType ConvTy) override {
13821       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
13822              << ConvTy->isEnumeralType() << ConvTy;
13823     }
13824     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
13825                                              QualType) override {
13826       llvm_unreachable("conversion functions are permitted");
13827     }
13828   } ConvertDiagnoser;
13829   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
13830 }
13831 
13832 static bool
13833 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
13834                           bool StrictlyPositive, bool BuildCapture = false,
13835                           OpenMPDirectiveKind DKind = OMPD_unknown,
13836                           OpenMPDirectiveKind *CaptureRegion = nullptr,
13837                           Stmt **HelperValStmt = nullptr) {
13838   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
13839       !ValExpr->isInstantiationDependent()) {
13840     SourceLocation Loc = ValExpr->getExprLoc();
13841     ExprResult Value =
13842         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
13843     if (Value.isInvalid())
13844       return false;
13845 
13846     ValExpr = Value.get();
13847     // The expression must evaluate to a non-negative integer value.
13848     if (Optional<llvm::APSInt> Result =
13849             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
13850       if (Result->isSigned() &&
13851           !((!StrictlyPositive && Result->isNonNegative()) ||
13852             (StrictlyPositive && Result->isStrictlyPositive()))) {
13853         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
13854             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
13855             << ValExpr->getSourceRange();
13856         return false;
13857       }
13858     }
13859     if (!BuildCapture)
13860       return true;
13861     *CaptureRegion =
13862         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
13863     if (*CaptureRegion != OMPD_unknown &&
13864         !SemaRef.CurContext->isDependentContext()) {
13865       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
13866       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13867       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
13868       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
13869     }
13870   }
13871   return true;
13872 }
13873 
13874 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
13875                                              SourceLocation StartLoc,
13876                                              SourceLocation LParenLoc,
13877                                              SourceLocation EndLoc) {
13878   Expr *ValExpr = NumThreads;
13879   Stmt *HelperValStmt = nullptr;
13880 
13881   // OpenMP [2.5, Restrictions]
13882   //  The num_threads expression must evaluate to a positive integer value.
13883   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
13884                                  /*StrictlyPositive=*/true))
13885     return nullptr;
13886 
13887   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13888   OpenMPDirectiveKind CaptureRegion =
13889       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
13890   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13891     ValExpr = MakeFullExpr(ValExpr).get();
13892     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13893     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13894     HelperValStmt = buildPreInits(Context, Captures);
13895   }
13896 
13897   return new (Context) OMPNumThreadsClause(
13898       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13899 }
13900 
13901 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
13902                                                        OpenMPClauseKind CKind,
13903                                                        bool StrictlyPositive) {
13904   if (!E)
13905     return ExprError();
13906   if (E->isValueDependent() || E->isTypeDependent() ||
13907       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
13908     return E;
13909   llvm::APSInt Result;
13910   ExprResult ICE =
13911       VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
13912   if (ICE.isInvalid())
13913     return ExprError();
13914   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
13915       (!StrictlyPositive && !Result.isNonNegative())) {
13916     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
13917         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
13918         << E->getSourceRange();
13919     return ExprError();
13920   }
13921   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
13922     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
13923         << E->getSourceRange();
13924     return ExprError();
13925   }
13926   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
13927     DSAStack->setAssociatedLoops(Result.getExtValue());
13928   else if (CKind == OMPC_ordered)
13929     DSAStack->setAssociatedLoops(Result.getExtValue());
13930   return ICE;
13931 }
13932 
13933 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
13934                                           SourceLocation LParenLoc,
13935                                           SourceLocation EndLoc) {
13936   // OpenMP [2.8.1, simd construct, Description]
13937   // The parameter of the safelen clause must be a constant
13938   // positive integer expression.
13939   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
13940   if (Safelen.isInvalid())
13941     return nullptr;
13942   return new (Context)
13943       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
13944 }
13945 
13946 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
13947                                           SourceLocation LParenLoc,
13948                                           SourceLocation EndLoc) {
13949   // OpenMP [2.8.1, simd construct, Description]
13950   // The parameter of the simdlen clause must be a constant
13951   // positive integer expression.
13952   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
13953   if (Simdlen.isInvalid())
13954     return nullptr;
13955   return new (Context)
13956       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
13957 }
13958 
13959 /// Tries to find omp_allocator_handle_t type.
13960 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
13961                                     DSAStackTy *Stack) {
13962   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
13963   if (!OMPAllocatorHandleT.isNull())
13964     return true;
13965   // Build the predefined allocator expressions.
13966   bool ErrorFound = false;
13967   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
13968     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
13969     StringRef Allocator =
13970         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
13971     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
13972     auto *VD = dyn_cast_or_null<ValueDecl>(
13973         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
13974     if (!VD) {
13975       ErrorFound = true;
13976       break;
13977     }
13978     QualType AllocatorType =
13979         VD->getType().getNonLValueExprType(S.getASTContext());
13980     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
13981     if (!Res.isUsable()) {
13982       ErrorFound = true;
13983       break;
13984     }
13985     if (OMPAllocatorHandleT.isNull())
13986       OMPAllocatorHandleT = AllocatorType;
13987     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
13988       ErrorFound = true;
13989       break;
13990     }
13991     Stack->setAllocator(AllocatorKind, Res.get());
13992   }
13993   if (ErrorFound) {
13994     S.Diag(Loc, diag::err_omp_implied_type_not_found)
13995         << "omp_allocator_handle_t";
13996     return false;
13997   }
13998   OMPAllocatorHandleT.addConst();
13999   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
14000   return true;
14001 }
14002 
14003 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
14004                                             SourceLocation LParenLoc,
14005                                             SourceLocation EndLoc) {
14006   // OpenMP [2.11.3, allocate Directive, Description]
14007   // allocator is an expression of omp_allocator_handle_t type.
14008   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
14009     return nullptr;
14010 
14011   ExprResult Allocator = DefaultLvalueConversion(A);
14012   if (Allocator.isInvalid())
14013     return nullptr;
14014   Allocator = PerformImplicitConversion(Allocator.get(),
14015                                         DSAStack->getOMPAllocatorHandleT(),
14016                                         Sema::AA_Initializing,
14017                                         /*AllowExplicit=*/true);
14018   if (Allocator.isInvalid())
14019     return nullptr;
14020   return new (Context)
14021       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
14022 }
14023 
14024 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
14025                                            SourceLocation StartLoc,
14026                                            SourceLocation LParenLoc,
14027                                            SourceLocation EndLoc) {
14028   // OpenMP [2.7.1, loop construct, Description]
14029   // OpenMP [2.8.1, simd construct, Description]
14030   // OpenMP [2.9.6, distribute construct, Description]
14031   // The parameter of the collapse clause must be a constant
14032   // positive integer expression.
14033   ExprResult NumForLoopsResult =
14034       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
14035   if (NumForLoopsResult.isInvalid())
14036     return nullptr;
14037   return new (Context)
14038       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
14039 }
14040 
14041 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
14042                                           SourceLocation EndLoc,
14043                                           SourceLocation LParenLoc,
14044                                           Expr *NumForLoops) {
14045   // OpenMP [2.7.1, loop construct, Description]
14046   // OpenMP [2.8.1, simd construct, Description]
14047   // OpenMP [2.9.6, distribute construct, Description]
14048   // The parameter of the ordered clause must be a constant
14049   // positive integer expression if any.
14050   if (NumForLoops && LParenLoc.isValid()) {
14051     ExprResult NumForLoopsResult =
14052         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
14053     if (NumForLoopsResult.isInvalid())
14054       return nullptr;
14055     NumForLoops = NumForLoopsResult.get();
14056   } else {
14057     NumForLoops = nullptr;
14058   }
14059   auto *Clause = OMPOrderedClause::Create(
14060       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
14061       StartLoc, LParenLoc, EndLoc);
14062   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
14063   return Clause;
14064 }
14065 
14066 OMPClause *Sema::ActOnOpenMPSimpleClause(
14067     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
14068     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14069   OMPClause *Res = nullptr;
14070   switch (Kind) {
14071   case OMPC_default:
14072     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
14073                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14074     break;
14075   case OMPC_proc_bind:
14076     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14077                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14078     break;
14079   case OMPC_atomic_default_mem_order:
14080     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14081         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14082         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14083     break;
14084   case OMPC_order:
14085     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14086                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14087     break;
14088   case OMPC_update:
14089     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14090                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14091     break;
14092   case OMPC_if:
14093   case OMPC_final:
14094   case OMPC_num_threads:
14095   case OMPC_safelen:
14096   case OMPC_simdlen:
14097   case OMPC_sizes:
14098   case OMPC_allocator:
14099   case OMPC_collapse:
14100   case OMPC_schedule:
14101   case OMPC_private:
14102   case OMPC_firstprivate:
14103   case OMPC_lastprivate:
14104   case OMPC_shared:
14105   case OMPC_reduction:
14106   case OMPC_task_reduction:
14107   case OMPC_in_reduction:
14108   case OMPC_linear:
14109   case OMPC_aligned:
14110   case OMPC_copyin:
14111   case OMPC_copyprivate:
14112   case OMPC_ordered:
14113   case OMPC_nowait:
14114   case OMPC_untied:
14115   case OMPC_mergeable:
14116   case OMPC_threadprivate:
14117   case OMPC_allocate:
14118   case OMPC_flush:
14119   case OMPC_depobj:
14120   case OMPC_read:
14121   case OMPC_write:
14122   case OMPC_capture:
14123   case OMPC_seq_cst:
14124   case OMPC_acq_rel:
14125   case OMPC_acquire:
14126   case OMPC_release:
14127   case OMPC_relaxed:
14128   case OMPC_depend:
14129   case OMPC_device:
14130   case OMPC_threads:
14131   case OMPC_simd:
14132   case OMPC_map:
14133   case OMPC_num_teams:
14134   case OMPC_thread_limit:
14135   case OMPC_priority:
14136   case OMPC_grainsize:
14137   case OMPC_nogroup:
14138   case OMPC_num_tasks:
14139   case OMPC_hint:
14140   case OMPC_dist_schedule:
14141   case OMPC_defaultmap:
14142   case OMPC_unknown:
14143   case OMPC_uniform:
14144   case OMPC_to:
14145   case OMPC_from:
14146   case OMPC_use_device_ptr:
14147   case OMPC_use_device_addr:
14148   case OMPC_is_device_ptr:
14149   case OMPC_unified_address:
14150   case OMPC_unified_shared_memory:
14151   case OMPC_reverse_offload:
14152   case OMPC_dynamic_allocators:
14153   case OMPC_device_type:
14154   case OMPC_match:
14155   case OMPC_nontemporal:
14156   case OMPC_destroy:
14157   case OMPC_novariants:
14158   case OMPC_nocontext:
14159   case OMPC_detach:
14160   case OMPC_inclusive:
14161   case OMPC_exclusive:
14162   case OMPC_uses_allocators:
14163   case OMPC_affinity:
14164   default:
14165     llvm_unreachable("Clause is not allowed.");
14166   }
14167   return Res;
14168 }
14169 
14170 static std::string
14171 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14172                         ArrayRef<unsigned> Exclude = llvm::None) {
14173   SmallString<256> Buffer;
14174   llvm::raw_svector_ostream Out(Buffer);
14175   unsigned Skipped = Exclude.size();
14176   auto S = Exclude.begin(), E = Exclude.end();
14177   for (unsigned I = First; I < Last; ++I) {
14178     if (std::find(S, E, I) != E) {
14179       --Skipped;
14180       continue;
14181     }
14182     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14183     if (I + Skipped + 2 == Last)
14184       Out << " or ";
14185     else if (I + Skipped + 1 != Last)
14186       Out << ", ";
14187   }
14188   return std::string(Out.str());
14189 }
14190 
14191 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14192                                           SourceLocation KindKwLoc,
14193                                           SourceLocation StartLoc,
14194                                           SourceLocation LParenLoc,
14195                                           SourceLocation EndLoc) {
14196   if (Kind == OMP_DEFAULT_unknown) {
14197     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14198         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14199                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14200         << getOpenMPClauseName(OMPC_default);
14201     return nullptr;
14202   }
14203 
14204   switch (Kind) {
14205   case OMP_DEFAULT_none:
14206     DSAStack->setDefaultDSANone(KindKwLoc);
14207     break;
14208   case OMP_DEFAULT_shared:
14209     DSAStack->setDefaultDSAShared(KindKwLoc);
14210     break;
14211   case OMP_DEFAULT_firstprivate:
14212     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14213     break;
14214   default:
14215     llvm_unreachable("DSA unexpected in OpenMP default clause");
14216   }
14217 
14218   return new (Context)
14219       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14220 }
14221 
14222 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14223                                            SourceLocation KindKwLoc,
14224                                            SourceLocation StartLoc,
14225                                            SourceLocation LParenLoc,
14226                                            SourceLocation EndLoc) {
14227   if (Kind == OMP_PROC_BIND_unknown) {
14228     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14229         << getListOfPossibleValues(OMPC_proc_bind,
14230                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14231                                    /*Last=*/
14232                                    unsigned(LangOpts.OpenMP > 50
14233                                                 ? OMP_PROC_BIND_primary
14234                                                 : OMP_PROC_BIND_spread) +
14235                                        1)
14236         << getOpenMPClauseName(OMPC_proc_bind);
14237     return nullptr;
14238   }
14239   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14240     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14241         << getListOfPossibleValues(OMPC_proc_bind,
14242                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14243                                    /*Last=*/
14244                                    unsigned(OMP_PROC_BIND_spread) + 1)
14245         << getOpenMPClauseName(OMPC_proc_bind);
14246   return new (Context)
14247       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14248 }
14249 
14250 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14251     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14252     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14253   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14254     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14255         << getListOfPossibleValues(
14256                OMPC_atomic_default_mem_order, /*First=*/0,
14257                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14258         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14259     return nullptr;
14260   }
14261   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14262                                                       LParenLoc, EndLoc);
14263 }
14264 
14265 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14266                                         SourceLocation KindKwLoc,
14267                                         SourceLocation StartLoc,
14268                                         SourceLocation LParenLoc,
14269                                         SourceLocation EndLoc) {
14270   if (Kind == OMPC_ORDER_unknown) {
14271     static_assert(OMPC_ORDER_unknown > 0,
14272                   "OMPC_ORDER_unknown not greater than 0");
14273     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14274         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14275                                    /*Last=*/OMPC_ORDER_unknown)
14276         << getOpenMPClauseName(OMPC_order);
14277     return nullptr;
14278   }
14279   return new (Context)
14280       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14281 }
14282 
14283 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14284                                          SourceLocation KindKwLoc,
14285                                          SourceLocation StartLoc,
14286                                          SourceLocation LParenLoc,
14287                                          SourceLocation EndLoc) {
14288   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14289       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14290     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14291                          OMPC_DEPEND_depobj};
14292     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14293         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14294                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14295         << getOpenMPClauseName(OMPC_update);
14296     return nullptr;
14297   }
14298   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14299                                  EndLoc);
14300 }
14301 
14302 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14303                                         SourceLocation StartLoc,
14304                                         SourceLocation LParenLoc,
14305                                         SourceLocation EndLoc) {
14306   for (Expr *SizeExpr : SizeExprs) {
14307     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14308         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14309     if (!NumForLoopsResult.isUsable())
14310       return nullptr;
14311   }
14312 
14313   DSAStack->setAssociatedLoops(SizeExprs.size());
14314   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14315                                 SizeExprs);
14316 }
14317 
14318 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14319     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14320     SourceLocation StartLoc, SourceLocation LParenLoc,
14321     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
14322     SourceLocation EndLoc) {
14323   OMPClause *Res = nullptr;
14324   switch (Kind) {
14325   case OMPC_schedule:
14326     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
14327     assert(Argument.size() == NumberOfElements &&
14328            ArgumentLoc.size() == NumberOfElements);
14329     Res = ActOnOpenMPScheduleClause(
14330         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
14331         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
14332         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
14333         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
14334         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
14335     break;
14336   case OMPC_if:
14337     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14338     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
14339                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
14340                               DelimLoc, EndLoc);
14341     break;
14342   case OMPC_dist_schedule:
14343     Res = ActOnOpenMPDistScheduleClause(
14344         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
14345         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
14346     break;
14347   case OMPC_defaultmap:
14348     enum { Modifier, DefaultmapKind };
14349     Res = ActOnOpenMPDefaultmapClause(
14350         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
14351         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
14352         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
14353         EndLoc);
14354     break;
14355   case OMPC_device:
14356     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14357     Res = ActOnOpenMPDeviceClause(
14358         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
14359         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
14360     break;
14361   case OMPC_final:
14362   case OMPC_num_threads:
14363   case OMPC_safelen:
14364   case OMPC_simdlen:
14365   case OMPC_sizes:
14366   case OMPC_allocator:
14367   case OMPC_collapse:
14368   case OMPC_default:
14369   case OMPC_proc_bind:
14370   case OMPC_private:
14371   case OMPC_firstprivate:
14372   case OMPC_lastprivate:
14373   case OMPC_shared:
14374   case OMPC_reduction:
14375   case OMPC_task_reduction:
14376   case OMPC_in_reduction:
14377   case OMPC_linear:
14378   case OMPC_aligned:
14379   case OMPC_copyin:
14380   case OMPC_copyprivate:
14381   case OMPC_ordered:
14382   case OMPC_nowait:
14383   case OMPC_untied:
14384   case OMPC_mergeable:
14385   case OMPC_threadprivate:
14386   case OMPC_allocate:
14387   case OMPC_flush:
14388   case OMPC_depobj:
14389   case OMPC_read:
14390   case OMPC_write:
14391   case OMPC_update:
14392   case OMPC_capture:
14393   case OMPC_seq_cst:
14394   case OMPC_acq_rel:
14395   case OMPC_acquire:
14396   case OMPC_release:
14397   case OMPC_relaxed:
14398   case OMPC_depend:
14399   case OMPC_threads:
14400   case OMPC_simd:
14401   case OMPC_map:
14402   case OMPC_num_teams:
14403   case OMPC_thread_limit:
14404   case OMPC_priority:
14405   case OMPC_grainsize:
14406   case OMPC_nogroup:
14407   case OMPC_num_tasks:
14408   case OMPC_hint:
14409   case OMPC_unknown:
14410   case OMPC_uniform:
14411   case OMPC_to:
14412   case OMPC_from:
14413   case OMPC_use_device_ptr:
14414   case OMPC_use_device_addr:
14415   case OMPC_is_device_ptr:
14416   case OMPC_unified_address:
14417   case OMPC_unified_shared_memory:
14418   case OMPC_reverse_offload:
14419   case OMPC_dynamic_allocators:
14420   case OMPC_atomic_default_mem_order:
14421   case OMPC_device_type:
14422   case OMPC_match:
14423   case OMPC_nontemporal:
14424   case OMPC_order:
14425   case OMPC_destroy:
14426   case OMPC_novariants:
14427   case OMPC_nocontext:
14428   case OMPC_detach:
14429   case OMPC_inclusive:
14430   case OMPC_exclusive:
14431   case OMPC_uses_allocators:
14432   case OMPC_affinity:
14433   default:
14434     llvm_unreachable("Clause is not allowed.");
14435   }
14436   return Res;
14437 }
14438 
14439 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
14440                                    OpenMPScheduleClauseModifier M2,
14441                                    SourceLocation M1Loc, SourceLocation M2Loc) {
14442   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
14443     SmallVector<unsigned, 2> Excluded;
14444     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
14445       Excluded.push_back(M2);
14446     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
14447       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
14448     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
14449       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
14450     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
14451         << getListOfPossibleValues(OMPC_schedule,
14452                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
14453                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14454                                    Excluded)
14455         << getOpenMPClauseName(OMPC_schedule);
14456     return true;
14457   }
14458   return false;
14459 }
14460 
14461 OMPClause *Sema::ActOnOpenMPScheduleClause(
14462     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
14463     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14464     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
14465     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
14466   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
14467       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
14468     return nullptr;
14469   // OpenMP, 2.7.1, Loop Construct, Restrictions
14470   // Either the monotonic modifier or the nonmonotonic modifier can be specified
14471   // but not both.
14472   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
14473       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
14474        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
14475       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
14476        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
14477     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
14478         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
14479         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
14480     return nullptr;
14481   }
14482   if (Kind == OMPC_SCHEDULE_unknown) {
14483     std::string Values;
14484     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
14485       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
14486       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14487                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14488                                        Exclude);
14489     } else {
14490       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14491                                        /*Last=*/OMPC_SCHEDULE_unknown);
14492     }
14493     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14494         << Values << getOpenMPClauseName(OMPC_schedule);
14495     return nullptr;
14496   }
14497   // OpenMP, 2.7.1, Loop Construct, Restrictions
14498   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
14499   // schedule(guided).
14500   // OpenMP 5.0 does not have this restriction.
14501   if (LangOpts.OpenMP < 50 &&
14502       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
14503        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
14504       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
14505     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
14506          diag::err_omp_schedule_nonmonotonic_static);
14507     return nullptr;
14508   }
14509   Expr *ValExpr = ChunkSize;
14510   Stmt *HelperValStmt = nullptr;
14511   if (ChunkSize) {
14512     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14513         !ChunkSize->isInstantiationDependent() &&
14514         !ChunkSize->containsUnexpandedParameterPack()) {
14515       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14516       ExprResult Val =
14517           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14518       if (Val.isInvalid())
14519         return nullptr;
14520 
14521       ValExpr = Val.get();
14522 
14523       // OpenMP [2.7.1, Restrictions]
14524       //  chunk_size must be a loop invariant integer expression with a positive
14525       //  value.
14526       if (Optional<llvm::APSInt> Result =
14527               ValExpr->getIntegerConstantExpr(Context)) {
14528         if (Result->isSigned() && !Result->isStrictlyPositive()) {
14529           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14530               << "schedule" << 1 << ChunkSize->getSourceRange();
14531           return nullptr;
14532         }
14533       } else if (getOpenMPCaptureRegionForClause(
14534                      DSAStack->getCurrentDirective(), OMPC_schedule,
14535                      LangOpts.OpenMP) != OMPD_unknown &&
14536                  !CurContext->isDependentContext()) {
14537         ValExpr = MakeFullExpr(ValExpr).get();
14538         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14539         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14540         HelperValStmt = buildPreInits(Context, Captures);
14541       }
14542     }
14543   }
14544 
14545   return new (Context)
14546       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
14547                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
14548 }
14549 
14550 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
14551                                    SourceLocation StartLoc,
14552                                    SourceLocation EndLoc) {
14553   OMPClause *Res = nullptr;
14554   switch (Kind) {
14555   case OMPC_ordered:
14556     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
14557     break;
14558   case OMPC_nowait:
14559     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
14560     break;
14561   case OMPC_untied:
14562     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
14563     break;
14564   case OMPC_mergeable:
14565     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
14566     break;
14567   case OMPC_read:
14568     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
14569     break;
14570   case OMPC_write:
14571     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
14572     break;
14573   case OMPC_update:
14574     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
14575     break;
14576   case OMPC_capture:
14577     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
14578     break;
14579   case OMPC_seq_cst:
14580     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
14581     break;
14582   case OMPC_acq_rel:
14583     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
14584     break;
14585   case OMPC_acquire:
14586     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
14587     break;
14588   case OMPC_release:
14589     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
14590     break;
14591   case OMPC_relaxed:
14592     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
14593     break;
14594   case OMPC_threads:
14595     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
14596     break;
14597   case OMPC_simd:
14598     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
14599     break;
14600   case OMPC_nogroup:
14601     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
14602     break;
14603   case OMPC_unified_address:
14604     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
14605     break;
14606   case OMPC_unified_shared_memory:
14607     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14608     break;
14609   case OMPC_reverse_offload:
14610     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
14611     break;
14612   case OMPC_dynamic_allocators:
14613     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
14614     break;
14615   case OMPC_destroy:
14616     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
14617                                    /*LParenLoc=*/SourceLocation(),
14618                                    /*VarLoc=*/SourceLocation(), EndLoc);
14619     break;
14620   case OMPC_if:
14621   case OMPC_final:
14622   case OMPC_num_threads:
14623   case OMPC_safelen:
14624   case OMPC_simdlen:
14625   case OMPC_sizes:
14626   case OMPC_allocator:
14627   case OMPC_collapse:
14628   case OMPC_schedule:
14629   case OMPC_private:
14630   case OMPC_firstprivate:
14631   case OMPC_lastprivate:
14632   case OMPC_shared:
14633   case OMPC_reduction:
14634   case OMPC_task_reduction:
14635   case OMPC_in_reduction:
14636   case OMPC_linear:
14637   case OMPC_aligned:
14638   case OMPC_copyin:
14639   case OMPC_copyprivate:
14640   case OMPC_default:
14641   case OMPC_proc_bind:
14642   case OMPC_threadprivate:
14643   case OMPC_allocate:
14644   case OMPC_flush:
14645   case OMPC_depobj:
14646   case OMPC_depend:
14647   case OMPC_device:
14648   case OMPC_map:
14649   case OMPC_num_teams:
14650   case OMPC_thread_limit:
14651   case OMPC_priority:
14652   case OMPC_grainsize:
14653   case OMPC_num_tasks:
14654   case OMPC_hint:
14655   case OMPC_dist_schedule:
14656   case OMPC_defaultmap:
14657   case OMPC_unknown:
14658   case OMPC_uniform:
14659   case OMPC_to:
14660   case OMPC_from:
14661   case OMPC_use_device_ptr:
14662   case OMPC_use_device_addr:
14663   case OMPC_is_device_ptr:
14664   case OMPC_atomic_default_mem_order:
14665   case OMPC_device_type:
14666   case OMPC_match:
14667   case OMPC_nontemporal:
14668   case OMPC_order:
14669   case OMPC_novariants:
14670   case OMPC_nocontext:
14671   case OMPC_detach:
14672   case OMPC_inclusive:
14673   case OMPC_exclusive:
14674   case OMPC_uses_allocators:
14675   case OMPC_affinity:
14676   default:
14677     llvm_unreachable("Clause is not allowed.");
14678   }
14679   return Res;
14680 }
14681 
14682 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
14683                                          SourceLocation EndLoc) {
14684   DSAStack->setNowaitRegion();
14685   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
14686 }
14687 
14688 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
14689                                          SourceLocation EndLoc) {
14690   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
14691 }
14692 
14693 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
14694                                             SourceLocation EndLoc) {
14695   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
14696 }
14697 
14698 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
14699                                        SourceLocation EndLoc) {
14700   return new (Context) OMPReadClause(StartLoc, EndLoc);
14701 }
14702 
14703 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
14704                                         SourceLocation EndLoc) {
14705   return new (Context) OMPWriteClause(StartLoc, EndLoc);
14706 }
14707 
14708 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
14709                                          SourceLocation EndLoc) {
14710   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
14711 }
14712 
14713 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
14714                                           SourceLocation EndLoc) {
14715   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
14716 }
14717 
14718 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
14719                                          SourceLocation EndLoc) {
14720   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
14721 }
14722 
14723 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
14724                                          SourceLocation EndLoc) {
14725   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
14726 }
14727 
14728 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
14729                                           SourceLocation EndLoc) {
14730   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
14731 }
14732 
14733 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
14734                                           SourceLocation EndLoc) {
14735   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
14736 }
14737 
14738 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
14739                                           SourceLocation EndLoc) {
14740   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
14741 }
14742 
14743 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
14744                                           SourceLocation EndLoc) {
14745   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
14746 }
14747 
14748 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
14749                                        SourceLocation EndLoc) {
14750   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
14751 }
14752 
14753 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
14754                                           SourceLocation EndLoc) {
14755   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
14756 }
14757 
14758 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
14759                                                  SourceLocation EndLoc) {
14760   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
14761 }
14762 
14763 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
14764                                                       SourceLocation EndLoc) {
14765   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14766 }
14767 
14768 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
14769                                                  SourceLocation EndLoc) {
14770   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
14771 }
14772 
14773 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
14774                                                     SourceLocation EndLoc) {
14775   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
14776 }
14777 
14778 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
14779                                              SourceLocation StartLoc,
14780                                              SourceLocation EndLoc) {
14781 
14782   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14783   // At least one action-clause must appear on a directive.
14784   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
14785     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
14786     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
14787         << Expected << getOpenMPDirectiveName(OMPD_interop);
14788     return StmtError();
14789   }
14790 
14791   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14792   // A depend clause can only appear on the directive if a targetsync
14793   // interop-type is present or the interop-var was initialized with
14794   // the targetsync interop-type.
14795 
14796   // If there is any 'init' clause diagnose if there is no 'init' clause with
14797   // interop-type of 'targetsync'. Cases involving other directives cannot be
14798   // diagnosed.
14799   const OMPDependClause *DependClause = nullptr;
14800   bool HasInitClause = false;
14801   bool IsTargetSync = false;
14802   for (const OMPClause *C : Clauses) {
14803     if (IsTargetSync)
14804       break;
14805     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
14806       HasInitClause = true;
14807       if (InitClause->getIsTargetSync())
14808         IsTargetSync = true;
14809     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
14810       DependClause = DC;
14811     }
14812   }
14813   if (DependClause && HasInitClause && !IsTargetSync) {
14814     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
14815     return StmtError();
14816   }
14817 
14818   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14819   // Each interop-var may be specified for at most one action-clause of each
14820   // interop construct.
14821   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
14822   for (const OMPClause *C : Clauses) {
14823     OpenMPClauseKind ClauseKind = C->getClauseKind();
14824     const DeclRefExpr *DRE = nullptr;
14825     SourceLocation VarLoc;
14826 
14827     if (ClauseKind == OMPC_init) {
14828       const auto *IC = cast<OMPInitClause>(C);
14829       VarLoc = IC->getVarLoc();
14830       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
14831     } else if (ClauseKind == OMPC_use) {
14832       const auto *UC = cast<OMPUseClause>(C);
14833       VarLoc = UC->getVarLoc();
14834       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
14835     } else if (ClauseKind == OMPC_destroy) {
14836       const auto *DC = cast<OMPDestroyClause>(C);
14837       VarLoc = DC->getVarLoc();
14838       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
14839     }
14840 
14841     if (!DRE)
14842       continue;
14843 
14844     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
14845       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
14846         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
14847         return StmtError();
14848       }
14849     }
14850   }
14851 
14852   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
14853 }
14854 
14855 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
14856                                    SourceLocation VarLoc,
14857                                    OpenMPClauseKind Kind) {
14858   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
14859       InteropVarExpr->isInstantiationDependent() ||
14860       InteropVarExpr->containsUnexpandedParameterPack())
14861     return true;
14862 
14863   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
14864   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
14865     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
14866     return false;
14867   }
14868 
14869   // Interop variable should be of type omp_interop_t.
14870   bool HasError = false;
14871   QualType InteropType;
14872   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
14873                       VarLoc, Sema::LookupOrdinaryName);
14874   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
14875     NamedDecl *ND = Result.getFoundDecl();
14876     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
14877       InteropType = QualType(TD->getTypeForDecl(), 0);
14878     } else {
14879       HasError = true;
14880     }
14881   } else {
14882     HasError = true;
14883   }
14884 
14885   if (HasError) {
14886     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
14887         << "omp_interop_t";
14888     return false;
14889   }
14890 
14891   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
14892   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
14893     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
14894     return false;
14895   }
14896 
14897   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14898   // The interop-var passed to init or destroy must be non-const.
14899   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
14900       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
14901     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
14902         << /*non-const*/ 1;
14903     return false;
14904   }
14905   return true;
14906 }
14907 
14908 OMPClause *
14909 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
14910                             bool IsTarget, bool IsTargetSync,
14911                             SourceLocation StartLoc, SourceLocation LParenLoc,
14912                             SourceLocation VarLoc, SourceLocation EndLoc) {
14913 
14914   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
14915     return nullptr;
14916 
14917   // Check prefer_type values.  These foreign-runtime-id values are either
14918   // string literals or constant integral expressions.
14919   for (const Expr *E : PrefExprs) {
14920     if (E->isValueDependent() || E->isTypeDependent() ||
14921         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14922       continue;
14923     if (E->isIntegerConstantExpr(Context))
14924       continue;
14925     if (isa<StringLiteral>(E))
14926       continue;
14927     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
14928     return nullptr;
14929   }
14930 
14931   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
14932                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
14933                                EndLoc);
14934 }
14935 
14936 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
14937                                       SourceLocation LParenLoc,
14938                                       SourceLocation VarLoc,
14939                                       SourceLocation EndLoc) {
14940 
14941   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
14942     return nullptr;
14943 
14944   return new (Context)
14945       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
14946 }
14947 
14948 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
14949                                           SourceLocation StartLoc,
14950                                           SourceLocation LParenLoc,
14951                                           SourceLocation VarLoc,
14952                                           SourceLocation EndLoc) {
14953   if (InteropVar &&
14954       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
14955     return nullptr;
14956 
14957   return new (Context)
14958       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
14959 }
14960 
14961 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
14962                                              SourceLocation StartLoc,
14963                                              SourceLocation LParenLoc,
14964                                              SourceLocation EndLoc) {
14965   Expr *ValExpr = Condition;
14966   Stmt *HelperValStmt = nullptr;
14967   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14968   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14969       !Condition->isInstantiationDependent() &&
14970       !Condition->containsUnexpandedParameterPack()) {
14971     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14972     if (Val.isInvalid())
14973       return nullptr;
14974 
14975     ValExpr = MakeFullExpr(Val.get()).get();
14976 
14977     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14978     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
14979                                                     LangOpts.OpenMP);
14980     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14981       ValExpr = MakeFullExpr(ValExpr).get();
14982       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14983       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14984       HelperValStmt = buildPreInits(Context, Captures);
14985     }
14986   }
14987 
14988   return new (Context) OMPNovariantsClause(
14989       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14990 }
14991 
14992 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
14993                                             SourceLocation StartLoc,
14994                                             SourceLocation LParenLoc,
14995                                             SourceLocation EndLoc) {
14996   Expr *ValExpr = Condition;
14997   Stmt *HelperValStmt = nullptr;
14998   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14999   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15000       !Condition->isInstantiationDependent() &&
15001       !Condition->containsUnexpandedParameterPack()) {
15002     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15003     if (Val.isInvalid())
15004       return nullptr;
15005 
15006     ValExpr = MakeFullExpr(Val.get()).get();
15007 
15008     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15009     CaptureRegion =
15010         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
15011     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15012       ValExpr = MakeFullExpr(ValExpr).get();
15013       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15014       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15015       HelperValStmt = buildPreInits(Context, Captures);
15016     }
15017   }
15018 
15019   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
15020                                           StartLoc, LParenLoc, EndLoc);
15021 }
15022 
15023 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
15024                                          SourceLocation StartLoc,
15025                                          SourceLocation LParenLoc,
15026                                          SourceLocation EndLoc) {
15027   Expr *ValExpr = ThreadID;
15028   Stmt *HelperValStmt = nullptr;
15029 
15030   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15031   OpenMPDirectiveKind CaptureRegion =
15032       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
15033   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15034     ValExpr = MakeFullExpr(ValExpr).get();
15035     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15036     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15037     HelperValStmt = buildPreInits(Context, Captures);
15038   }
15039 
15040   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
15041                                        StartLoc, LParenLoc, EndLoc);
15042 }
15043 
15044 OMPClause *Sema::ActOnOpenMPVarListClause(
15045     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
15046     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
15047     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
15048     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
15049     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15050     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
15051     SourceLocation ExtraModifierLoc,
15052     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
15053     ArrayRef<SourceLocation> MotionModifiersLoc) {
15054   SourceLocation StartLoc = Locs.StartLoc;
15055   SourceLocation LParenLoc = Locs.LParenLoc;
15056   SourceLocation EndLoc = Locs.EndLoc;
15057   OMPClause *Res = nullptr;
15058   switch (Kind) {
15059   case OMPC_private:
15060     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15061     break;
15062   case OMPC_firstprivate:
15063     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15064     break;
15065   case OMPC_lastprivate:
15066     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
15067            "Unexpected lastprivate modifier.");
15068     Res = ActOnOpenMPLastprivateClause(
15069         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
15070         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
15071     break;
15072   case OMPC_shared:
15073     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
15074     break;
15075   case OMPC_reduction:
15076     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
15077            "Unexpected lastprivate modifier.");
15078     Res = ActOnOpenMPReductionClause(
15079         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
15080         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
15081         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
15082     break;
15083   case OMPC_task_reduction:
15084     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15085                                          EndLoc, ReductionOrMapperIdScopeSpec,
15086                                          ReductionOrMapperId);
15087     break;
15088   case OMPC_in_reduction:
15089     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15090                                        EndLoc, ReductionOrMapperIdScopeSpec,
15091                                        ReductionOrMapperId);
15092     break;
15093   case OMPC_linear:
15094     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
15095            "Unexpected linear modifier.");
15096     Res = ActOnOpenMPLinearClause(
15097         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15098         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15099         ColonLoc, EndLoc);
15100     break;
15101   case OMPC_aligned:
15102     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15103                                    LParenLoc, ColonLoc, EndLoc);
15104     break;
15105   case OMPC_copyin:
15106     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15107     break;
15108   case OMPC_copyprivate:
15109     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15110     break;
15111   case OMPC_flush:
15112     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15113     break;
15114   case OMPC_depend:
15115     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15116            "Unexpected depend modifier.");
15117     Res = ActOnOpenMPDependClause(
15118         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15119         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15120     break;
15121   case OMPC_map:
15122     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15123            "Unexpected map modifier.");
15124     Res = ActOnOpenMPMapClause(
15125         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15126         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15127         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15128     break;
15129   case OMPC_to:
15130     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15131                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15132                               ColonLoc, VarList, Locs);
15133     break;
15134   case OMPC_from:
15135     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15136                                 ReductionOrMapperIdScopeSpec,
15137                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15138     break;
15139   case OMPC_use_device_ptr:
15140     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15141     break;
15142   case OMPC_use_device_addr:
15143     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15144     break;
15145   case OMPC_is_device_ptr:
15146     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15147     break;
15148   case OMPC_allocate:
15149     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15150                                     LParenLoc, ColonLoc, EndLoc);
15151     break;
15152   case OMPC_nontemporal:
15153     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15154     break;
15155   case OMPC_inclusive:
15156     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15157     break;
15158   case OMPC_exclusive:
15159     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15160     break;
15161   case OMPC_affinity:
15162     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15163                                     DepModOrTailExpr, VarList);
15164     break;
15165   case OMPC_if:
15166   case OMPC_depobj:
15167   case OMPC_final:
15168   case OMPC_num_threads:
15169   case OMPC_safelen:
15170   case OMPC_simdlen:
15171   case OMPC_sizes:
15172   case OMPC_allocator:
15173   case OMPC_collapse:
15174   case OMPC_default:
15175   case OMPC_proc_bind:
15176   case OMPC_schedule:
15177   case OMPC_ordered:
15178   case OMPC_nowait:
15179   case OMPC_untied:
15180   case OMPC_mergeable:
15181   case OMPC_threadprivate:
15182   case OMPC_read:
15183   case OMPC_write:
15184   case OMPC_update:
15185   case OMPC_capture:
15186   case OMPC_seq_cst:
15187   case OMPC_acq_rel:
15188   case OMPC_acquire:
15189   case OMPC_release:
15190   case OMPC_relaxed:
15191   case OMPC_device:
15192   case OMPC_threads:
15193   case OMPC_simd:
15194   case OMPC_num_teams:
15195   case OMPC_thread_limit:
15196   case OMPC_priority:
15197   case OMPC_grainsize:
15198   case OMPC_nogroup:
15199   case OMPC_num_tasks:
15200   case OMPC_hint:
15201   case OMPC_dist_schedule:
15202   case OMPC_defaultmap:
15203   case OMPC_unknown:
15204   case OMPC_uniform:
15205   case OMPC_unified_address:
15206   case OMPC_unified_shared_memory:
15207   case OMPC_reverse_offload:
15208   case OMPC_dynamic_allocators:
15209   case OMPC_atomic_default_mem_order:
15210   case OMPC_device_type:
15211   case OMPC_match:
15212   case OMPC_order:
15213   case OMPC_destroy:
15214   case OMPC_novariants:
15215   case OMPC_nocontext:
15216   case OMPC_detach:
15217   case OMPC_uses_allocators:
15218   default:
15219     llvm_unreachable("Clause is not allowed.");
15220   }
15221   return Res;
15222 }
15223 
15224 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15225                                        ExprObjectKind OK, SourceLocation Loc) {
15226   ExprResult Res = BuildDeclRefExpr(
15227       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15228   if (!Res.isUsable())
15229     return ExprError();
15230   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15231     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15232     if (!Res.isUsable())
15233       return ExprError();
15234   }
15235   if (VK != VK_LValue && Res.get()->isGLValue()) {
15236     Res = DefaultLvalueConversion(Res.get());
15237     if (!Res.isUsable())
15238       return ExprError();
15239   }
15240   return Res;
15241 }
15242 
15243 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15244                                           SourceLocation StartLoc,
15245                                           SourceLocation LParenLoc,
15246                                           SourceLocation EndLoc) {
15247   SmallVector<Expr *, 8> Vars;
15248   SmallVector<Expr *, 8> PrivateCopies;
15249   for (Expr *RefExpr : VarList) {
15250     assert(RefExpr && "NULL expr in OpenMP private clause.");
15251     SourceLocation ELoc;
15252     SourceRange ERange;
15253     Expr *SimpleRefExpr = RefExpr;
15254     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15255     if (Res.second) {
15256       // It will be analyzed later.
15257       Vars.push_back(RefExpr);
15258       PrivateCopies.push_back(nullptr);
15259     }
15260     ValueDecl *D = Res.first;
15261     if (!D)
15262       continue;
15263 
15264     QualType Type = D->getType();
15265     auto *VD = dyn_cast<VarDecl>(D);
15266 
15267     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15268     //  A variable that appears in a private clause must not have an incomplete
15269     //  type or a reference type.
15270     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15271       continue;
15272     Type = Type.getNonReferenceType();
15273 
15274     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15275     // A variable that is privatized must not have a const-qualified type
15276     // unless it is of class type with a mutable member. This restriction does
15277     // not apply to the firstprivate clause.
15278     //
15279     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15280     // A variable that appears in a private clause must not have a
15281     // const-qualified type unless it is of class type with a mutable member.
15282     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15283       continue;
15284 
15285     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15286     // in a Construct]
15287     //  Variables with the predetermined data-sharing attributes may not be
15288     //  listed in data-sharing attributes clauses, except for the cases
15289     //  listed below. For these exceptions only, listing a predetermined
15290     //  variable in a data-sharing attribute clause is allowed and overrides
15291     //  the variable's predetermined data-sharing attributes.
15292     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15293     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15294       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15295                                           << getOpenMPClauseName(OMPC_private);
15296       reportOriginalDsa(*this, DSAStack, D, DVar);
15297       continue;
15298     }
15299 
15300     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15301     // Variably modified types are not supported for tasks.
15302     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15303         isOpenMPTaskingDirective(CurrDir)) {
15304       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15305           << getOpenMPClauseName(OMPC_private) << Type
15306           << getOpenMPDirectiveName(CurrDir);
15307       bool IsDecl =
15308           !VD ||
15309           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15310       Diag(D->getLocation(),
15311            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15312           << D;
15313       continue;
15314     }
15315 
15316     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15317     // A list item cannot appear in both a map clause and a data-sharing
15318     // attribute clause on the same construct
15319     //
15320     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15321     // A list item cannot appear in both a map clause and a data-sharing
15322     // attribute clause on the same construct unless the construct is a
15323     // combined construct.
15324     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
15325         CurrDir == OMPD_target) {
15326       OpenMPClauseKind ConflictKind;
15327       if (DSAStack->checkMappableExprComponentListsForDecl(
15328               VD, /*CurrentRegionOnly=*/true,
15329               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
15330                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
15331                 ConflictKind = WhereFoundClauseKind;
15332                 return true;
15333               })) {
15334         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15335             << getOpenMPClauseName(OMPC_private)
15336             << getOpenMPClauseName(ConflictKind)
15337             << getOpenMPDirectiveName(CurrDir);
15338         reportOriginalDsa(*this, DSAStack, D, DVar);
15339         continue;
15340       }
15341     }
15342 
15343     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
15344     //  A variable of class type (or array thereof) that appears in a private
15345     //  clause requires an accessible, unambiguous default constructor for the
15346     //  class type.
15347     // Generate helper private variable and initialize it with the default
15348     // value. The address of the original variable is replaced by the address of
15349     // the new private variable in CodeGen. This new variable is not added to
15350     // IdResolver, so the code in the OpenMP region uses original variable for
15351     // proper diagnostics.
15352     Type = Type.getUnqualifiedType();
15353     VarDecl *VDPrivate =
15354         buildVarDecl(*this, ELoc, Type, D->getName(),
15355                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15356                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15357     ActOnUninitializedDecl(VDPrivate);
15358     if (VDPrivate->isInvalidDecl())
15359       continue;
15360     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15361         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15362 
15363     DeclRefExpr *Ref = nullptr;
15364     if (!VD && !CurContext->isDependentContext())
15365       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15366     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
15367     Vars.push_back((VD || CurContext->isDependentContext())
15368                        ? RefExpr->IgnoreParens()
15369                        : Ref);
15370     PrivateCopies.push_back(VDPrivateRefExpr);
15371   }
15372 
15373   if (Vars.empty())
15374     return nullptr;
15375 
15376   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15377                                   PrivateCopies);
15378 }
15379 
15380 namespace {
15381 class DiagsUninitializedSeveretyRAII {
15382 private:
15383   DiagnosticsEngine &Diags;
15384   SourceLocation SavedLoc;
15385   bool IsIgnored = false;
15386 
15387 public:
15388   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
15389                                  bool IsIgnored)
15390       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
15391     if (!IsIgnored) {
15392       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
15393                         /*Map*/ diag::Severity::Ignored, Loc);
15394     }
15395   }
15396   ~DiagsUninitializedSeveretyRAII() {
15397     if (!IsIgnored)
15398       Diags.popMappings(SavedLoc);
15399   }
15400 };
15401 }
15402 
15403 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
15404                                                SourceLocation StartLoc,
15405                                                SourceLocation LParenLoc,
15406                                                SourceLocation EndLoc) {
15407   SmallVector<Expr *, 8> Vars;
15408   SmallVector<Expr *, 8> PrivateCopies;
15409   SmallVector<Expr *, 8> Inits;
15410   SmallVector<Decl *, 4> ExprCaptures;
15411   bool IsImplicitClause =
15412       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
15413   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
15414 
15415   for (Expr *RefExpr : VarList) {
15416     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
15417     SourceLocation ELoc;
15418     SourceRange ERange;
15419     Expr *SimpleRefExpr = RefExpr;
15420     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15421     if (Res.second) {
15422       // It will be analyzed later.
15423       Vars.push_back(RefExpr);
15424       PrivateCopies.push_back(nullptr);
15425       Inits.push_back(nullptr);
15426     }
15427     ValueDecl *D = Res.first;
15428     if (!D)
15429       continue;
15430 
15431     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
15432     QualType Type = D->getType();
15433     auto *VD = dyn_cast<VarDecl>(D);
15434 
15435     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15436     //  A variable that appears in a private clause must not have an incomplete
15437     //  type or a reference type.
15438     if (RequireCompleteType(ELoc, Type,
15439                             diag::err_omp_firstprivate_incomplete_type))
15440       continue;
15441     Type = Type.getNonReferenceType();
15442 
15443     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
15444     //  A variable of class type (or array thereof) that appears in a private
15445     //  clause requires an accessible, unambiguous copy constructor for the
15446     //  class type.
15447     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15448 
15449     // If an implicit firstprivate variable found it was checked already.
15450     DSAStackTy::DSAVarData TopDVar;
15451     if (!IsImplicitClause) {
15452       DSAStackTy::DSAVarData DVar =
15453           DSAStack->getTopDSA(D, /*FromParent=*/false);
15454       TopDVar = DVar;
15455       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15456       bool IsConstant = ElemType.isConstant(Context);
15457       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
15458       //  A list item that specifies a given variable may not appear in more
15459       // than one clause on the same directive, except that a variable may be
15460       //  specified in both firstprivate and lastprivate clauses.
15461       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15462       // A list item may appear in a firstprivate or lastprivate clause but not
15463       // both.
15464       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
15465           (isOpenMPDistributeDirective(CurrDir) ||
15466            DVar.CKind != OMPC_lastprivate) &&
15467           DVar.RefExpr) {
15468         Diag(ELoc, diag::err_omp_wrong_dsa)
15469             << getOpenMPClauseName(DVar.CKind)
15470             << getOpenMPClauseName(OMPC_firstprivate);
15471         reportOriginalDsa(*this, DSAStack, D, DVar);
15472         continue;
15473       }
15474 
15475       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15476       // in a Construct]
15477       //  Variables with the predetermined data-sharing attributes may not be
15478       //  listed in data-sharing attributes clauses, except for the cases
15479       //  listed below. For these exceptions only, listing a predetermined
15480       //  variable in a data-sharing attribute clause is allowed and overrides
15481       //  the variable's predetermined data-sharing attributes.
15482       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15483       // in a Construct, C/C++, p.2]
15484       //  Variables with const-qualified type having no mutable member may be
15485       //  listed in a firstprivate clause, even if they are static data members.
15486       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
15487           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
15488         Diag(ELoc, diag::err_omp_wrong_dsa)
15489             << getOpenMPClauseName(DVar.CKind)
15490             << getOpenMPClauseName(OMPC_firstprivate);
15491         reportOriginalDsa(*this, DSAStack, D, DVar);
15492         continue;
15493       }
15494 
15495       // OpenMP [2.9.3.4, Restrictions, p.2]
15496       //  A list item that is private within a parallel region must not appear
15497       //  in a firstprivate clause on a worksharing construct if any of the
15498       //  worksharing regions arising from the worksharing construct ever bind
15499       //  to any of the parallel regions arising from the parallel construct.
15500       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15501       // A list item that is private within a teams region must not appear in a
15502       // firstprivate clause on a distribute construct if any of the distribute
15503       // regions arising from the distribute construct ever bind to any of the
15504       // teams regions arising from the teams construct.
15505       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15506       // A list item that appears in a reduction clause of a teams construct
15507       // must not appear in a firstprivate clause on a distribute construct if
15508       // any of the distribute regions arising from the distribute construct
15509       // ever bind to any of the teams regions arising from the teams construct.
15510       if ((isOpenMPWorksharingDirective(CurrDir) ||
15511            isOpenMPDistributeDirective(CurrDir)) &&
15512           !isOpenMPParallelDirective(CurrDir) &&
15513           !isOpenMPTeamsDirective(CurrDir)) {
15514         DVar = DSAStack->getImplicitDSA(D, true);
15515         if (DVar.CKind != OMPC_shared &&
15516             (isOpenMPParallelDirective(DVar.DKind) ||
15517              isOpenMPTeamsDirective(DVar.DKind) ||
15518              DVar.DKind == OMPD_unknown)) {
15519           Diag(ELoc, diag::err_omp_required_access)
15520               << getOpenMPClauseName(OMPC_firstprivate)
15521               << getOpenMPClauseName(OMPC_shared);
15522           reportOriginalDsa(*this, DSAStack, D, DVar);
15523           continue;
15524         }
15525       }
15526       // OpenMP [2.9.3.4, Restrictions, p.3]
15527       //  A list item that appears in a reduction clause of a parallel construct
15528       //  must not appear in a firstprivate clause on a worksharing or task
15529       //  construct if any of the worksharing or task regions arising from the
15530       //  worksharing or task construct ever bind to any of the parallel regions
15531       //  arising from the parallel construct.
15532       // OpenMP [2.9.3.4, Restrictions, p.4]
15533       //  A list item that appears in a reduction clause in worksharing
15534       //  construct must not appear in a firstprivate clause in a task construct
15535       //  encountered during execution of any of the worksharing regions arising
15536       //  from the worksharing construct.
15537       if (isOpenMPTaskingDirective(CurrDir)) {
15538         DVar = DSAStack->hasInnermostDSA(
15539             D,
15540             [](OpenMPClauseKind C, bool AppliedToPointee) {
15541               return C == OMPC_reduction && !AppliedToPointee;
15542             },
15543             [](OpenMPDirectiveKind K) {
15544               return isOpenMPParallelDirective(K) ||
15545                      isOpenMPWorksharingDirective(K) ||
15546                      isOpenMPTeamsDirective(K);
15547             },
15548             /*FromParent=*/true);
15549         if (DVar.CKind == OMPC_reduction &&
15550             (isOpenMPParallelDirective(DVar.DKind) ||
15551              isOpenMPWorksharingDirective(DVar.DKind) ||
15552              isOpenMPTeamsDirective(DVar.DKind))) {
15553           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
15554               << getOpenMPDirectiveName(DVar.DKind);
15555           reportOriginalDsa(*this, DSAStack, D, DVar);
15556           continue;
15557         }
15558       }
15559 
15560       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15561       // A list item cannot appear in both a map clause and a data-sharing
15562       // attribute clause on the same construct
15563       //
15564       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15565       // A list item cannot appear in both a map clause and a data-sharing
15566       // attribute clause on the same construct unless the construct is a
15567       // combined construct.
15568       if ((LangOpts.OpenMP <= 45 &&
15569            isOpenMPTargetExecutionDirective(CurrDir)) ||
15570           CurrDir == OMPD_target) {
15571         OpenMPClauseKind ConflictKind;
15572         if (DSAStack->checkMappableExprComponentListsForDecl(
15573                 VD, /*CurrentRegionOnly=*/true,
15574                 [&ConflictKind](
15575                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
15576                     OpenMPClauseKind WhereFoundClauseKind) {
15577                   ConflictKind = WhereFoundClauseKind;
15578                   return true;
15579                 })) {
15580           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15581               << getOpenMPClauseName(OMPC_firstprivate)
15582               << getOpenMPClauseName(ConflictKind)
15583               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15584           reportOriginalDsa(*this, DSAStack, D, DVar);
15585           continue;
15586         }
15587       }
15588     }
15589 
15590     // Variably modified types are not supported for tasks.
15591     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15592         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
15593       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15594           << getOpenMPClauseName(OMPC_firstprivate) << Type
15595           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15596       bool IsDecl =
15597           !VD ||
15598           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15599       Diag(D->getLocation(),
15600            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15601           << D;
15602       continue;
15603     }
15604 
15605     Type = Type.getUnqualifiedType();
15606     VarDecl *VDPrivate =
15607         buildVarDecl(*this, ELoc, Type, D->getName(),
15608                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15609                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15610     // Generate helper private variable and initialize it with the value of the
15611     // original variable. The address of the original variable is replaced by
15612     // the address of the new private variable in the CodeGen. This new variable
15613     // is not added to IdResolver, so the code in the OpenMP region uses
15614     // original variable for proper diagnostics and variable capturing.
15615     Expr *VDInitRefExpr = nullptr;
15616     // For arrays generate initializer for single element and replace it by the
15617     // original array element in CodeGen.
15618     if (Type->isArrayType()) {
15619       VarDecl *VDInit =
15620           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
15621       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
15622       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
15623       ElemType = ElemType.getUnqualifiedType();
15624       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
15625                                          ".firstprivate.temp");
15626       InitializedEntity Entity =
15627           InitializedEntity::InitializeVariable(VDInitTemp);
15628       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
15629 
15630       InitializationSequence InitSeq(*this, Entity, Kind, Init);
15631       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
15632       if (Result.isInvalid())
15633         VDPrivate->setInvalidDecl();
15634       else
15635         VDPrivate->setInit(Result.getAs<Expr>());
15636       // Remove temp variable declaration.
15637       Context.Deallocate(VDInitTemp);
15638     } else {
15639       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
15640                                      ".firstprivate.temp");
15641       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
15642                                        RefExpr->getExprLoc());
15643       AddInitializerToDecl(VDPrivate,
15644                            DefaultLvalueConversion(VDInitRefExpr).get(),
15645                            /*DirectInit=*/false);
15646     }
15647     if (VDPrivate->isInvalidDecl()) {
15648       if (IsImplicitClause) {
15649         Diag(RefExpr->getExprLoc(),
15650              diag::note_omp_task_predetermined_firstprivate_here);
15651       }
15652       continue;
15653     }
15654     CurContext->addDecl(VDPrivate);
15655     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15656         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
15657         RefExpr->getExprLoc());
15658     DeclRefExpr *Ref = nullptr;
15659     if (!VD && !CurContext->isDependentContext()) {
15660       if (TopDVar.CKind == OMPC_lastprivate) {
15661         Ref = TopDVar.PrivateCopy;
15662       } else {
15663         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15664         if (!isOpenMPCapturedDecl(D))
15665           ExprCaptures.push_back(Ref->getDecl());
15666       }
15667     }
15668     if (!IsImplicitClause)
15669       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15670     Vars.push_back((VD || CurContext->isDependentContext())
15671                        ? RefExpr->IgnoreParens()
15672                        : Ref);
15673     PrivateCopies.push_back(VDPrivateRefExpr);
15674     Inits.push_back(VDInitRefExpr);
15675   }
15676 
15677   if (Vars.empty())
15678     return nullptr;
15679 
15680   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15681                                        Vars, PrivateCopies, Inits,
15682                                        buildPreInits(Context, ExprCaptures));
15683 }
15684 
15685 OMPClause *Sema::ActOnOpenMPLastprivateClause(
15686     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
15687     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
15688     SourceLocation LParenLoc, SourceLocation EndLoc) {
15689   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
15690     assert(ColonLoc.isValid() && "Colon location must be valid.");
15691     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
15692         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
15693                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
15694         << getOpenMPClauseName(OMPC_lastprivate);
15695     return nullptr;
15696   }
15697 
15698   SmallVector<Expr *, 8> Vars;
15699   SmallVector<Expr *, 8> SrcExprs;
15700   SmallVector<Expr *, 8> DstExprs;
15701   SmallVector<Expr *, 8> AssignmentOps;
15702   SmallVector<Decl *, 4> ExprCaptures;
15703   SmallVector<Expr *, 4> ExprPostUpdates;
15704   for (Expr *RefExpr : VarList) {
15705     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
15706     SourceLocation ELoc;
15707     SourceRange ERange;
15708     Expr *SimpleRefExpr = RefExpr;
15709     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15710     if (Res.second) {
15711       // It will be analyzed later.
15712       Vars.push_back(RefExpr);
15713       SrcExprs.push_back(nullptr);
15714       DstExprs.push_back(nullptr);
15715       AssignmentOps.push_back(nullptr);
15716     }
15717     ValueDecl *D = Res.first;
15718     if (!D)
15719       continue;
15720 
15721     QualType Type = D->getType();
15722     auto *VD = dyn_cast<VarDecl>(D);
15723 
15724     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
15725     //  A variable that appears in a lastprivate clause must not have an
15726     //  incomplete type or a reference type.
15727     if (RequireCompleteType(ELoc, Type,
15728                             diag::err_omp_lastprivate_incomplete_type))
15729       continue;
15730     Type = Type.getNonReferenceType();
15731 
15732     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15733     // A variable that is privatized must not have a const-qualified type
15734     // unless it is of class type with a mutable member. This restriction does
15735     // not apply to the firstprivate clause.
15736     //
15737     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
15738     // A variable that appears in a lastprivate clause must not have a
15739     // const-qualified type unless it is of class type with a mutable member.
15740     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
15741       continue;
15742 
15743     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
15744     // A list item that appears in a lastprivate clause with the conditional
15745     // modifier must be a scalar variable.
15746     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
15747       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
15748       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15749                                VarDecl::DeclarationOnly;
15750       Diag(D->getLocation(),
15751            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15752           << D;
15753       continue;
15754     }
15755 
15756     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15757     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
15758     // in a Construct]
15759     //  Variables with the predetermined data-sharing attributes may not be
15760     //  listed in data-sharing attributes clauses, except for the cases
15761     //  listed below.
15762     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15763     // A list item may appear in a firstprivate or lastprivate clause but not
15764     // both.
15765     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15766     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
15767         (isOpenMPDistributeDirective(CurrDir) ||
15768          DVar.CKind != OMPC_firstprivate) &&
15769         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
15770       Diag(ELoc, diag::err_omp_wrong_dsa)
15771           << getOpenMPClauseName(DVar.CKind)
15772           << getOpenMPClauseName(OMPC_lastprivate);
15773       reportOriginalDsa(*this, DSAStack, D, DVar);
15774       continue;
15775     }
15776 
15777     // OpenMP [2.14.3.5, Restrictions, p.2]
15778     // A list item that is private within a parallel region, or that appears in
15779     // the reduction clause of a parallel construct, must not appear in a
15780     // lastprivate clause on a worksharing construct if any of the corresponding
15781     // worksharing regions ever binds to any of the corresponding parallel
15782     // regions.
15783     DSAStackTy::DSAVarData TopDVar = DVar;
15784     if (isOpenMPWorksharingDirective(CurrDir) &&
15785         !isOpenMPParallelDirective(CurrDir) &&
15786         !isOpenMPTeamsDirective(CurrDir)) {
15787       DVar = DSAStack->getImplicitDSA(D, true);
15788       if (DVar.CKind != OMPC_shared) {
15789         Diag(ELoc, diag::err_omp_required_access)
15790             << getOpenMPClauseName(OMPC_lastprivate)
15791             << getOpenMPClauseName(OMPC_shared);
15792         reportOriginalDsa(*this, DSAStack, D, DVar);
15793         continue;
15794       }
15795     }
15796 
15797     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
15798     //  A variable of class type (or array thereof) that appears in a
15799     //  lastprivate clause requires an accessible, unambiguous default
15800     //  constructor for the class type, unless the list item is also specified
15801     //  in a firstprivate clause.
15802     //  A variable of class type (or array thereof) that appears in a
15803     //  lastprivate clause requires an accessible, unambiguous copy assignment
15804     //  operator for the class type.
15805     Type = Context.getBaseElementType(Type).getNonReferenceType();
15806     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
15807                                   Type.getUnqualifiedType(), ".lastprivate.src",
15808                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15809     DeclRefExpr *PseudoSrcExpr =
15810         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
15811     VarDecl *DstVD =
15812         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
15813                      D->hasAttrs() ? &D->getAttrs() : nullptr);
15814     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
15815     // For arrays generate assignment operation for single element and replace
15816     // it by the original array element in CodeGen.
15817     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
15818                                          PseudoDstExpr, PseudoSrcExpr);
15819     if (AssignmentOp.isInvalid())
15820       continue;
15821     AssignmentOp =
15822         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
15823     if (AssignmentOp.isInvalid())
15824       continue;
15825 
15826     DeclRefExpr *Ref = nullptr;
15827     if (!VD && !CurContext->isDependentContext()) {
15828       if (TopDVar.CKind == OMPC_firstprivate) {
15829         Ref = TopDVar.PrivateCopy;
15830       } else {
15831         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15832         if (!isOpenMPCapturedDecl(D))
15833           ExprCaptures.push_back(Ref->getDecl());
15834       }
15835       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
15836           (!isOpenMPCapturedDecl(D) &&
15837            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
15838         ExprResult RefRes = DefaultLvalueConversion(Ref);
15839         if (!RefRes.isUsable())
15840           continue;
15841         ExprResult PostUpdateRes =
15842             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15843                        RefRes.get());
15844         if (!PostUpdateRes.isUsable())
15845           continue;
15846         ExprPostUpdates.push_back(
15847             IgnoredValueConversions(PostUpdateRes.get()).get());
15848       }
15849     }
15850     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
15851     Vars.push_back((VD || CurContext->isDependentContext())
15852                        ? RefExpr->IgnoreParens()
15853                        : Ref);
15854     SrcExprs.push_back(PseudoSrcExpr);
15855     DstExprs.push_back(PseudoDstExpr);
15856     AssignmentOps.push_back(AssignmentOp.get());
15857   }
15858 
15859   if (Vars.empty())
15860     return nullptr;
15861 
15862   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15863                                       Vars, SrcExprs, DstExprs, AssignmentOps,
15864                                       LPKind, LPKindLoc, ColonLoc,
15865                                       buildPreInits(Context, ExprCaptures),
15866                                       buildPostUpdate(*this, ExprPostUpdates));
15867 }
15868 
15869 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
15870                                          SourceLocation StartLoc,
15871                                          SourceLocation LParenLoc,
15872                                          SourceLocation EndLoc) {
15873   SmallVector<Expr *, 8> Vars;
15874   for (Expr *RefExpr : VarList) {
15875     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
15876     SourceLocation ELoc;
15877     SourceRange ERange;
15878     Expr *SimpleRefExpr = RefExpr;
15879     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15880     if (Res.second) {
15881       // It will be analyzed later.
15882       Vars.push_back(RefExpr);
15883     }
15884     ValueDecl *D = Res.first;
15885     if (!D)
15886       continue;
15887 
15888     auto *VD = dyn_cast<VarDecl>(D);
15889     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15890     // in a Construct]
15891     //  Variables with the predetermined data-sharing attributes may not be
15892     //  listed in data-sharing attributes clauses, except for the cases
15893     //  listed below. For these exceptions only, listing a predetermined
15894     //  variable in a data-sharing attribute clause is allowed and overrides
15895     //  the variable's predetermined data-sharing attributes.
15896     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15897     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
15898         DVar.RefExpr) {
15899       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15900                                           << getOpenMPClauseName(OMPC_shared);
15901       reportOriginalDsa(*this, DSAStack, D, DVar);
15902       continue;
15903     }
15904 
15905     DeclRefExpr *Ref = nullptr;
15906     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
15907       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15908     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
15909     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
15910                        ? RefExpr->IgnoreParens()
15911                        : Ref);
15912   }
15913 
15914   if (Vars.empty())
15915     return nullptr;
15916 
15917   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
15918 }
15919 
15920 namespace {
15921 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
15922   DSAStackTy *Stack;
15923 
15924 public:
15925   bool VisitDeclRefExpr(DeclRefExpr *E) {
15926     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
15927       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
15928       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
15929         return false;
15930       if (DVar.CKind != OMPC_unknown)
15931         return true;
15932       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
15933           VD,
15934           [](OpenMPClauseKind C, bool AppliedToPointee) {
15935             return isOpenMPPrivate(C) && !AppliedToPointee;
15936           },
15937           [](OpenMPDirectiveKind) { return true; },
15938           /*FromParent=*/true);
15939       return DVarPrivate.CKind != OMPC_unknown;
15940     }
15941     return false;
15942   }
15943   bool VisitStmt(Stmt *S) {
15944     for (Stmt *Child : S->children()) {
15945       if (Child && Visit(Child))
15946         return true;
15947     }
15948     return false;
15949   }
15950   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
15951 };
15952 } // namespace
15953 
15954 namespace {
15955 // Transform MemberExpression for specified FieldDecl of current class to
15956 // DeclRefExpr to specified OMPCapturedExprDecl.
15957 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
15958   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
15959   ValueDecl *Field = nullptr;
15960   DeclRefExpr *CapturedExpr = nullptr;
15961 
15962 public:
15963   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
15964       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
15965 
15966   ExprResult TransformMemberExpr(MemberExpr *E) {
15967     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
15968         E->getMemberDecl() == Field) {
15969       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
15970       return CapturedExpr;
15971     }
15972     return BaseTransform::TransformMemberExpr(E);
15973   }
15974   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
15975 };
15976 } // namespace
15977 
15978 template <typename T, typename U>
15979 static T filterLookupForUDReductionAndMapper(
15980     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
15981   for (U &Set : Lookups) {
15982     for (auto *D : Set) {
15983       if (T Res = Gen(cast<ValueDecl>(D)))
15984         return Res;
15985     }
15986   }
15987   return T();
15988 }
15989 
15990 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
15991   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
15992 
15993   for (auto RD : D->redecls()) {
15994     // Don't bother with extra checks if we already know this one isn't visible.
15995     if (RD == D)
15996       continue;
15997 
15998     auto ND = cast<NamedDecl>(RD);
15999     if (LookupResult::isVisible(SemaRef, ND))
16000       return ND;
16001   }
16002 
16003   return nullptr;
16004 }
16005 
16006 static void
16007 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
16008                         SourceLocation Loc, QualType Ty,
16009                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
16010   // Find all of the associated namespaces and classes based on the
16011   // arguments we have.
16012   Sema::AssociatedNamespaceSet AssociatedNamespaces;
16013   Sema::AssociatedClassSet AssociatedClasses;
16014   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
16015   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
16016                                              AssociatedClasses);
16017 
16018   // C++ [basic.lookup.argdep]p3:
16019   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
16020   //   and let Y be the lookup set produced by argument dependent
16021   //   lookup (defined as follows). If X contains [...] then Y is
16022   //   empty. Otherwise Y is the set of declarations found in the
16023   //   namespaces associated with the argument types as described
16024   //   below. The set of declarations found by the lookup of the name
16025   //   is the union of X and Y.
16026   //
16027   // Here, we compute Y and add its members to the overloaded
16028   // candidate set.
16029   for (auto *NS : AssociatedNamespaces) {
16030     //   When considering an associated namespace, the lookup is the
16031     //   same as the lookup performed when the associated namespace is
16032     //   used as a qualifier (3.4.3.2) except that:
16033     //
16034     //     -- Any using-directives in the associated namespace are
16035     //        ignored.
16036     //
16037     //     -- Any namespace-scope friend functions declared in
16038     //        associated classes are visible within their respective
16039     //        namespaces even if they are not visible during an ordinary
16040     //        lookup (11.4).
16041     DeclContext::lookup_result R = NS->lookup(Id.getName());
16042     for (auto *D : R) {
16043       auto *Underlying = D;
16044       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16045         Underlying = USD->getTargetDecl();
16046 
16047       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
16048           !isa<OMPDeclareMapperDecl>(Underlying))
16049         continue;
16050 
16051       if (!SemaRef.isVisible(D)) {
16052         D = findAcceptableDecl(SemaRef, D);
16053         if (!D)
16054           continue;
16055         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16056           Underlying = USD->getTargetDecl();
16057       }
16058       Lookups.emplace_back();
16059       Lookups.back().addDecl(Underlying);
16060     }
16061   }
16062 }
16063 
16064 static ExprResult
16065 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
16066                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
16067                          const DeclarationNameInfo &ReductionId, QualType Ty,
16068                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
16069   if (ReductionIdScopeSpec.isInvalid())
16070     return ExprError();
16071   SmallVector<UnresolvedSet<8>, 4> Lookups;
16072   if (S) {
16073     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16074     Lookup.suppressDiagnostics();
16075     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
16076       NamedDecl *D = Lookup.getRepresentativeDecl();
16077       do {
16078         S = S->getParent();
16079       } while (S && !S->isDeclScope(D));
16080       if (S)
16081         S = S->getParent();
16082       Lookups.emplace_back();
16083       Lookups.back().append(Lookup.begin(), Lookup.end());
16084       Lookup.clear();
16085     }
16086   } else if (auto *ULE =
16087                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
16088     Lookups.push_back(UnresolvedSet<8>());
16089     Decl *PrevD = nullptr;
16090     for (NamedDecl *D : ULE->decls()) {
16091       if (D == PrevD)
16092         Lookups.push_back(UnresolvedSet<8>());
16093       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
16094         Lookups.back().addDecl(DRD);
16095       PrevD = D;
16096     }
16097   }
16098   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16099       Ty->isInstantiationDependentType() ||
16100       Ty->containsUnexpandedParameterPack() ||
16101       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16102         return !D->isInvalidDecl() &&
16103                (D->getType()->isDependentType() ||
16104                 D->getType()->isInstantiationDependentType() ||
16105                 D->getType()->containsUnexpandedParameterPack());
16106       })) {
16107     UnresolvedSet<8> ResSet;
16108     for (const UnresolvedSet<8> &Set : Lookups) {
16109       if (Set.empty())
16110         continue;
16111       ResSet.append(Set.begin(), Set.end());
16112       // The last item marks the end of all declarations at the specified scope.
16113       ResSet.addDecl(Set[Set.size() - 1]);
16114     }
16115     return UnresolvedLookupExpr::Create(
16116         SemaRef.Context, /*NamingClass=*/nullptr,
16117         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16118         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16119   }
16120   // Lookup inside the classes.
16121   // C++ [over.match.oper]p3:
16122   //   For a unary operator @ with an operand of a type whose
16123   //   cv-unqualified version is T1, and for a binary operator @ with
16124   //   a left operand of a type whose cv-unqualified version is T1 and
16125   //   a right operand of a type whose cv-unqualified version is T2,
16126   //   three sets of candidate functions, designated member
16127   //   candidates, non-member candidates and built-in candidates, are
16128   //   constructed as follows:
16129   //     -- If T1 is a complete class type or a class currently being
16130   //        defined, the set of member candidates is the result of the
16131   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16132   //        the set of member candidates is empty.
16133   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16134   Lookup.suppressDiagnostics();
16135   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16136     // Complete the type if it can be completed.
16137     // If the type is neither complete nor being defined, bail out now.
16138     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16139         TyRec->getDecl()->getDefinition()) {
16140       Lookup.clear();
16141       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16142       if (Lookup.empty()) {
16143         Lookups.emplace_back();
16144         Lookups.back().append(Lookup.begin(), Lookup.end());
16145       }
16146     }
16147   }
16148   // Perform ADL.
16149   if (SemaRef.getLangOpts().CPlusPlus)
16150     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16151   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16152           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16153             if (!D->isInvalidDecl() &&
16154                 SemaRef.Context.hasSameType(D->getType(), Ty))
16155               return D;
16156             return nullptr;
16157           }))
16158     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16159                                     VK_LValue, Loc);
16160   if (SemaRef.getLangOpts().CPlusPlus) {
16161     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16162             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16163               if (!D->isInvalidDecl() &&
16164                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16165                   !Ty.isMoreQualifiedThan(D->getType()))
16166                 return D;
16167               return nullptr;
16168             })) {
16169       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16170                          /*DetectVirtual=*/false);
16171       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16172         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16173                 VD->getType().getUnqualifiedType()))) {
16174           if (SemaRef.CheckBaseClassAccess(
16175                   Loc, VD->getType(), Ty, Paths.front(),
16176                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16177             SemaRef.BuildBasePathArray(Paths, BasePath);
16178             return SemaRef.BuildDeclRefExpr(
16179                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16180           }
16181         }
16182       }
16183     }
16184   }
16185   if (ReductionIdScopeSpec.isSet()) {
16186     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16187         << Ty << Range;
16188     return ExprError();
16189   }
16190   return ExprEmpty();
16191 }
16192 
16193 namespace {
16194 /// Data for the reduction-based clauses.
16195 struct ReductionData {
16196   /// List of original reduction items.
16197   SmallVector<Expr *, 8> Vars;
16198   /// List of private copies of the reduction items.
16199   SmallVector<Expr *, 8> Privates;
16200   /// LHS expressions for the reduction_op expressions.
16201   SmallVector<Expr *, 8> LHSs;
16202   /// RHS expressions for the reduction_op expressions.
16203   SmallVector<Expr *, 8> RHSs;
16204   /// Reduction operation expression.
16205   SmallVector<Expr *, 8> ReductionOps;
16206   /// inscan copy operation expressions.
16207   SmallVector<Expr *, 8> InscanCopyOps;
16208   /// inscan copy temp array expressions for prefix sums.
16209   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16210   /// inscan copy temp array element expressions for prefix sums.
16211   SmallVector<Expr *, 8> InscanCopyArrayElems;
16212   /// Taskgroup descriptors for the corresponding reduction items in
16213   /// in_reduction clauses.
16214   SmallVector<Expr *, 8> TaskgroupDescriptors;
16215   /// List of captures for clause.
16216   SmallVector<Decl *, 4> ExprCaptures;
16217   /// List of postupdate expressions.
16218   SmallVector<Expr *, 4> ExprPostUpdates;
16219   /// Reduction modifier.
16220   unsigned RedModifier = 0;
16221   ReductionData() = delete;
16222   /// Reserves required memory for the reduction data.
16223   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16224     Vars.reserve(Size);
16225     Privates.reserve(Size);
16226     LHSs.reserve(Size);
16227     RHSs.reserve(Size);
16228     ReductionOps.reserve(Size);
16229     if (RedModifier == OMPC_REDUCTION_inscan) {
16230       InscanCopyOps.reserve(Size);
16231       InscanCopyArrayTemps.reserve(Size);
16232       InscanCopyArrayElems.reserve(Size);
16233     }
16234     TaskgroupDescriptors.reserve(Size);
16235     ExprCaptures.reserve(Size);
16236     ExprPostUpdates.reserve(Size);
16237   }
16238   /// Stores reduction item and reduction operation only (required for dependent
16239   /// reduction item).
16240   void push(Expr *Item, Expr *ReductionOp) {
16241     Vars.emplace_back(Item);
16242     Privates.emplace_back(nullptr);
16243     LHSs.emplace_back(nullptr);
16244     RHSs.emplace_back(nullptr);
16245     ReductionOps.emplace_back(ReductionOp);
16246     TaskgroupDescriptors.emplace_back(nullptr);
16247     if (RedModifier == OMPC_REDUCTION_inscan) {
16248       InscanCopyOps.push_back(nullptr);
16249       InscanCopyArrayTemps.push_back(nullptr);
16250       InscanCopyArrayElems.push_back(nullptr);
16251     }
16252   }
16253   /// Stores reduction data.
16254   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16255             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16256             Expr *CopyArrayElem) {
16257     Vars.emplace_back(Item);
16258     Privates.emplace_back(Private);
16259     LHSs.emplace_back(LHS);
16260     RHSs.emplace_back(RHS);
16261     ReductionOps.emplace_back(ReductionOp);
16262     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16263     if (RedModifier == OMPC_REDUCTION_inscan) {
16264       InscanCopyOps.push_back(CopyOp);
16265       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16266       InscanCopyArrayElems.push_back(CopyArrayElem);
16267     } else {
16268       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16269              CopyArrayElem == nullptr &&
16270              "Copy operation must be used for inscan reductions only.");
16271     }
16272   }
16273 };
16274 } // namespace
16275 
16276 static bool checkOMPArraySectionConstantForReduction(
16277     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16278     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16279   const Expr *Length = OASE->getLength();
16280   if (Length == nullptr) {
16281     // For array sections of the form [1:] or [:], we would need to analyze
16282     // the lower bound...
16283     if (OASE->getColonLocFirst().isValid())
16284       return false;
16285 
16286     // This is an array subscript which has implicit length 1!
16287     SingleElement = true;
16288     ArraySizes.push_back(llvm::APSInt::get(1));
16289   } else {
16290     Expr::EvalResult Result;
16291     if (!Length->EvaluateAsInt(Result, Context))
16292       return false;
16293 
16294     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16295     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16296     ArraySizes.push_back(ConstantLengthValue);
16297   }
16298 
16299   // Get the base of this array section and walk up from there.
16300   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16301 
16302   // We require length = 1 for all array sections except the right-most to
16303   // guarantee that the memory region is contiguous and has no holes in it.
16304   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16305     Length = TempOASE->getLength();
16306     if (Length == nullptr) {
16307       // For array sections of the form [1:] or [:], we would need to analyze
16308       // the lower bound...
16309       if (OASE->getColonLocFirst().isValid())
16310         return false;
16311 
16312       // This is an array subscript which has implicit length 1!
16313       ArraySizes.push_back(llvm::APSInt::get(1));
16314     } else {
16315       Expr::EvalResult Result;
16316       if (!Length->EvaluateAsInt(Result, Context))
16317         return false;
16318 
16319       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16320       if (ConstantLengthValue.getSExtValue() != 1)
16321         return false;
16322 
16323       ArraySizes.push_back(ConstantLengthValue);
16324     }
16325     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16326   }
16327 
16328   // If we have a single element, we don't need to add the implicit lengths.
16329   if (!SingleElement) {
16330     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16331       // Has implicit length 1!
16332       ArraySizes.push_back(llvm::APSInt::get(1));
16333       Base = TempASE->getBase()->IgnoreParenImpCasts();
16334     }
16335   }
16336 
16337   // This array section can be privatized as a single value or as a constant
16338   // sized array.
16339   return true;
16340 }
16341 
16342 static BinaryOperatorKind
16343 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
16344   if (BOK == BO_Add)
16345     return BO_AddAssign;
16346   if (BOK == BO_Mul)
16347     return BO_MulAssign;
16348   if (BOK == BO_And)
16349     return BO_AndAssign;
16350   if (BOK == BO_Or)
16351     return BO_OrAssign;
16352   if (BOK == BO_Xor)
16353     return BO_XorAssign;
16354   return BOK;
16355 }
16356 
16357 static bool actOnOMPReductionKindClause(
16358     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
16359     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16360     SourceLocation ColonLoc, SourceLocation EndLoc,
16361     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16362     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
16363   DeclarationName DN = ReductionId.getName();
16364   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
16365   BinaryOperatorKind BOK = BO_Comma;
16366 
16367   ASTContext &Context = S.Context;
16368   // OpenMP [2.14.3.6, reduction clause]
16369   // C
16370   // reduction-identifier is either an identifier or one of the following
16371   // operators: +, -, *,  &, |, ^, && and ||
16372   // C++
16373   // reduction-identifier is either an id-expression or one of the following
16374   // operators: +, -, *, &, |, ^, && and ||
16375   switch (OOK) {
16376   case OO_Plus:
16377   case OO_Minus:
16378     BOK = BO_Add;
16379     break;
16380   case OO_Star:
16381     BOK = BO_Mul;
16382     break;
16383   case OO_Amp:
16384     BOK = BO_And;
16385     break;
16386   case OO_Pipe:
16387     BOK = BO_Or;
16388     break;
16389   case OO_Caret:
16390     BOK = BO_Xor;
16391     break;
16392   case OO_AmpAmp:
16393     BOK = BO_LAnd;
16394     break;
16395   case OO_PipePipe:
16396     BOK = BO_LOr;
16397     break;
16398   case OO_New:
16399   case OO_Delete:
16400   case OO_Array_New:
16401   case OO_Array_Delete:
16402   case OO_Slash:
16403   case OO_Percent:
16404   case OO_Tilde:
16405   case OO_Exclaim:
16406   case OO_Equal:
16407   case OO_Less:
16408   case OO_Greater:
16409   case OO_LessEqual:
16410   case OO_GreaterEqual:
16411   case OO_PlusEqual:
16412   case OO_MinusEqual:
16413   case OO_StarEqual:
16414   case OO_SlashEqual:
16415   case OO_PercentEqual:
16416   case OO_CaretEqual:
16417   case OO_AmpEqual:
16418   case OO_PipeEqual:
16419   case OO_LessLess:
16420   case OO_GreaterGreater:
16421   case OO_LessLessEqual:
16422   case OO_GreaterGreaterEqual:
16423   case OO_EqualEqual:
16424   case OO_ExclaimEqual:
16425   case OO_Spaceship:
16426   case OO_PlusPlus:
16427   case OO_MinusMinus:
16428   case OO_Comma:
16429   case OO_ArrowStar:
16430   case OO_Arrow:
16431   case OO_Call:
16432   case OO_Subscript:
16433   case OO_Conditional:
16434   case OO_Coawait:
16435   case NUM_OVERLOADED_OPERATORS:
16436     llvm_unreachable("Unexpected reduction identifier");
16437   case OO_None:
16438     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
16439       if (II->isStr("max"))
16440         BOK = BO_GT;
16441       else if (II->isStr("min"))
16442         BOK = BO_LT;
16443     }
16444     break;
16445   }
16446   SourceRange ReductionIdRange;
16447   if (ReductionIdScopeSpec.isValid())
16448     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
16449   else
16450     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
16451   ReductionIdRange.setEnd(ReductionId.getEndLoc());
16452 
16453   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
16454   bool FirstIter = true;
16455   for (Expr *RefExpr : VarList) {
16456     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
16457     // OpenMP [2.1, C/C++]
16458     //  A list item is a variable or array section, subject to the restrictions
16459     //  specified in Section 2.4 on page 42 and in each of the sections
16460     // describing clauses and directives for which a list appears.
16461     // OpenMP  [2.14.3.3, Restrictions, p.1]
16462     //  A variable that is part of another variable (as an array or
16463     //  structure element) cannot appear in a private clause.
16464     if (!FirstIter && IR != ER)
16465       ++IR;
16466     FirstIter = false;
16467     SourceLocation ELoc;
16468     SourceRange ERange;
16469     Expr *SimpleRefExpr = RefExpr;
16470     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
16471                               /*AllowArraySection=*/true);
16472     if (Res.second) {
16473       // Try to find 'declare reduction' corresponding construct before using
16474       // builtin/overloaded operators.
16475       QualType Type = Context.DependentTy;
16476       CXXCastPath BasePath;
16477       ExprResult DeclareReductionRef = buildDeclareReductionRef(
16478           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16479           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16480       Expr *ReductionOp = nullptr;
16481       if (S.CurContext->isDependentContext() &&
16482           (DeclareReductionRef.isUnset() ||
16483            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
16484         ReductionOp = DeclareReductionRef.get();
16485       // It will be analyzed later.
16486       RD.push(RefExpr, ReductionOp);
16487     }
16488     ValueDecl *D = Res.first;
16489     if (!D)
16490       continue;
16491 
16492     Expr *TaskgroupDescriptor = nullptr;
16493     QualType Type;
16494     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
16495     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
16496     if (ASE) {
16497       Type = ASE->getType().getNonReferenceType();
16498     } else if (OASE) {
16499       QualType BaseType =
16500           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16501       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16502         Type = ATy->getElementType();
16503       else
16504         Type = BaseType->getPointeeType();
16505       Type = Type.getNonReferenceType();
16506     } else {
16507       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
16508     }
16509     auto *VD = dyn_cast<VarDecl>(D);
16510 
16511     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16512     //  A variable that appears in a private clause must not have an incomplete
16513     //  type or a reference type.
16514     if (S.RequireCompleteType(ELoc, D->getType(),
16515                               diag::err_omp_reduction_incomplete_type))
16516       continue;
16517     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16518     // A list item that appears in a reduction clause must not be
16519     // const-qualified.
16520     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
16521                                   /*AcceptIfMutable*/ false, ASE || OASE))
16522       continue;
16523 
16524     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
16525     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
16526     //  If a list-item is a reference type then it must bind to the same object
16527     //  for all threads of the team.
16528     if (!ASE && !OASE) {
16529       if (VD) {
16530         VarDecl *VDDef = VD->getDefinition();
16531         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
16532           DSARefChecker Check(Stack);
16533           if (Check.Visit(VDDef->getInit())) {
16534             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
16535                 << getOpenMPClauseName(ClauseKind) << ERange;
16536             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
16537             continue;
16538           }
16539         }
16540       }
16541 
16542       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16543       // in a Construct]
16544       //  Variables with the predetermined data-sharing attributes may not be
16545       //  listed in data-sharing attributes clauses, except for the cases
16546       //  listed below. For these exceptions only, listing a predetermined
16547       //  variable in a data-sharing attribute clause is allowed and overrides
16548       //  the variable's predetermined data-sharing attributes.
16549       // OpenMP [2.14.3.6, Restrictions, p.3]
16550       //  Any number of reduction clauses can be specified on the directive,
16551       //  but a list item can appear only once in the reduction clauses for that
16552       //  directive.
16553       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16554       if (DVar.CKind == OMPC_reduction) {
16555         S.Diag(ELoc, diag::err_omp_once_referenced)
16556             << getOpenMPClauseName(ClauseKind);
16557         if (DVar.RefExpr)
16558           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
16559         continue;
16560       }
16561       if (DVar.CKind != OMPC_unknown) {
16562         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16563             << getOpenMPClauseName(DVar.CKind)
16564             << getOpenMPClauseName(OMPC_reduction);
16565         reportOriginalDsa(S, Stack, D, DVar);
16566         continue;
16567       }
16568 
16569       // OpenMP [2.14.3.6, Restrictions, p.1]
16570       //  A list item that appears in a reduction clause of a worksharing
16571       //  construct must be shared in the parallel regions to which any of the
16572       //  worksharing regions arising from the worksharing construct bind.
16573       if (isOpenMPWorksharingDirective(CurrDir) &&
16574           !isOpenMPParallelDirective(CurrDir) &&
16575           !isOpenMPTeamsDirective(CurrDir)) {
16576         DVar = Stack->getImplicitDSA(D, true);
16577         if (DVar.CKind != OMPC_shared) {
16578           S.Diag(ELoc, diag::err_omp_required_access)
16579               << getOpenMPClauseName(OMPC_reduction)
16580               << getOpenMPClauseName(OMPC_shared);
16581           reportOriginalDsa(S, Stack, D, DVar);
16582           continue;
16583         }
16584       }
16585     } else {
16586       // Threadprivates cannot be shared between threads, so dignose if the base
16587       // is a threadprivate variable.
16588       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16589       if (DVar.CKind == OMPC_threadprivate) {
16590         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16591             << getOpenMPClauseName(DVar.CKind)
16592             << getOpenMPClauseName(OMPC_reduction);
16593         reportOriginalDsa(S, Stack, D, DVar);
16594         continue;
16595       }
16596     }
16597 
16598     // Try to find 'declare reduction' corresponding construct before using
16599     // builtin/overloaded operators.
16600     CXXCastPath BasePath;
16601     ExprResult DeclareReductionRef = buildDeclareReductionRef(
16602         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16603         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16604     if (DeclareReductionRef.isInvalid())
16605       continue;
16606     if (S.CurContext->isDependentContext() &&
16607         (DeclareReductionRef.isUnset() ||
16608          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
16609       RD.push(RefExpr, DeclareReductionRef.get());
16610       continue;
16611     }
16612     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
16613       // Not allowed reduction identifier is found.
16614       S.Diag(ReductionId.getBeginLoc(),
16615              diag::err_omp_unknown_reduction_identifier)
16616           << Type << ReductionIdRange;
16617       continue;
16618     }
16619 
16620     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16621     // The type of a list item that appears in a reduction clause must be valid
16622     // for the reduction-identifier. For a max or min reduction in C, the type
16623     // of the list item must be an allowed arithmetic data type: char, int,
16624     // float, double, or _Bool, possibly modified with long, short, signed, or
16625     // unsigned. For a max or min reduction in C++, the type of the list item
16626     // must be an allowed arithmetic data type: char, wchar_t, int, float,
16627     // double, or bool, possibly modified with long, short, signed, or unsigned.
16628     if (DeclareReductionRef.isUnset()) {
16629       if ((BOK == BO_GT || BOK == BO_LT) &&
16630           !(Type->isScalarType() ||
16631             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
16632         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
16633             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
16634         if (!ASE && !OASE) {
16635           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16636                                    VarDecl::DeclarationOnly;
16637           S.Diag(D->getLocation(),
16638                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16639               << D;
16640         }
16641         continue;
16642       }
16643       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
16644           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
16645         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
16646             << getOpenMPClauseName(ClauseKind);
16647         if (!ASE && !OASE) {
16648           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16649                                    VarDecl::DeclarationOnly;
16650           S.Diag(D->getLocation(),
16651                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16652               << D;
16653         }
16654         continue;
16655       }
16656     }
16657 
16658     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
16659     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
16660                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16661     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
16662                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16663     QualType PrivateTy = Type;
16664 
16665     // Try if we can determine constant lengths for all array sections and avoid
16666     // the VLA.
16667     bool ConstantLengthOASE = false;
16668     if (OASE) {
16669       bool SingleElement;
16670       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
16671       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
16672           Context, OASE, SingleElement, ArraySizes);
16673 
16674       // If we don't have a single element, we must emit a constant array type.
16675       if (ConstantLengthOASE && !SingleElement) {
16676         for (llvm::APSInt &Size : ArraySizes)
16677           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
16678                                                    ArrayType::Normal,
16679                                                    /*IndexTypeQuals=*/0);
16680       }
16681     }
16682 
16683     if ((OASE && !ConstantLengthOASE) ||
16684         (!OASE && !ASE &&
16685          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
16686       if (!Context.getTargetInfo().isVLASupported()) {
16687         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
16688           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
16689           S.Diag(ELoc, diag::note_vla_unsupported);
16690           continue;
16691         } else {
16692           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
16693           S.targetDiag(ELoc, diag::note_vla_unsupported);
16694         }
16695       }
16696       // For arrays/array sections only:
16697       // Create pseudo array type for private copy. The size for this array will
16698       // be generated during codegen.
16699       // For array subscripts or single variables Private Ty is the same as Type
16700       // (type of the variable or single array element).
16701       PrivateTy = Context.getVariableArrayType(
16702           Type,
16703           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
16704           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
16705     } else if (!ASE && !OASE &&
16706                Context.getAsArrayType(D->getType().getNonReferenceType())) {
16707       PrivateTy = D->getType().getNonReferenceType();
16708     }
16709     // Private copy.
16710     VarDecl *PrivateVD =
16711         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
16712                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16713                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16714     // Add initializer for private variable.
16715     Expr *Init = nullptr;
16716     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
16717     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
16718     if (DeclareReductionRef.isUsable()) {
16719       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
16720       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
16721       if (DRD->getInitializer()) {
16722         S.ActOnUninitializedDecl(PrivateVD);
16723         Init = DRDRef;
16724         RHSVD->setInit(DRDRef);
16725         RHSVD->setInitStyle(VarDecl::CallInit);
16726       }
16727     } else {
16728       switch (BOK) {
16729       case BO_Add:
16730       case BO_Xor:
16731       case BO_Or:
16732       case BO_LOr:
16733         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
16734         if (Type->isScalarType() || Type->isAnyComplexType())
16735           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
16736         break;
16737       case BO_Mul:
16738       case BO_LAnd:
16739         if (Type->isScalarType() || Type->isAnyComplexType()) {
16740           // '*' and '&&' reduction ops - initializer is '1'.
16741           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
16742         }
16743         break;
16744       case BO_And: {
16745         // '&' reduction op - initializer is '~0'.
16746         QualType OrigType = Type;
16747         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
16748           Type = ComplexTy->getElementType();
16749         if (Type->isRealFloatingType()) {
16750           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
16751               Context.getFloatTypeSemantics(Type),
16752               Context.getTypeSize(Type));
16753           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
16754                                          Type, ELoc);
16755         } else if (Type->isScalarType()) {
16756           uint64_t Size = Context.getTypeSize(Type);
16757           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
16758           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
16759           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
16760         }
16761         if (Init && OrigType->isAnyComplexType()) {
16762           // Init = 0xFFFF + 0xFFFFi;
16763           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
16764           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
16765         }
16766         Type = OrigType;
16767         break;
16768       }
16769       case BO_LT:
16770       case BO_GT: {
16771         // 'min' reduction op - initializer is 'Largest representable number in
16772         // the reduction list item type'.
16773         // 'max' reduction op - initializer is 'Least representable number in
16774         // the reduction list item type'.
16775         if (Type->isIntegerType() || Type->isPointerType()) {
16776           bool IsSigned = Type->hasSignedIntegerRepresentation();
16777           uint64_t Size = Context.getTypeSize(Type);
16778           QualType IntTy =
16779               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
16780           llvm::APInt InitValue =
16781               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
16782                                         : llvm::APInt::getMinValue(Size)
16783                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
16784                                         : llvm::APInt::getMaxValue(Size);
16785           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
16786           if (Type->isPointerType()) {
16787             // Cast to pointer type.
16788             ExprResult CastExpr = S.BuildCStyleCastExpr(
16789                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
16790             if (CastExpr.isInvalid())
16791               continue;
16792             Init = CastExpr.get();
16793           }
16794         } else if (Type->isRealFloatingType()) {
16795           llvm::APFloat InitValue = llvm::APFloat::getLargest(
16796               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
16797           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
16798                                          Type, ELoc);
16799         }
16800         break;
16801       }
16802       case BO_PtrMemD:
16803       case BO_PtrMemI:
16804       case BO_MulAssign:
16805       case BO_Div:
16806       case BO_Rem:
16807       case BO_Sub:
16808       case BO_Shl:
16809       case BO_Shr:
16810       case BO_LE:
16811       case BO_GE:
16812       case BO_EQ:
16813       case BO_NE:
16814       case BO_Cmp:
16815       case BO_AndAssign:
16816       case BO_XorAssign:
16817       case BO_OrAssign:
16818       case BO_Assign:
16819       case BO_AddAssign:
16820       case BO_SubAssign:
16821       case BO_DivAssign:
16822       case BO_RemAssign:
16823       case BO_ShlAssign:
16824       case BO_ShrAssign:
16825       case BO_Comma:
16826         llvm_unreachable("Unexpected reduction operation");
16827       }
16828     }
16829     if (Init && DeclareReductionRef.isUnset()) {
16830       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
16831       // Store initializer for single element in private copy. Will be used
16832       // during codegen.
16833       PrivateVD->setInit(RHSVD->getInit());
16834       PrivateVD->setInitStyle(RHSVD->getInitStyle());
16835     } else if (!Init) {
16836       S.ActOnUninitializedDecl(RHSVD);
16837       // Store initializer for single element in private copy. Will be used
16838       // during codegen.
16839       PrivateVD->setInit(RHSVD->getInit());
16840       PrivateVD->setInitStyle(RHSVD->getInitStyle());
16841     }
16842     if (RHSVD->isInvalidDecl())
16843       continue;
16844     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
16845       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
16846           << Type << ReductionIdRange;
16847       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16848                                VarDecl::DeclarationOnly;
16849       S.Diag(D->getLocation(),
16850              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16851           << D;
16852       continue;
16853     }
16854     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
16855     ExprResult ReductionOp;
16856     if (DeclareReductionRef.isUsable()) {
16857       QualType RedTy = DeclareReductionRef.get()->getType();
16858       QualType PtrRedTy = Context.getPointerType(RedTy);
16859       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
16860       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
16861       if (!BasePath.empty()) {
16862         LHS = S.DefaultLvalueConversion(LHS.get());
16863         RHS = S.DefaultLvalueConversion(RHS.get());
16864         LHS = ImplicitCastExpr::Create(
16865             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
16866             LHS.get()->getValueKind(), FPOptionsOverride());
16867         RHS = ImplicitCastExpr::Create(
16868             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
16869             RHS.get()->getValueKind(), FPOptionsOverride());
16870       }
16871       FunctionProtoType::ExtProtoInfo EPI;
16872       QualType Params[] = {PtrRedTy, PtrRedTy};
16873       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
16874       auto *OVE = new (Context) OpaqueValueExpr(
16875           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
16876           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
16877       Expr *Args[] = {LHS.get(), RHS.get()};
16878       ReductionOp =
16879           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc,
16880                            S.CurFPFeatureOverrides());
16881     } else {
16882       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
16883       if (Type->isRecordType() && CombBOK != BOK) {
16884         Sema::TentativeAnalysisScope Trap(S);
16885         ReductionOp =
16886             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16887                          CombBOK, LHSDRE, RHSDRE);
16888       }
16889       if (!ReductionOp.isUsable()) {
16890         ReductionOp =
16891             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
16892                          LHSDRE, RHSDRE);
16893         if (ReductionOp.isUsable()) {
16894           if (BOK != BO_LT && BOK != BO_GT) {
16895             ReductionOp =
16896                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16897                              BO_Assign, LHSDRE, ReductionOp.get());
16898           } else {
16899             auto *ConditionalOp = new (Context)
16900                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
16901                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
16902             ReductionOp =
16903                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16904                              BO_Assign, LHSDRE, ConditionalOp);
16905           }
16906         }
16907       }
16908       if (ReductionOp.isUsable())
16909         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
16910                                             /*DiscardedValue*/ false);
16911       if (!ReductionOp.isUsable())
16912         continue;
16913     }
16914 
16915     // Add copy operations for inscan reductions.
16916     // LHS = RHS;
16917     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
16918     if (ClauseKind == OMPC_reduction &&
16919         RD.RedModifier == OMPC_REDUCTION_inscan) {
16920       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
16921       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
16922                                RHS.get());
16923       if (!CopyOpRes.isUsable())
16924         continue;
16925       CopyOpRes =
16926           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
16927       if (!CopyOpRes.isUsable())
16928         continue;
16929       // For simd directive and simd-based directives in simd mode no need to
16930       // construct temp array, need just a single temp element.
16931       if (Stack->getCurrentDirective() == OMPD_simd ||
16932           (S.getLangOpts().OpenMPSimd &&
16933            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
16934         VarDecl *TempArrayVD =
16935             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
16936                          D->hasAttrs() ? &D->getAttrs() : nullptr);
16937         // Add a constructor to the temp decl.
16938         S.ActOnUninitializedDecl(TempArrayVD);
16939         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
16940       } else {
16941         // Build temp array for prefix sum.
16942         auto *Dim = new (S.Context)
16943             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
16944         QualType ArrayTy =
16945             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
16946                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
16947         VarDecl *TempArrayVD =
16948             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
16949                          D->hasAttrs() ? &D->getAttrs() : nullptr);
16950         // Add a constructor to the temp decl.
16951         S.ActOnUninitializedDecl(TempArrayVD);
16952         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
16953         TempArrayElem =
16954             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
16955         auto *Idx = new (S.Context)
16956             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
16957         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
16958                                                           ELoc, Idx, ELoc);
16959       }
16960     }
16961 
16962     // OpenMP [2.15.4.6, Restrictions, p.2]
16963     // A list item that appears in an in_reduction clause of a task construct
16964     // must appear in a task_reduction clause of a construct associated with a
16965     // taskgroup region that includes the participating task in its taskgroup
16966     // set. The construct associated with the innermost region that meets this
16967     // condition must specify the same reduction-identifier as the in_reduction
16968     // clause.
16969     if (ClauseKind == OMPC_in_reduction) {
16970       SourceRange ParentSR;
16971       BinaryOperatorKind ParentBOK;
16972       const Expr *ParentReductionOp = nullptr;
16973       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
16974       DSAStackTy::DSAVarData ParentBOKDSA =
16975           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
16976                                                   ParentBOKTD);
16977       DSAStackTy::DSAVarData ParentReductionOpDSA =
16978           Stack->getTopMostTaskgroupReductionData(
16979               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
16980       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
16981       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
16982       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
16983           (DeclareReductionRef.isUsable() && IsParentBOK) ||
16984           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
16985         bool EmitError = true;
16986         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
16987           llvm::FoldingSetNodeID RedId, ParentRedId;
16988           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
16989           DeclareReductionRef.get()->Profile(RedId, Context,
16990                                              /*Canonical=*/true);
16991           EmitError = RedId != ParentRedId;
16992         }
16993         if (EmitError) {
16994           S.Diag(ReductionId.getBeginLoc(),
16995                  diag::err_omp_reduction_identifier_mismatch)
16996               << ReductionIdRange << RefExpr->getSourceRange();
16997           S.Diag(ParentSR.getBegin(),
16998                  diag::note_omp_previous_reduction_identifier)
16999               << ParentSR
17000               << (IsParentBOK ? ParentBOKDSA.RefExpr
17001                               : ParentReductionOpDSA.RefExpr)
17002                      ->getSourceRange();
17003           continue;
17004         }
17005       }
17006       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
17007     }
17008 
17009     DeclRefExpr *Ref = nullptr;
17010     Expr *VarsExpr = RefExpr->IgnoreParens();
17011     if (!VD && !S.CurContext->isDependentContext()) {
17012       if (ASE || OASE) {
17013         TransformExprToCaptures RebuildToCapture(S, D);
17014         VarsExpr =
17015             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
17016         Ref = RebuildToCapture.getCapturedExpr();
17017       } else {
17018         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
17019       }
17020       if (!S.isOpenMPCapturedDecl(D)) {
17021         RD.ExprCaptures.emplace_back(Ref->getDecl());
17022         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17023           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
17024           if (!RefRes.isUsable())
17025             continue;
17026           ExprResult PostUpdateRes =
17027               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17028                            RefRes.get());
17029           if (!PostUpdateRes.isUsable())
17030             continue;
17031           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
17032               Stack->getCurrentDirective() == OMPD_taskgroup) {
17033             S.Diag(RefExpr->getExprLoc(),
17034                    diag::err_omp_reduction_non_addressable_expression)
17035                 << RefExpr->getSourceRange();
17036             continue;
17037           }
17038           RD.ExprPostUpdates.emplace_back(
17039               S.IgnoredValueConversions(PostUpdateRes.get()).get());
17040         }
17041       }
17042     }
17043     // All reduction items are still marked as reduction (to do not increase
17044     // code base size).
17045     unsigned Modifier = RD.RedModifier;
17046     // Consider task_reductions as reductions with task modifier. Required for
17047     // correct analysis of in_reduction clauses.
17048     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
17049       Modifier = OMPC_REDUCTION_task;
17050     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
17051                   ASE || OASE);
17052     if (Modifier == OMPC_REDUCTION_task &&
17053         (CurrDir == OMPD_taskgroup ||
17054          ((isOpenMPParallelDirective(CurrDir) ||
17055            isOpenMPWorksharingDirective(CurrDir)) &&
17056           !isOpenMPSimdDirective(CurrDir)))) {
17057       if (DeclareReductionRef.isUsable())
17058         Stack->addTaskgroupReductionData(D, ReductionIdRange,
17059                                          DeclareReductionRef.get());
17060       else
17061         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
17062     }
17063     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
17064             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
17065             TempArrayElem.get());
17066   }
17067   return RD.Vars.empty();
17068 }
17069 
17070 OMPClause *Sema::ActOnOpenMPReductionClause(
17071     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
17072     SourceLocation StartLoc, SourceLocation LParenLoc,
17073     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
17074     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17075     ArrayRef<Expr *> UnresolvedReductions) {
17076   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
17077     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
17078         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
17079                                    /*Last=*/OMPC_REDUCTION_unknown)
17080         << getOpenMPClauseName(OMPC_reduction);
17081     return nullptr;
17082   }
17083   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
17084   // A reduction clause with the inscan reduction-modifier may only appear on a
17085   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
17086   // construct, a parallel worksharing-loop construct or a parallel
17087   // worksharing-loop SIMD construct.
17088   if (Modifier == OMPC_REDUCTION_inscan &&
17089       (DSAStack->getCurrentDirective() != OMPD_for &&
17090        DSAStack->getCurrentDirective() != OMPD_for_simd &&
17091        DSAStack->getCurrentDirective() != OMPD_simd &&
17092        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
17093        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
17094     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
17095     return nullptr;
17096   }
17097 
17098   ReductionData RD(VarList.size(), Modifier);
17099   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
17100                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17101                                   ReductionIdScopeSpec, ReductionId,
17102                                   UnresolvedReductions, RD))
17103     return nullptr;
17104 
17105   return OMPReductionClause::Create(
17106       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
17107       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17108       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
17109       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
17110       buildPreInits(Context, RD.ExprCaptures),
17111       buildPostUpdate(*this, RD.ExprPostUpdates));
17112 }
17113 
17114 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
17115     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17116     SourceLocation ColonLoc, SourceLocation EndLoc,
17117     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17118     ArrayRef<Expr *> UnresolvedReductions) {
17119   ReductionData RD(VarList.size());
17120   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17121                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17122                                   ReductionIdScopeSpec, ReductionId,
17123                                   UnresolvedReductions, RD))
17124     return nullptr;
17125 
17126   return OMPTaskReductionClause::Create(
17127       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17128       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17129       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17130       buildPreInits(Context, RD.ExprCaptures),
17131       buildPostUpdate(*this, RD.ExprPostUpdates));
17132 }
17133 
17134 OMPClause *Sema::ActOnOpenMPInReductionClause(
17135     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17136     SourceLocation ColonLoc, SourceLocation EndLoc,
17137     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17138     ArrayRef<Expr *> UnresolvedReductions) {
17139   ReductionData RD(VarList.size());
17140   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17141                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17142                                   ReductionIdScopeSpec, ReductionId,
17143                                   UnresolvedReductions, RD))
17144     return nullptr;
17145 
17146   return OMPInReductionClause::Create(
17147       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17148       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17149       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17150       buildPreInits(Context, RD.ExprCaptures),
17151       buildPostUpdate(*this, RD.ExprPostUpdates));
17152 }
17153 
17154 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17155                                      SourceLocation LinLoc) {
17156   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17157       LinKind == OMPC_LINEAR_unknown) {
17158     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17159     return true;
17160   }
17161   return false;
17162 }
17163 
17164 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17165                                  OpenMPLinearClauseKind LinKind, QualType Type,
17166                                  bool IsDeclareSimd) {
17167   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17168   // A variable must not have an incomplete type or a reference type.
17169   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17170     return true;
17171   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17172       !Type->isReferenceType()) {
17173     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17174         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17175     return true;
17176   }
17177   Type = Type.getNonReferenceType();
17178 
17179   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17180   // A variable that is privatized must not have a const-qualified type
17181   // unless it is of class type with a mutable member. This restriction does
17182   // not apply to the firstprivate clause, nor to the linear clause on
17183   // declarative directives (like declare simd).
17184   if (!IsDeclareSimd &&
17185       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17186     return true;
17187 
17188   // A list item must be of integral or pointer type.
17189   Type = Type.getUnqualifiedType().getCanonicalType();
17190   const auto *Ty = Type.getTypePtrOrNull();
17191   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17192               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17193     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17194     if (D) {
17195       bool IsDecl =
17196           !VD ||
17197           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17198       Diag(D->getLocation(),
17199            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17200           << D;
17201     }
17202     return true;
17203   }
17204   return false;
17205 }
17206 
17207 OMPClause *Sema::ActOnOpenMPLinearClause(
17208     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17209     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17210     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17211   SmallVector<Expr *, 8> Vars;
17212   SmallVector<Expr *, 8> Privates;
17213   SmallVector<Expr *, 8> Inits;
17214   SmallVector<Decl *, 4> ExprCaptures;
17215   SmallVector<Expr *, 4> ExprPostUpdates;
17216   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17217     LinKind = OMPC_LINEAR_val;
17218   for (Expr *RefExpr : VarList) {
17219     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17220     SourceLocation ELoc;
17221     SourceRange ERange;
17222     Expr *SimpleRefExpr = RefExpr;
17223     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17224     if (Res.second) {
17225       // It will be analyzed later.
17226       Vars.push_back(RefExpr);
17227       Privates.push_back(nullptr);
17228       Inits.push_back(nullptr);
17229     }
17230     ValueDecl *D = Res.first;
17231     if (!D)
17232       continue;
17233 
17234     QualType Type = D->getType();
17235     auto *VD = dyn_cast<VarDecl>(D);
17236 
17237     // OpenMP [2.14.3.7, linear clause]
17238     //  A list-item cannot appear in more than one linear clause.
17239     //  A list-item that appears in a linear clause cannot appear in any
17240     //  other data-sharing attribute clause.
17241     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17242     if (DVar.RefExpr) {
17243       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17244                                           << getOpenMPClauseName(OMPC_linear);
17245       reportOriginalDsa(*this, DSAStack, D, DVar);
17246       continue;
17247     }
17248 
17249     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17250       continue;
17251     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17252 
17253     // Build private copy of original var.
17254     VarDecl *Private =
17255         buildVarDecl(*this, ELoc, Type, D->getName(),
17256                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17257                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17258     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17259     // Build var to save initial value.
17260     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17261     Expr *InitExpr;
17262     DeclRefExpr *Ref = nullptr;
17263     if (!VD && !CurContext->isDependentContext()) {
17264       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17265       if (!isOpenMPCapturedDecl(D)) {
17266         ExprCaptures.push_back(Ref->getDecl());
17267         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17268           ExprResult RefRes = DefaultLvalueConversion(Ref);
17269           if (!RefRes.isUsable())
17270             continue;
17271           ExprResult PostUpdateRes =
17272               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17273                          SimpleRefExpr, RefRes.get());
17274           if (!PostUpdateRes.isUsable())
17275             continue;
17276           ExprPostUpdates.push_back(
17277               IgnoredValueConversions(PostUpdateRes.get()).get());
17278         }
17279       }
17280     }
17281     if (LinKind == OMPC_LINEAR_uval)
17282       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17283     else
17284       InitExpr = VD ? SimpleRefExpr : Ref;
17285     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17286                          /*DirectInit=*/false);
17287     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17288 
17289     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17290     Vars.push_back((VD || CurContext->isDependentContext())
17291                        ? RefExpr->IgnoreParens()
17292                        : Ref);
17293     Privates.push_back(PrivateRef);
17294     Inits.push_back(InitRef);
17295   }
17296 
17297   if (Vars.empty())
17298     return nullptr;
17299 
17300   Expr *StepExpr = Step;
17301   Expr *CalcStepExpr = nullptr;
17302   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17303       !Step->isInstantiationDependent() &&
17304       !Step->containsUnexpandedParameterPack()) {
17305     SourceLocation StepLoc = Step->getBeginLoc();
17306     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17307     if (Val.isInvalid())
17308       return nullptr;
17309     StepExpr = Val.get();
17310 
17311     // Build var to save the step value.
17312     VarDecl *SaveVar =
17313         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17314     ExprResult SaveRef =
17315         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17316     ExprResult CalcStep =
17317         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17318     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17319 
17320     // Warn about zero linear step (it would be probably better specified as
17321     // making corresponding variables 'const').
17322     if (Optional<llvm::APSInt> Result =
17323             StepExpr->getIntegerConstantExpr(Context)) {
17324       if (!Result->isNegative() && !Result->isStrictlyPositive())
17325         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17326             << Vars[0] << (Vars.size() > 1);
17327     } else if (CalcStep.isUsable()) {
17328       // Calculate the step beforehand instead of doing this on each iteration.
17329       // (This is not used if the number of iterations may be kfold-ed).
17330       CalcStepExpr = CalcStep.get();
17331     }
17332   }
17333 
17334   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17335                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17336                                  StepExpr, CalcStepExpr,
17337                                  buildPreInits(Context, ExprCaptures),
17338                                  buildPostUpdate(*this, ExprPostUpdates));
17339 }
17340 
17341 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
17342                                      Expr *NumIterations, Sema &SemaRef,
17343                                      Scope *S, DSAStackTy *Stack) {
17344   // Walk the vars and build update/final expressions for the CodeGen.
17345   SmallVector<Expr *, 8> Updates;
17346   SmallVector<Expr *, 8> Finals;
17347   SmallVector<Expr *, 8> UsedExprs;
17348   Expr *Step = Clause.getStep();
17349   Expr *CalcStep = Clause.getCalcStep();
17350   // OpenMP [2.14.3.7, linear clause]
17351   // If linear-step is not specified it is assumed to be 1.
17352   if (!Step)
17353     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
17354   else if (CalcStep)
17355     Step = cast<BinaryOperator>(CalcStep)->getLHS();
17356   bool HasErrors = false;
17357   auto CurInit = Clause.inits().begin();
17358   auto CurPrivate = Clause.privates().begin();
17359   OpenMPLinearClauseKind LinKind = Clause.getModifier();
17360   for (Expr *RefExpr : Clause.varlists()) {
17361     SourceLocation ELoc;
17362     SourceRange ERange;
17363     Expr *SimpleRefExpr = RefExpr;
17364     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
17365     ValueDecl *D = Res.first;
17366     if (Res.second || !D) {
17367       Updates.push_back(nullptr);
17368       Finals.push_back(nullptr);
17369       HasErrors = true;
17370       continue;
17371     }
17372     auto &&Info = Stack->isLoopControlVariable(D);
17373     // OpenMP [2.15.11, distribute simd Construct]
17374     // A list item may not appear in a linear clause, unless it is the loop
17375     // iteration variable.
17376     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
17377         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
17378       SemaRef.Diag(ELoc,
17379                    diag::err_omp_linear_distribute_var_non_loop_iteration);
17380       Updates.push_back(nullptr);
17381       Finals.push_back(nullptr);
17382       HasErrors = true;
17383       continue;
17384     }
17385     Expr *InitExpr = *CurInit;
17386 
17387     // Build privatized reference to the current linear var.
17388     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
17389     Expr *CapturedRef;
17390     if (LinKind == OMPC_LINEAR_uval)
17391       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
17392     else
17393       CapturedRef =
17394           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
17395                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
17396                            /*RefersToCapture=*/true);
17397 
17398     // Build update: Var = InitExpr + IV * Step
17399     ExprResult Update;
17400     if (!Info.first)
17401       Update = buildCounterUpdate(
17402           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
17403           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
17404     else
17405       Update = *CurPrivate;
17406     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
17407                                          /*DiscardedValue*/ false);
17408 
17409     // Build final: Var = InitExpr + NumIterations * Step
17410     ExprResult Final;
17411     if (!Info.first)
17412       Final =
17413           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
17414                              InitExpr, NumIterations, Step, /*Subtract=*/false,
17415                              /*IsNonRectangularLB=*/false);
17416     else
17417       Final = *CurPrivate;
17418     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
17419                                         /*DiscardedValue*/ false);
17420 
17421     if (!Update.isUsable() || !Final.isUsable()) {
17422       Updates.push_back(nullptr);
17423       Finals.push_back(nullptr);
17424       UsedExprs.push_back(nullptr);
17425       HasErrors = true;
17426     } else {
17427       Updates.push_back(Update.get());
17428       Finals.push_back(Final.get());
17429       if (!Info.first)
17430         UsedExprs.push_back(SimpleRefExpr);
17431     }
17432     ++CurInit;
17433     ++CurPrivate;
17434   }
17435   if (Expr *S = Clause.getStep())
17436     UsedExprs.push_back(S);
17437   // Fill the remaining part with the nullptr.
17438   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
17439   Clause.setUpdates(Updates);
17440   Clause.setFinals(Finals);
17441   Clause.setUsedExprs(UsedExprs);
17442   return HasErrors;
17443 }
17444 
17445 OMPClause *Sema::ActOnOpenMPAlignedClause(
17446     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
17447     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17448   SmallVector<Expr *, 8> Vars;
17449   for (Expr *RefExpr : VarList) {
17450     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17451     SourceLocation ELoc;
17452     SourceRange ERange;
17453     Expr *SimpleRefExpr = RefExpr;
17454     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17455     if (Res.second) {
17456       // It will be analyzed later.
17457       Vars.push_back(RefExpr);
17458     }
17459     ValueDecl *D = Res.first;
17460     if (!D)
17461       continue;
17462 
17463     QualType QType = D->getType();
17464     auto *VD = dyn_cast<VarDecl>(D);
17465 
17466     // OpenMP  [2.8.1, simd construct, Restrictions]
17467     // The type of list items appearing in the aligned clause must be
17468     // array, pointer, reference to array, or reference to pointer.
17469     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17470     const Type *Ty = QType.getTypePtrOrNull();
17471     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
17472       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
17473           << QType << getLangOpts().CPlusPlus << ERange;
17474       bool IsDecl =
17475           !VD ||
17476           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17477       Diag(D->getLocation(),
17478            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17479           << D;
17480       continue;
17481     }
17482 
17483     // OpenMP  [2.8.1, simd construct, Restrictions]
17484     // A list-item cannot appear in more than one aligned clause.
17485     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
17486       Diag(ELoc, diag::err_omp_used_in_clause_twice)
17487           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
17488       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17489           << getOpenMPClauseName(OMPC_aligned);
17490       continue;
17491     }
17492 
17493     DeclRefExpr *Ref = nullptr;
17494     if (!VD && isOpenMPCapturedDecl(D))
17495       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17496     Vars.push_back(DefaultFunctionArrayConversion(
17497                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
17498                        .get());
17499   }
17500 
17501   // OpenMP [2.8.1, simd construct, Description]
17502   // The parameter of the aligned clause, alignment, must be a constant
17503   // positive integer expression.
17504   // If no optional parameter is specified, implementation-defined default
17505   // alignments for SIMD instructions on the target platforms are assumed.
17506   if (Alignment != nullptr) {
17507     ExprResult AlignResult =
17508         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
17509     if (AlignResult.isInvalid())
17510       return nullptr;
17511     Alignment = AlignResult.get();
17512   }
17513   if (Vars.empty())
17514     return nullptr;
17515 
17516   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
17517                                   EndLoc, Vars, Alignment);
17518 }
17519 
17520 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
17521                                          SourceLocation StartLoc,
17522                                          SourceLocation LParenLoc,
17523                                          SourceLocation EndLoc) {
17524   SmallVector<Expr *, 8> Vars;
17525   SmallVector<Expr *, 8> SrcExprs;
17526   SmallVector<Expr *, 8> DstExprs;
17527   SmallVector<Expr *, 8> AssignmentOps;
17528   for (Expr *RefExpr : VarList) {
17529     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
17530     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17531       // It will be analyzed later.
17532       Vars.push_back(RefExpr);
17533       SrcExprs.push_back(nullptr);
17534       DstExprs.push_back(nullptr);
17535       AssignmentOps.push_back(nullptr);
17536       continue;
17537     }
17538 
17539     SourceLocation ELoc = RefExpr->getExprLoc();
17540     // OpenMP [2.1, C/C++]
17541     //  A list item is a variable name.
17542     // OpenMP  [2.14.4.1, Restrictions, p.1]
17543     //  A list item that appears in a copyin clause must be threadprivate.
17544     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
17545     if (!DE || !isa<VarDecl>(DE->getDecl())) {
17546       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
17547           << 0 << RefExpr->getSourceRange();
17548       continue;
17549     }
17550 
17551     Decl *D = DE->getDecl();
17552     auto *VD = cast<VarDecl>(D);
17553 
17554     QualType Type = VD->getType();
17555     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
17556       // It will be analyzed later.
17557       Vars.push_back(DE);
17558       SrcExprs.push_back(nullptr);
17559       DstExprs.push_back(nullptr);
17560       AssignmentOps.push_back(nullptr);
17561       continue;
17562     }
17563 
17564     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
17565     //  A list item that appears in a copyin clause must be threadprivate.
17566     if (!DSAStack->isThreadPrivate(VD)) {
17567       Diag(ELoc, diag::err_omp_required_access)
17568           << getOpenMPClauseName(OMPC_copyin)
17569           << getOpenMPDirectiveName(OMPD_threadprivate);
17570       continue;
17571     }
17572 
17573     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17574     //  A variable of class type (or array thereof) that appears in a
17575     //  copyin clause requires an accessible, unambiguous copy assignment
17576     //  operator for the class type.
17577     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17578     VarDecl *SrcVD =
17579         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
17580                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17581     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
17582         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
17583     VarDecl *DstVD =
17584         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
17585                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17586     DeclRefExpr *PseudoDstExpr =
17587         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
17588     // For arrays generate assignment operation for single element and replace
17589     // it by the original array element in CodeGen.
17590     ExprResult AssignmentOp =
17591         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
17592                    PseudoSrcExpr);
17593     if (AssignmentOp.isInvalid())
17594       continue;
17595     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
17596                                        /*DiscardedValue*/ false);
17597     if (AssignmentOp.isInvalid())
17598       continue;
17599 
17600     DSAStack->addDSA(VD, DE, OMPC_copyin);
17601     Vars.push_back(DE);
17602     SrcExprs.push_back(PseudoSrcExpr);
17603     DstExprs.push_back(PseudoDstExpr);
17604     AssignmentOps.push_back(AssignmentOp.get());
17605   }
17606 
17607   if (Vars.empty())
17608     return nullptr;
17609 
17610   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17611                                  SrcExprs, DstExprs, AssignmentOps);
17612 }
17613 
17614 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
17615                                               SourceLocation StartLoc,
17616                                               SourceLocation LParenLoc,
17617                                               SourceLocation EndLoc) {
17618   SmallVector<Expr *, 8> Vars;
17619   SmallVector<Expr *, 8> SrcExprs;
17620   SmallVector<Expr *, 8> DstExprs;
17621   SmallVector<Expr *, 8> AssignmentOps;
17622   for (Expr *RefExpr : VarList) {
17623     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17624     SourceLocation ELoc;
17625     SourceRange ERange;
17626     Expr *SimpleRefExpr = RefExpr;
17627     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17628     if (Res.second) {
17629       // It will be analyzed later.
17630       Vars.push_back(RefExpr);
17631       SrcExprs.push_back(nullptr);
17632       DstExprs.push_back(nullptr);
17633       AssignmentOps.push_back(nullptr);
17634     }
17635     ValueDecl *D = Res.first;
17636     if (!D)
17637       continue;
17638 
17639     QualType Type = D->getType();
17640     auto *VD = dyn_cast<VarDecl>(D);
17641 
17642     // OpenMP [2.14.4.2, Restrictions, p.2]
17643     //  A list item that appears in a copyprivate clause may not appear in a
17644     //  private or firstprivate clause on the single construct.
17645     if (!VD || !DSAStack->isThreadPrivate(VD)) {
17646       DSAStackTy::DSAVarData DVar =
17647           DSAStack->getTopDSA(D, /*FromParent=*/false);
17648       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
17649           DVar.RefExpr) {
17650         Diag(ELoc, diag::err_omp_wrong_dsa)
17651             << getOpenMPClauseName(DVar.CKind)
17652             << getOpenMPClauseName(OMPC_copyprivate);
17653         reportOriginalDsa(*this, DSAStack, D, DVar);
17654         continue;
17655       }
17656 
17657       // OpenMP [2.11.4.2, Restrictions, p.1]
17658       //  All list items that appear in a copyprivate clause must be either
17659       //  threadprivate or private in the enclosing context.
17660       if (DVar.CKind == OMPC_unknown) {
17661         DVar = DSAStack->getImplicitDSA(D, false);
17662         if (DVar.CKind == OMPC_shared) {
17663           Diag(ELoc, diag::err_omp_required_access)
17664               << getOpenMPClauseName(OMPC_copyprivate)
17665               << "threadprivate or private in the enclosing context";
17666           reportOriginalDsa(*this, DSAStack, D, DVar);
17667           continue;
17668         }
17669       }
17670     }
17671 
17672     // Variably modified types are not supported.
17673     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
17674       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17675           << getOpenMPClauseName(OMPC_copyprivate) << Type
17676           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17677       bool IsDecl =
17678           !VD ||
17679           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17680       Diag(D->getLocation(),
17681            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17682           << D;
17683       continue;
17684     }
17685 
17686     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17687     //  A variable of class type (or array thereof) that appears in a
17688     //  copyin clause requires an accessible, unambiguous copy assignment
17689     //  operator for the class type.
17690     Type = Context.getBaseElementType(Type.getNonReferenceType())
17691                .getUnqualifiedType();
17692     VarDecl *SrcVD =
17693         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
17694                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17695     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
17696     VarDecl *DstVD =
17697         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
17698                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17699     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
17700     ExprResult AssignmentOp = BuildBinOp(
17701         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
17702     if (AssignmentOp.isInvalid())
17703       continue;
17704     AssignmentOp =
17705         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
17706     if (AssignmentOp.isInvalid())
17707       continue;
17708 
17709     // No need to mark vars as copyprivate, they are already threadprivate or
17710     // implicitly private.
17711     assert(VD || isOpenMPCapturedDecl(D));
17712     Vars.push_back(
17713         VD ? RefExpr->IgnoreParens()
17714            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
17715     SrcExprs.push_back(PseudoSrcExpr);
17716     DstExprs.push_back(PseudoDstExpr);
17717     AssignmentOps.push_back(AssignmentOp.get());
17718   }
17719 
17720   if (Vars.empty())
17721     return nullptr;
17722 
17723   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17724                                       Vars, SrcExprs, DstExprs, AssignmentOps);
17725 }
17726 
17727 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
17728                                         SourceLocation StartLoc,
17729                                         SourceLocation LParenLoc,
17730                                         SourceLocation EndLoc) {
17731   if (VarList.empty())
17732     return nullptr;
17733 
17734   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
17735 }
17736 
17737 /// Tries to find omp_depend_t. type.
17738 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
17739                            bool Diagnose = true) {
17740   QualType OMPDependT = Stack->getOMPDependT();
17741   if (!OMPDependT.isNull())
17742     return true;
17743   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
17744   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
17745   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
17746     if (Diagnose)
17747       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
17748     return false;
17749   }
17750   Stack->setOMPDependT(PT.get());
17751   return true;
17752 }
17753 
17754 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
17755                                          SourceLocation LParenLoc,
17756                                          SourceLocation EndLoc) {
17757   if (!Depobj)
17758     return nullptr;
17759 
17760   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
17761 
17762   // OpenMP 5.0, 2.17.10.1 depobj Construct
17763   // depobj is an lvalue expression of type omp_depend_t.
17764   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
17765       !Depobj->isInstantiationDependent() &&
17766       !Depobj->containsUnexpandedParameterPack() &&
17767       (OMPDependTFound &&
17768        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
17769                                    /*CompareUnqualified=*/true))) {
17770     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
17771         << 0 << Depobj->getType() << Depobj->getSourceRange();
17772   }
17773 
17774   if (!Depobj->isLValue()) {
17775     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
17776         << 1 << Depobj->getSourceRange();
17777   }
17778 
17779   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
17780 }
17781 
17782 OMPClause *
17783 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
17784                               SourceLocation DepLoc, SourceLocation ColonLoc,
17785                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17786                               SourceLocation LParenLoc, SourceLocation EndLoc) {
17787   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
17788       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
17789     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
17790         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
17791     return nullptr;
17792   }
17793   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
17794        DSAStack->getCurrentDirective() == OMPD_depobj) &&
17795       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
17796        DepKind == OMPC_DEPEND_sink ||
17797        ((LangOpts.OpenMP < 50 ||
17798          DSAStack->getCurrentDirective() == OMPD_depobj) &&
17799         DepKind == OMPC_DEPEND_depobj))) {
17800     SmallVector<unsigned, 3> Except;
17801     Except.push_back(OMPC_DEPEND_source);
17802     Except.push_back(OMPC_DEPEND_sink);
17803     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
17804       Except.push_back(OMPC_DEPEND_depobj);
17805     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
17806                                ? "depend modifier(iterator) or "
17807                                : "";
17808     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
17809         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
17810                                               /*Last=*/OMPC_DEPEND_unknown,
17811                                               Except)
17812         << getOpenMPClauseName(OMPC_depend);
17813     return nullptr;
17814   }
17815   if (DepModifier &&
17816       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
17817     Diag(DepModifier->getExprLoc(),
17818          diag::err_omp_depend_sink_source_with_modifier);
17819     return nullptr;
17820   }
17821   if (DepModifier &&
17822       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
17823     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
17824 
17825   SmallVector<Expr *, 8> Vars;
17826   DSAStackTy::OperatorOffsetTy OpsOffs;
17827   llvm::APSInt DepCounter(/*BitWidth=*/32);
17828   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
17829   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
17830     if (const Expr *OrderedCountExpr =
17831             DSAStack->getParentOrderedRegionParam().first) {
17832       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
17833       TotalDepCount.setIsUnsigned(/*Val=*/true);
17834     }
17835   }
17836   for (Expr *RefExpr : VarList) {
17837     assert(RefExpr && "NULL expr in OpenMP shared clause.");
17838     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17839       // It will be analyzed later.
17840       Vars.push_back(RefExpr);
17841       continue;
17842     }
17843 
17844     SourceLocation ELoc = RefExpr->getExprLoc();
17845     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
17846     if (DepKind == OMPC_DEPEND_sink) {
17847       if (DSAStack->getParentOrderedRegionParam().first &&
17848           DepCounter >= TotalDepCount) {
17849         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
17850         continue;
17851       }
17852       ++DepCounter;
17853       // OpenMP  [2.13.9, Summary]
17854       // depend(dependence-type : vec), where dependence-type is:
17855       // 'sink' and where vec is the iteration vector, which has the form:
17856       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
17857       // where n is the value specified by the ordered clause in the loop
17858       // directive, xi denotes the loop iteration variable of the i-th nested
17859       // loop associated with the loop directive, and di is a constant
17860       // non-negative integer.
17861       if (CurContext->isDependentContext()) {
17862         // It will be analyzed later.
17863         Vars.push_back(RefExpr);
17864         continue;
17865       }
17866       SimpleExpr = SimpleExpr->IgnoreImplicit();
17867       OverloadedOperatorKind OOK = OO_None;
17868       SourceLocation OOLoc;
17869       Expr *LHS = SimpleExpr;
17870       Expr *RHS = nullptr;
17871       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
17872         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
17873         OOLoc = BO->getOperatorLoc();
17874         LHS = BO->getLHS()->IgnoreParenImpCasts();
17875         RHS = BO->getRHS()->IgnoreParenImpCasts();
17876       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
17877         OOK = OCE->getOperator();
17878         OOLoc = OCE->getOperatorLoc();
17879         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
17880         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
17881       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
17882         OOK = MCE->getMethodDecl()
17883                   ->getNameInfo()
17884                   .getName()
17885                   .getCXXOverloadedOperator();
17886         OOLoc = MCE->getCallee()->getExprLoc();
17887         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
17888         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
17889       }
17890       SourceLocation ELoc;
17891       SourceRange ERange;
17892       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
17893       if (Res.second) {
17894         // It will be analyzed later.
17895         Vars.push_back(RefExpr);
17896       }
17897       ValueDecl *D = Res.first;
17898       if (!D)
17899         continue;
17900 
17901       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
17902         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
17903         continue;
17904       }
17905       if (RHS) {
17906         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
17907             RHS, OMPC_depend, /*StrictlyPositive=*/false);
17908         if (RHSRes.isInvalid())
17909           continue;
17910       }
17911       if (!CurContext->isDependentContext() &&
17912           DSAStack->getParentOrderedRegionParam().first &&
17913           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
17914         const ValueDecl *VD =
17915             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
17916         if (VD)
17917           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
17918               << 1 << VD;
17919         else
17920           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
17921         continue;
17922       }
17923       OpsOffs.emplace_back(RHS, OOK);
17924     } else {
17925       bool OMPDependTFound = LangOpts.OpenMP >= 50;
17926       if (OMPDependTFound)
17927         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
17928                                          DepKind == OMPC_DEPEND_depobj);
17929       if (DepKind == OMPC_DEPEND_depobj) {
17930         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
17931         // List items used in depend clauses with the depobj dependence type
17932         // must be expressions of the omp_depend_t type.
17933         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
17934             !RefExpr->isInstantiationDependent() &&
17935             !RefExpr->containsUnexpandedParameterPack() &&
17936             (OMPDependTFound &&
17937              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
17938                                              RefExpr->getType()))) {
17939           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
17940               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
17941           continue;
17942         }
17943         if (!RefExpr->isLValue()) {
17944           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
17945               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
17946           continue;
17947         }
17948       } else {
17949         // OpenMP 5.0 [2.17.11, Restrictions]
17950         // List items used in depend clauses cannot be zero-length array
17951         // sections.
17952         QualType ExprTy = RefExpr->getType().getNonReferenceType();
17953         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
17954         if (OASE) {
17955           QualType BaseType =
17956               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17957           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17958             ExprTy = ATy->getElementType();
17959           else
17960             ExprTy = BaseType->getPointeeType();
17961           ExprTy = ExprTy.getNonReferenceType();
17962           const Expr *Length = OASE->getLength();
17963           Expr::EvalResult Result;
17964           if (Length && !Length->isValueDependent() &&
17965               Length->EvaluateAsInt(Result, Context) &&
17966               Result.Val.getInt().isNullValue()) {
17967             Diag(ELoc,
17968                  diag::err_omp_depend_zero_length_array_section_not_allowed)
17969                 << SimpleExpr->getSourceRange();
17970             continue;
17971           }
17972         }
17973 
17974         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
17975         // List items used in depend clauses with the in, out, inout or
17976         // mutexinoutset dependence types cannot be expressions of the
17977         // omp_depend_t type.
17978         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
17979             !RefExpr->isInstantiationDependent() &&
17980             !RefExpr->containsUnexpandedParameterPack() &&
17981             (OMPDependTFound &&
17982              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
17983           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17984               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
17985               << RefExpr->getSourceRange();
17986           continue;
17987         }
17988 
17989         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
17990         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
17991             (ASE && !ASE->getBase()->isTypeDependent() &&
17992              !ASE->getBase()
17993                   ->getType()
17994                   .getNonReferenceType()
17995                   ->isPointerType() &&
17996              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
17997           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17998               << (LangOpts.OpenMP >= 50 ? 1 : 0)
17999               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18000           continue;
18001         }
18002 
18003         ExprResult Res;
18004         {
18005           Sema::TentativeAnalysisScope Trap(*this);
18006           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
18007                                      RefExpr->IgnoreParenImpCasts());
18008         }
18009         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18010             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18011           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18012               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18013               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18014           continue;
18015         }
18016       }
18017     }
18018     Vars.push_back(RefExpr->IgnoreParenImpCasts());
18019   }
18020 
18021   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
18022       TotalDepCount > VarList.size() &&
18023       DSAStack->getParentOrderedRegionParam().first &&
18024       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
18025     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
18026         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
18027   }
18028   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
18029       Vars.empty())
18030     return nullptr;
18031 
18032   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18033                                     DepModifier, DepKind, DepLoc, ColonLoc,
18034                                     Vars, TotalDepCount.getZExtValue());
18035   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
18036       DSAStack->isParentOrderedRegion())
18037     DSAStack->addDoacrossDependClause(C, OpsOffs);
18038   return C;
18039 }
18040 
18041 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
18042                                          Expr *Device, SourceLocation StartLoc,
18043                                          SourceLocation LParenLoc,
18044                                          SourceLocation ModifierLoc,
18045                                          SourceLocation EndLoc) {
18046   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
18047          "Unexpected device modifier in OpenMP < 50.");
18048 
18049   bool ErrorFound = false;
18050   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
18051     std::string Values =
18052         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
18053     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
18054         << Values << getOpenMPClauseName(OMPC_device);
18055     ErrorFound = true;
18056   }
18057 
18058   Expr *ValExpr = Device;
18059   Stmt *HelperValStmt = nullptr;
18060 
18061   // OpenMP [2.9.1, Restrictions]
18062   // The device expression must evaluate to a non-negative integer value.
18063   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
18064                                           /*StrictlyPositive=*/false) ||
18065                ErrorFound;
18066   if (ErrorFound)
18067     return nullptr;
18068 
18069   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18070   OpenMPDirectiveKind CaptureRegion =
18071       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
18072   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18073     ValExpr = MakeFullExpr(ValExpr).get();
18074     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18075     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18076     HelperValStmt = buildPreInits(Context, Captures);
18077   }
18078 
18079   return new (Context)
18080       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18081                       LParenLoc, ModifierLoc, EndLoc);
18082 }
18083 
18084 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
18085                               DSAStackTy *Stack, QualType QTy,
18086                               bool FullCheck = true) {
18087   NamedDecl *ND;
18088   if (QTy->isIncompleteType(&ND)) {
18089     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
18090     return false;
18091   }
18092   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
18093       !QTy.isTriviallyCopyableType(SemaRef.Context))
18094     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
18095   return true;
18096 }
18097 
18098 /// Return true if it can be proven that the provided array expression
18099 /// (array section or array subscript) does NOT specify the whole size of the
18100 /// array whose base type is \a BaseQTy.
18101 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
18102                                                         const Expr *E,
18103                                                         QualType BaseQTy) {
18104   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18105 
18106   // If this is an array subscript, it refers to the whole size if the size of
18107   // the dimension is constant and equals 1. Also, an array section assumes the
18108   // format of an array subscript if no colon is used.
18109   if (isa<ArraySubscriptExpr>(E) ||
18110       (OASE && OASE->getColonLocFirst().isInvalid())) {
18111     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18112       return ATy->getSize().getSExtValue() != 1;
18113     // Size can't be evaluated statically.
18114     return false;
18115   }
18116 
18117   assert(OASE && "Expecting array section if not an array subscript.");
18118   const Expr *LowerBound = OASE->getLowerBound();
18119   const Expr *Length = OASE->getLength();
18120 
18121   // If there is a lower bound that does not evaluates to zero, we are not
18122   // covering the whole dimension.
18123   if (LowerBound) {
18124     Expr::EvalResult Result;
18125     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18126       return false; // Can't get the integer value as a constant.
18127 
18128     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18129     if (ConstLowerBound.getSExtValue())
18130       return true;
18131   }
18132 
18133   // If we don't have a length we covering the whole dimension.
18134   if (!Length)
18135     return false;
18136 
18137   // If the base is a pointer, we don't have a way to get the size of the
18138   // pointee.
18139   if (BaseQTy->isPointerType())
18140     return false;
18141 
18142   // We can only check if the length is the same as the size of the dimension
18143   // if we have a constant array.
18144   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18145   if (!CATy)
18146     return false;
18147 
18148   Expr::EvalResult Result;
18149   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18150     return false; // Can't get the integer value as a constant.
18151 
18152   llvm::APSInt ConstLength = Result.Val.getInt();
18153   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18154 }
18155 
18156 // Return true if it can be proven that the provided array expression (array
18157 // section or array subscript) does NOT specify a single element of the array
18158 // whose base type is \a BaseQTy.
18159 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18160                                                         const Expr *E,
18161                                                         QualType BaseQTy) {
18162   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18163 
18164   // An array subscript always refer to a single element. Also, an array section
18165   // assumes the format of an array subscript if no colon is used.
18166   if (isa<ArraySubscriptExpr>(E) ||
18167       (OASE && OASE->getColonLocFirst().isInvalid()))
18168     return false;
18169 
18170   assert(OASE && "Expecting array section if not an array subscript.");
18171   const Expr *Length = OASE->getLength();
18172 
18173   // If we don't have a length we have to check if the array has unitary size
18174   // for this dimension. Also, we should always expect a length if the base type
18175   // is pointer.
18176   if (!Length) {
18177     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18178       return ATy->getSize().getSExtValue() != 1;
18179     // We cannot assume anything.
18180     return false;
18181   }
18182 
18183   // Check if the length evaluates to 1.
18184   Expr::EvalResult Result;
18185   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18186     return false; // Can't get the integer value as a constant.
18187 
18188   llvm::APSInt ConstLength = Result.Val.getInt();
18189   return ConstLength.getSExtValue() != 1;
18190 }
18191 
18192 // The base of elements of list in a map clause have to be either:
18193 //  - a reference to variable or field.
18194 //  - a member expression.
18195 //  - an array expression.
18196 //
18197 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18198 // reference to 'r'.
18199 //
18200 // If we have:
18201 //
18202 // struct SS {
18203 //   Bla S;
18204 //   foo() {
18205 //     #pragma omp target map (S.Arr[:12]);
18206 //   }
18207 // }
18208 //
18209 // We want to retrieve the member expression 'this->S';
18210 
18211 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18212 //  If a list item is an array section, it must specify contiguous storage.
18213 //
18214 // For this restriction it is sufficient that we make sure only references
18215 // to variables or fields and array expressions, and that no array sections
18216 // exist except in the rightmost expression (unless they cover the whole
18217 // dimension of the array). E.g. these would be invalid:
18218 //
18219 //   r.ArrS[3:5].Arr[6:7]
18220 //
18221 //   r.ArrS[3:5].x
18222 //
18223 // but these would be valid:
18224 //   r.ArrS[3].Arr[6:7]
18225 //
18226 //   r.ArrS[3].x
18227 namespace {
18228 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18229   Sema &SemaRef;
18230   OpenMPClauseKind CKind = OMPC_unknown;
18231   OpenMPDirectiveKind DKind = OMPD_unknown;
18232   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18233   bool IsNonContiguous = false;
18234   bool NoDiagnose = false;
18235   const Expr *RelevantExpr = nullptr;
18236   bool AllowUnitySizeArraySection = true;
18237   bool AllowWholeSizeArraySection = true;
18238   bool AllowAnotherPtr = true;
18239   SourceLocation ELoc;
18240   SourceRange ERange;
18241 
18242   void emitErrorMsg() {
18243     // If nothing else worked, this is not a valid map clause expression.
18244     if (SemaRef.getLangOpts().OpenMP < 50) {
18245       SemaRef.Diag(ELoc,
18246                    diag::err_omp_expected_named_var_member_or_array_expression)
18247           << ERange;
18248     } else {
18249       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18250           << getOpenMPClauseName(CKind) << ERange;
18251     }
18252   }
18253 
18254 public:
18255   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18256     if (!isa<VarDecl>(DRE->getDecl())) {
18257       emitErrorMsg();
18258       return false;
18259     }
18260     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18261     RelevantExpr = DRE;
18262     // Record the component.
18263     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18264     return true;
18265   }
18266 
18267   bool VisitMemberExpr(MemberExpr *ME) {
18268     Expr *E = ME;
18269     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18270 
18271     if (isa<CXXThisExpr>(BaseE)) {
18272       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18273       // We found a base expression: this->Val.
18274       RelevantExpr = ME;
18275     } else {
18276       E = BaseE;
18277     }
18278 
18279     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18280       if (!NoDiagnose) {
18281         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18282           << ME->getSourceRange();
18283         return false;
18284       }
18285       if (RelevantExpr)
18286         return false;
18287       return Visit(E);
18288     }
18289 
18290     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18291 
18292     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18293     //  A bit-field cannot appear in a map clause.
18294     //
18295     if (FD->isBitField()) {
18296       if (!NoDiagnose) {
18297         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18298           << ME->getSourceRange() << getOpenMPClauseName(CKind);
18299         return false;
18300       }
18301       if (RelevantExpr)
18302         return false;
18303       return Visit(E);
18304     }
18305 
18306     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18307     //  If the type of a list item is a reference to a type T then the type
18308     //  will be considered to be T for all purposes of this clause.
18309     QualType CurType = BaseE->getType().getNonReferenceType();
18310 
18311     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18312     //  A list item cannot be a variable that is a member of a structure with
18313     //  a union type.
18314     //
18315     if (CurType->isUnionType()) {
18316       if (!NoDiagnose) {
18317         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18318           << ME->getSourceRange();
18319         return false;
18320       }
18321       return RelevantExpr || Visit(E);
18322     }
18323 
18324     // If we got a member expression, we should not expect any array section
18325     // before that:
18326     //
18327     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18328     //  If a list item is an element of a structure, only the rightmost symbol
18329     //  of the variable reference can be an array section.
18330     //
18331     AllowUnitySizeArraySection = false;
18332     AllowWholeSizeArraySection = false;
18333 
18334     // Record the component.
18335     Components.emplace_back(ME, FD, IsNonContiguous);
18336     return RelevantExpr || Visit(E);
18337   }
18338 
18339   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18340     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18341 
18342     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
18343       if (!NoDiagnose) {
18344         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18345           << 0 << AE->getSourceRange();
18346         return false;
18347       }
18348       return RelevantExpr || Visit(E);
18349     }
18350 
18351     // If we got an array subscript that express the whole dimension we
18352     // can have any array expressions before. If it only expressing part of
18353     // the dimension, we can only have unitary-size array expressions.
18354     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
18355                                                     E->getType()))
18356       AllowWholeSizeArraySection = false;
18357 
18358     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
18359       Expr::EvalResult Result;
18360       if (!AE->getIdx()->isValueDependent() &&
18361           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
18362           !Result.Val.getInt().isNullValue()) {
18363         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18364                      diag::err_omp_invalid_map_this_expr);
18365         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18366                      diag::note_omp_invalid_subscript_on_this_ptr_map);
18367       }
18368       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18369       RelevantExpr = TE;
18370     }
18371 
18372     // Record the component - we don't have any declaration associated.
18373     Components.emplace_back(AE, nullptr, IsNonContiguous);
18374 
18375     return RelevantExpr || Visit(E);
18376   }
18377 
18378   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
18379     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
18380     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18381     QualType CurType =
18382       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18383 
18384     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18385     //  If the type of a list item is a reference to a type T then the type
18386     //  will be considered to be T for all purposes of this clause.
18387     if (CurType->isReferenceType())
18388       CurType = CurType->getPointeeType();
18389 
18390     bool IsPointer = CurType->isAnyPointerType();
18391 
18392     if (!IsPointer && !CurType->isArrayType()) {
18393       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18394         << 0 << OASE->getSourceRange();
18395       return false;
18396     }
18397 
18398     bool NotWhole =
18399       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
18400     bool NotUnity =
18401       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
18402 
18403     if (AllowWholeSizeArraySection) {
18404       // Any array section is currently allowed. Allowing a whole size array
18405       // section implies allowing a unity array section as well.
18406       //
18407       // If this array section refers to the whole dimension we can still
18408       // accept other array sections before this one, except if the base is a
18409       // pointer. Otherwise, only unitary sections are accepted.
18410       if (NotWhole || IsPointer)
18411         AllowWholeSizeArraySection = false;
18412     } else if (DKind == OMPD_target_update &&
18413                SemaRef.getLangOpts().OpenMP >= 50) {
18414       if (IsPointer && !AllowAnotherPtr)
18415         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
18416             << /*array of unknown bound */ 1;
18417       else
18418         IsNonContiguous = true;
18419     } else if (AllowUnitySizeArraySection && NotUnity) {
18420       // A unity or whole array section is not allowed and that is not
18421       // compatible with the properties of the current array section.
18422       SemaRef.Diag(
18423         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
18424         << OASE->getSourceRange();
18425       return false;
18426     }
18427 
18428     if (IsPointer)
18429       AllowAnotherPtr = false;
18430 
18431     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
18432       Expr::EvalResult ResultR;
18433       Expr::EvalResult ResultL;
18434       if (!OASE->getLength()->isValueDependent() &&
18435           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
18436           !ResultR.Val.getInt().isOneValue()) {
18437         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18438                      diag::err_omp_invalid_map_this_expr);
18439         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18440                      diag::note_omp_invalid_length_on_this_ptr_mapping);
18441       }
18442       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
18443           OASE->getLowerBound()->EvaluateAsInt(ResultL,
18444                                                SemaRef.getASTContext()) &&
18445           !ResultL.Val.getInt().isNullValue()) {
18446         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18447                      diag::err_omp_invalid_map_this_expr);
18448         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18449                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
18450       }
18451       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18452       RelevantExpr = TE;
18453     }
18454 
18455     // Record the component - we don't have any declaration associated.
18456     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
18457     return RelevantExpr || Visit(E);
18458   }
18459   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
18460     Expr *Base = E->getBase();
18461 
18462     // Record the component - we don't have any declaration associated.
18463     Components.emplace_back(E, nullptr, IsNonContiguous);
18464 
18465     return Visit(Base->IgnoreParenImpCasts());
18466   }
18467 
18468   bool VisitUnaryOperator(UnaryOperator *UO) {
18469     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
18470         UO->getOpcode() != UO_Deref) {
18471       emitErrorMsg();
18472       return false;
18473     }
18474     if (!RelevantExpr) {
18475       // Record the component if haven't found base decl.
18476       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
18477     }
18478     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
18479   }
18480   bool VisitBinaryOperator(BinaryOperator *BO) {
18481     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
18482       emitErrorMsg();
18483       return false;
18484     }
18485 
18486     // Pointer arithmetic is the only thing we expect to happen here so after we
18487     // make sure the binary operator is a pointer type, the we only thing need
18488     // to to is to visit the subtree that has the same type as root (so that we
18489     // know the other subtree is just an offset)
18490     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
18491     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
18492     Components.emplace_back(BO, nullptr, false);
18493     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
18494             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
18495            "Either LHS or RHS have base decl inside");
18496     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
18497       return RelevantExpr || Visit(LE);
18498     return RelevantExpr || Visit(RE);
18499   }
18500   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
18501     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18502     RelevantExpr = CTE;
18503     Components.emplace_back(CTE, nullptr, IsNonContiguous);
18504     return true;
18505   }
18506   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
18507     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18508     Components.emplace_back(COCE, nullptr, IsNonContiguous);
18509     return true;
18510   }
18511   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
18512     Expr *Source = E->getSourceExpr();
18513     if (!Source) {
18514       emitErrorMsg();
18515       return false;
18516     }
18517     return Visit(Source);
18518   }
18519   bool VisitStmt(Stmt *) {
18520     emitErrorMsg();
18521     return false;
18522   }
18523   const Expr *getFoundBase() const {
18524     return RelevantExpr;
18525   }
18526   explicit MapBaseChecker(
18527       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
18528       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
18529       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
18530       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
18531         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
18532 };
18533 } // namespace
18534 
18535 /// Return the expression of the base of the mappable expression or null if it
18536 /// cannot be determined and do all the necessary checks to see if the expression
18537 /// is valid as a standalone mappable expression. In the process, record all the
18538 /// components of the expression.
18539 static const Expr *checkMapClauseExpressionBase(
18540     Sema &SemaRef, Expr *E,
18541     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
18542     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
18543   SourceLocation ELoc = E->getExprLoc();
18544   SourceRange ERange = E->getSourceRange();
18545   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
18546                          ERange);
18547   if (Checker.Visit(E->IgnoreParens())) {
18548     // Check if the highest dimension array section has length specified
18549     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
18550         (CKind == OMPC_to || CKind == OMPC_from)) {
18551       auto CI = CurComponents.rbegin();
18552       auto CE = CurComponents.rend();
18553       for (; CI != CE; ++CI) {
18554         const auto *OASE =
18555             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
18556         if (!OASE)
18557           continue;
18558         if (OASE && OASE->getLength())
18559           break;
18560         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
18561             << ERange;
18562       }
18563     }
18564     return Checker.getFoundBase();
18565   }
18566   return nullptr;
18567 }
18568 
18569 // Return true if expression E associated with value VD has conflicts with other
18570 // map information.
18571 static bool checkMapConflicts(
18572     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
18573     bool CurrentRegionOnly,
18574     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
18575     OpenMPClauseKind CKind) {
18576   assert(VD && E);
18577   SourceLocation ELoc = E->getExprLoc();
18578   SourceRange ERange = E->getSourceRange();
18579 
18580   // In order to easily check the conflicts we need to match each component of
18581   // the expression under test with the components of the expressions that are
18582   // already in the stack.
18583 
18584   assert(!CurComponents.empty() && "Map clause expression with no components!");
18585   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
18586          "Map clause expression with unexpected base!");
18587 
18588   // Variables to help detecting enclosing problems in data environment nests.
18589   bool IsEnclosedByDataEnvironmentExpr = false;
18590   const Expr *EnclosingExpr = nullptr;
18591 
18592   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
18593       VD, CurrentRegionOnly,
18594       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
18595        ERange, CKind, &EnclosingExpr,
18596        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
18597                           StackComponents,
18598                       OpenMPClauseKind Kind) {
18599         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
18600           return false;
18601         assert(!StackComponents.empty() &&
18602                "Map clause expression with no components!");
18603         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
18604                "Map clause expression with unexpected base!");
18605         (void)VD;
18606 
18607         // The whole expression in the stack.
18608         const Expr *RE = StackComponents.front().getAssociatedExpression();
18609 
18610         // Expressions must start from the same base. Here we detect at which
18611         // point both expressions diverge from each other and see if we can
18612         // detect if the memory referred to both expressions is contiguous and
18613         // do not overlap.
18614         auto CI = CurComponents.rbegin();
18615         auto CE = CurComponents.rend();
18616         auto SI = StackComponents.rbegin();
18617         auto SE = StackComponents.rend();
18618         for (; CI != CE && SI != SE; ++CI, ++SI) {
18619 
18620           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
18621           //  At most one list item can be an array item derived from a given
18622           //  variable in map clauses of the same construct.
18623           if (CurrentRegionOnly &&
18624               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
18625                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
18626                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
18627               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
18628                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
18629                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
18630             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
18631                          diag::err_omp_multiple_array_items_in_map_clause)
18632                 << CI->getAssociatedExpression()->getSourceRange();
18633             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
18634                          diag::note_used_here)
18635                 << SI->getAssociatedExpression()->getSourceRange();
18636             return true;
18637           }
18638 
18639           // Do both expressions have the same kind?
18640           if (CI->getAssociatedExpression()->getStmtClass() !=
18641               SI->getAssociatedExpression()->getStmtClass())
18642             break;
18643 
18644           // Are we dealing with different variables/fields?
18645           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
18646             break;
18647         }
18648         // Check if the extra components of the expressions in the enclosing
18649         // data environment are redundant for the current base declaration.
18650         // If they are, the maps completely overlap, which is legal.
18651         for (; SI != SE; ++SI) {
18652           QualType Type;
18653           if (const auto *ASE =
18654                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
18655             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
18656           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
18657                          SI->getAssociatedExpression())) {
18658             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18659             Type =
18660                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18661           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
18662                          SI->getAssociatedExpression())) {
18663             Type = OASE->getBase()->getType()->getPointeeType();
18664           }
18665           if (Type.isNull() || Type->isAnyPointerType() ||
18666               checkArrayExpressionDoesNotReferToWholeSize(
18667                   SemaRef, SI->getAssociatedExpression(), Type))
18668             break;
18669         }
18670 
18671         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
18672         //  List items of map clauses in the same construct must not share
18673         //  original storage.
18674         //
18675         // If the expressions are exactly the same or one is a subset of the
18676         // other, it means they are sharing storage.
18677         if (CI == CE && SI == SE) {
18678           if (CurrentRegionOnly) {
18679             if (CKind == OMPC_map) {
18680               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
18681             } else {
18682               assert(CKind == OMPC_to || CKind == OMPC_from);
18683               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
18684                   << ERange;
18685             }
18686             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18687                 << RE->getSourceRange();
18688             return true;
18689           }
18690           // If we find the same expression in the enclosing data environment,
18691           // that is legal.
18692           IsEnclosedByDataEnvironmentExpr = true;
18693           return false;
18694         }
18695 
18696         QualType DerivedType =
18697             std::prev(CI)->getAssociatedDeclaration()->getType();
18698         SourceLocation DerivedLoc =
18699             std::prev(CI)->getAssociatedExpression()->getExprLoc();
18700 
18701         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18702         //  If the type of a list item is a reference to a type T then the type
18703         //  will be considered to be T for all purposes of this clause.
18704         DerivedType = DerivedType.getNonReferenceType();
18705 
18706         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
18707         //  A variable for which the type is pointer and an array section
18708         //  derived from that variable must not appear as list items of map
18709         //  clauses of the same construct.
18710         //
18711         // Also, cover one of the cases in:
18712         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
18713         //  If any part of the original storage of a list item has corresponding
18714         //  storage in the device data environment, all of the original storage
18715         //  must have corresponding storage in the device data environment.
18716         //
18717         if (DerivedType->isAnyPointerType()) {
18718           if (CI == CE || SI == SE) {
18719             SemaRef.Diag(
18720                 DerivedLoc,
18721                 diag::err_omp_pointer_mapped_along_with_derived_section)
18722                 << DerivedLoc;
18723             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18724                 << RE->getSourceRange();
18725             return true;
18726           }
18727           if (CI->getAssociatedExpression()->getStmtClass() !=
18728                          SI->getAssociatedExpression()->getStmtClass() ||
18729                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
18730                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
18731             assert(CI != CE && SI != SE);
18732             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
18733                 << DerivedLoc;
18734             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18735                 << RE->getSourceRange();
18736             return true;
18737           }
18738         }
18739 
18740         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
18741         //  List items of map clauses in the same construct must not share
18742         //  original storage.
18743         //
18744         // An expression is a subset of the other.
18745         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
18746           if (CKind == OMPC_map) {
18747             if (CI != CE || SI != SE) {
18748               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
18749               // a pointer.
18750               auto Begin =
18751                   CI != CE ? CurComponents.begin() : StackComponents.begin();
18752               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
18753               auto It = Begin;
18754               while (It != End && !It->getAssociatedDeclaration())
18755                 std::advance(It, 1);
18756               assert(It != End &&
18757                      "Expected at least one component with the declaration.");
18758               if (It != Begin && It->getAssociatedDeclaration()
18759                                      ->getType()
18760                                      .getCanonicalType()
18761                                      ->isAnyPointerType()) {
18762                 IsEnclosedByDataEnvironmentExpr = false;
18763                 EnclosingExpr = nullptr;
18764                 return false;
18765               }
18766             }
18767             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
18768           } else {
18769             assert(CKind == OMPC_to || CKind == OMPC_from);
18770             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
18771                 << ERange;
18772           }
18773           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18774               << RE->getSourceRange();
18775           return true;
18776         }
18777 
18778         // The current expression uses the same base as other expression in the
18779         // data environment but does not contain it completely.
18780         if (!CurrentRegionOnly && SI != SE)
18781           EnclosingExpr = RE;
18782 
18783         // The current expression is a subset of the expression in the data
18784         // environment.
18785         IsEnclosedByDataEnvironmentExpr |=
18786             (!CurrentRegionOnly && CI != CE && SI == SE);
18787 
18788         return false;
18789       });
18790 
18791   if (CurrentRegionOnly)
18792     return FoundError;
18793 
18794   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
18795   //  If any part of the original storage of a list item has corresponding
18796   //  storage in the device data environment, all of the original storage must
18797   //  have corresponding storage in the device data environment.
18798   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
18799   //  If a list item is an element of a structure, and a different element of
18800   //  the structure has a corresponding list item in the device data environment
18801   //  prior to a task encountering the construct associated with the map clause,
18802   //  then the list item must also have a corresponding list item in the device
18803   //  data environment prior to the task encountering the construct.
18804   //
18805   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
18806     SemaRef.Diag(ELoc,
18807                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
18808         << ERange;
18809     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
18810         << EnclosingExpr->getSourceRange();
18811     return true;
18812   }
18813 
18814   return FoundError;
18815 }
18816 
18817 // Look up the user-defined mapper given the mapper name and mapped type, and
18818 // build a reference to it.
18819 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
18820                                             CXXScopeSpec &MapperIdScopeSpec,
18821                                             const DeclarationNameInfo &MapperId,
18822                                             QualType Type,
18823                                             Expr *UnresolvedMapper) {
18824   if (MapperIdScopeSpec.isInvalid())
18825     return ExprError();
18826   // Get the actual type for the array type.
18827   if (Type->isArrayType()) {
18828     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
18829     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
18830   }
18831   // Find all user-defined mappers with the given MapperId.
18832   SmallVector<UnresolvedSet<8>, 4> Lookups;
18833   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
18834   Lookup.suppressDiagnostics();
18835   if (S) {
18836     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
18837       NamedDecl *D = Lookup.getRepresentativeDecl();
18838       while (S && !S->isDeclScope(D))
18839         S = S->getParent();
18840       if (S)
18841         S = S->getParent();
18842       Lookups.emplace_back();
18843       Lookups.back().append(Lookup.begin(), Lookup.end());
18844       Lookup.clear();
18845     }
18846   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
18847     // Extract the user-defined mappers with the given MapperId.
18848     Lookups.push_back(UnresolvedSet<8>());
18849     for (NamedDecl *D : ULE->decls()) {
18850       auto *DMD = cast<OMPDeclareMapperDecl>(D);
18851       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
18852       Lookups.back().addDecl(DMD);
18853     }
18854   }
18855   // Defer the lookup for dependent types. The results will be passed through
18856   // UnresolvedMapper on instantiation.
18857   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
18858       Type->isInstantiationDependentType() ||
18859       Type->containsUnexpandedParameterPack() ||
18860       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
18861         return !D->isInvalidDecl() &&
18862                (D->getType()->isDependentType() ||
18863                 D->getType()->isInstantiationDependentType() ||
18864                 D->getType()->containsUnexpandedParameterPack());
18865       })) {
18866     UnresolvedSet<8> URS;
18867     for (const UnresolvedSet<8> &Set : Lookups) {
18868       if (Set.empty())
18869         continue;
18870       URS.append(Set.begin(), Set.end());
18871     }
18872     return UnresolvedLookupExpr::Create(
18873         SemaRef.Context, /*NamingClass=*/nullptr,
18874         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
18875         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
18876   }
18877   SourceLocation Loc = MapperId.getLoc();
18878   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
18879   //  The type must be of struct, union or class type in C and C++
18880   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
18881       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
18882     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
18883     return ExprError();
18884   }
18885   // Perform argument dependent lookup.
18886   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
18887     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
18888   // Return the first user-defined mapper with the desired type.
18889   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18890           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
18891             if (!D->isInvalidDecl() &&
18892                 SemaRef.Context.hasSameType(D->getType(), Type))
18893               return D;
18894             return nullptr;
18895           }))
18896     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
18897   // Find the first user-defined mapper with a type derived from the desired
18898   // type.
18899   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18900           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
18901             if (!D->isInvalidDecl() &&
18902                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
18903                 !Type.isMoreQualifiedThan(D->getType()))
18904               return D;
18905             return nullptr;
18906           })) {
18907     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
18908                        /*DetectVirtual=*/false);
18909     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
18910       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
18911               VD->getType().getUnqualifiedType()))) {
18912         if (SemaRef.CheckBaseClassAccess(
18913                 Loc, VD->getType(), Type, Paths.front(),
18914                 /*DiagID=*/0) != Sema::AR_inaccessible) {
18915           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
18916         }
18917       }
18918     }
18919   }
18920   // Report error if a mapper is specified, but cannot be found.
18921   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
18922     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
18923         << Type << MapperId.getName();
18924     return ExprError();
18925   }
18926   return ExprEmpty();
18927 }
18928 
18929 namespace {
18930 // Utility struct that gathers all the related lists associated with a mappable
18931 // expression.
18932 struct MappableVarListInfo {
18933   // The list of expressions.
18934   ArrayRef<Expr *> VarList;
18935   // The list of processed expressions.
18936   SmallVector<Expr *, 16> ProcessedVarList;
18937   // The mappble components for each expression.
18938   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
18939   // The base declaration of the variable.
18940   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
18941   // The reference to the user-defined mapper associated with every expression.
18942   SmallVector<Expr *, 16> UDMapperList;
18943 
18944   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
18945     // We have a list of components and base declarations for each entry in the
18946     // variable list.
18947     VarComponents.reserve(VarList.size());
18948     VarBaseDeclarations.reserve(VarList.size());
18949   }
18950 };
18951 }
18952 
18953 // Check the validity of the provided variable list for the provided clause kind
18954 // \a CKind. In the check process the valid expressions, mappable expression
18955 // components, variables, and user-defined mappers are extracted and used to
18956 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
18957 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
18958 // and \a MapperId are expected to be valid if the clause kind is 'map'.
18959 static void checkMappableExpressionList(
18960     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
18961     MappableVarListInfo &MVLI, SourceLocation StartLoc,
18962     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
18963     ArrayRef<Expr *> UnresolvedMappers,
18964     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
18965     bool IsMapTypeImplicit = false) {
18966   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
18967   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
18968          "Unexpected clause kind with mappable expressions!");
18969 
18970   // If the identifier of user-defined mapper is not specified, it is "default".
18971   // We do not change the actual name in this clause to distinguish whether a
18972   // mapper is specified explicitly, i.e., it is not explicitly specified when
18973   // MapperId.getName() is empty.
18974   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
18975     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
18976     MapperId.setName(DeclNames.getIdentifier(
18977         &SemaRef.getASTContext().Idents.get("default")));
18978     MapperId.setLoc(StartLoc);
18979   }
18980 
18981   // Iterators to find the current unresolved mapper expression.
18982   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
18983   bool UpdateUMIt = false;
18984   Expr *UnresolvedMapper = nullptr;
18985 
18986   // Keep track of the mappable components and base declarations in this clause.
18987   // Each entry in the list is going to have a list of components associated. We
18988   // record each set of the components so that we can build the clause later on.
18989   // In the end we should have the same amount of declarations and component
18990   // lists.
18991 
18992   for (Expr *RE : MVLI.VarList) {
18993     assert(RE && "Null expr in omp to/from/map clause");
18994     SourceLocation ELoc = RE->getExprLoc();
18995 
18996     // Find the current unresolved mapper expression.
18997     if (UpdateUMIt && UMIt != UMEnd) {
18998       UMIt++;
18999       assert(
19000           UMIt != UMEnd &&
19001           "Expect the size of UnresolvedMappers to match with that of VarList");
19002     }
19003     UpdateUMIt = true;
19004     if (UMIt != UMEnd)
19005       UnresolvedMapper = *UMIt;
19006 
19007     const Expr *VE = RE->IgnoreParenLValueCasts();
19008 
19009     if (VE->isValueDependent() || VE->isTypeDependent() ||
19010         VE->isInstantiationDependent() ||
19011         VE->containsUnexpandedParameterPack()) {
19012       // Try to find the associated user-defined mapper.
19013       ExprResult ER = buildUserDefinedMapperRef(
19014           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19015           VE->getType().getCanonicalType(), UnresolvedMapper);
19016       if (ER.isInvalid())
19017         continue;
19018       MVLI.UDMapperList.push_back(ER.get());
19019       // We can only analyze this information once the missing information is
19020       // resolved.
19021       MVLI.ProcessedVarList.push_back(RE);
19022       continue;
19023     }
19024 
19025     Expr *SimpleExpr = RE->IgnoreParenCasts();
19026 
19027     if (!RE->isLValue()) {
19028       if (SemaRef.getLangOpts().OpenMP < 50) {
19029         SemaRef.Diag(
19030             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
19031             << RE->getSourceRange();
19032       } else {
19033         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19034             << getOpenMPClauseName(CKind) << RE->getSourceRange();
19035       }
19036       continue;
19037     }
19038 
19039     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
19040     ValueDecl *CurDeclaration = nullptr;
19041 
19042     // Obtain the array or member expression bases if required. Also, fill the
19043     // components array with all the components identified in the process.
19044     const Expr *BE = checkMapClauseExpressionBase(
19045         SemaRef, SimpleExpr, CurComponents, CKind, DSAS->getCurrentDirective(),
19046         /*NoDiagnose=*/false);
19047     if (!BE)
19048       continue;
19049 
19050     assert(!CurComponents.empty() &&
19051            "Invalid mappable expression information.");
19052 
19053     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
19054       // Add store "this" pointer to class in DSAStackTy for future checking
19055       DSAS->addMappedClassesQualTypes(TE->getType());
19056       // Try to find the associated user-defined mapper.
19057       ExprResult ER = buildUserDefinedMapperRef(
19058           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19059           VE->getType().getCanonicalType(), UnresolvedMapper);
19060       if (ER.isInvalid())
19061         continue;
19062       MVLI.UDMapperList.push_back(ER.get());
19063       // Skip restriction checking for variable or field declarations
19064       MVLI.ProcessedVarList.push_back(RE);
19065       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19066       MVLI.VarComponents.back().append(CurComponents.begin(),
19067                                        CurComponents.end());
19068       MVLI.VarBaseDeclarations.push_back(nullptr);
19069       continue;
19070     }
19071 
19072     // For the following checks, we rely on the base declaration which is
19073     // expected to be associated with the last component. The declaration is
19074     // expected to be a variable or a field (if 'this' is being mapped).
19075     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
19076     assert(CurDeclaration && "Null decl on map clause.");
19077     assert(
19078         CurDeclaration->isCanonicalDecl() &&
19079         "Expecting components to have associated only canonical declarations.");
19080 
19081     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
19082     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
19083 
19084     assert((VD || FD) && "Only variables or fields are expected here!");
19085     (void)FD;
19086 
19087     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
19088     // threadprivate variables cannot appear in a map clause.
19089     // OpenMP 4.5 [2.10.5, target update Construct]
19090     // threadprivate variables cannot appear in a from clause.
19091     if (VD && DSAS->isThreadPrivate(VD)) {
19092       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19093       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
19094           << getOpenMPClauseName(CKind);
19095       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
19096       continue;
19097     }
19098 
19099     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19100     //  A list item cannot appear in both a map clause and a data-sharing
19101     //  attribute clause on the same construct.
19102 
19103     // Check conflicts with other map clause expressions. We check the conflicts
19104     // with the current construct separately from the enclosing data
19105     // environment, because the restrictions are different. We only have to
19106     // check conflicts across regions for the map clauses.
19107     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19108                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
19109       break;
19110     if (CKind == OMPC_map &&
19111         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
19112         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19113                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
19114       break;
19115 
19116     // OpenMP 4.5 [2.10.5, target update Construct]
19117     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19118     //  If the type of a list item is a reference to a type T then the type will
19119     //  be considered to be T for all purposes of this clause.
19120     auto I = llvm::find_if(
19121         CurComponents,
19122         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19123           return MC.getAssociatedDeclaration();
19124         });
19125     assert(I != CurComponents.end() && "Null decl on map clause.");
19126     (void)I;
19127     QualType Type;
19128     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19129     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19130     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19131     if (ASE) {
19132       Type = ASE->getType().getNonReferenceType();
19133     } else if (OASE) {
19134       QualType BaseType =
19135           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19136       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19137         Type = ATy->getElementType();
19138       else
19139         Type = BaseType->getPointeeType();
19140       Type = Type.getNonReferenceType();
19141     } else if (OAShE) {
19142       Type = OAShE->getBase()->getType()->getPointeeType();
19143     } else {
19144       Type = VE->getType();
19145     }
19146 
19147     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19148     // A list item in a to or from clause must have a mappable type.
19149     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19150     //  A list item must have a mappable type.
19151     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19152                            DSAS, Type))
19153       continue;
19154 
19155     if (CKind == OMPC_map) {
19156       // target enter data
19157       // OpenMP [2.10.2, Restrictions, p. 99]
19158       // A map-type must be specified in all map clauses and must be either
19159       // to or alloc.
19160       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19161       if (DKind == OMPD_target_enter_data &&
19162           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19163         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19164             << (IsMapTypeImplicit ? 1 : 0)
19165             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19166             << getOpenMPDirectiveName(DKind);
19167         continue;
19168       }
19169 
19170       // target exit_data
19171       // OpenMP [2.10.3, Restrictions, p. 102]
19172       // A map-type must be specified in all map clauses and must be either
19173       // from, release, or delete.
19174       if (DKind == OMPD_target_exit_data &&
19175           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19176             MapType == OMPC_MAP_delete)) {
19177         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19178             << (IsMapTypeImplicit ? 1 : 0)
19179             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19180             << getOpenMPDirectiveName(DKind);
19181         continue;
19182       }
19183 
19184       // target, target data
19185       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19186       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19187       // A map-type in a map clause must be to, from, tofrom or alloc
19188       if ((DKind == OMPD_target_data ||
19189            isOpenMPTargetExecutionDirective(DKind)) &&
19190           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19191             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19192         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19193             << (IsMapTypeImplicit ? 1 : 0)
19194             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19195             << getOpenMPDirectiveName(DKind);
19196         continue;
19197       }
19198 
19199       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19200       // A list item cannot appear in both a map clause and a data-sharing
19201       // attribute clause on the same construct
19202       //
19203       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19204       // A list item cannot appear in both a map clause and a data-sharing
19205       // attribute clause on the same construct unless the construct is a
19206       // combined construct.
19207       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19208                   isOpenMPTargetExecutionDirective(DKind)) ||
19209                  DKind == OMPD_target)) {
19210         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19211         if (isOpenMPPrivate(DVar.CKind)) {
19212           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19213               << getOpenMPClauseName(DVar.CKind)
19214               << getOpenMPClauseName(OMPC_map)
19215               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19216           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19217           continue;
19218         }
19219       }
19220     }
19221 
19222     // Try to find the associated user-defined mapper.
19223     ExprResult ER = buildUserDefinedMapperRef(
19224         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19225         Type.getCanonicalType(), UnresolvedMapper);
19226     if (ER.isInvalid())
19227       continue;
19228     MVLI.UDMapperList.push_back(ER.get());
19229 
19230     // Save the current expression.
19231     MVLI.ProcessedVarList.push_back(RE);
19232 
19233     // Store the components in the stack so that they can be used to check
19234     // against other clauses later on.
19235     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19236                                           /*WhereFoundClauseKind=*/OMPC_map);
19237 
19238     // Save the components and declaration to create the clause. For purposes of
19239     // the clause creation, any component list that has has base 'this' uses
19240     // null as base declaration.
19241     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19242     MVLI.VarComponents.back().append(CurComponents.begin(),
19243                                      CurComponents.end());
19244     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19245                                                            : CurDeclaration);
19246   }
19247 }
19248 
19249 OMPClause *Sema::ActOnOpenMPMapClause(
19250     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19251     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19252     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19253     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19254     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19255     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
19256   OpenMPMapModifierKind Modifiers[] = {
19257       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19258       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
19259   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19260 
19261   // Process map-type-modifiers, flag errors for duplicate modifiers.
19262   unsigned Count = 0;
19263   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19264     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19265         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
19266       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19267       continue;
19268     }
19269     assert(Count < NumberOfOMPMapClauseModifiers &&
19270            "Modifiers exceed the allowed number of map type modifiers");
19271     Modifiers[Count] = MapTypeModifiers[I];
19272     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19273     ++Count;
19274   }
19275 
19276   MappableVarListInfo MVLI(VarList);
19277   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19278                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19279                               MapType, IsMapTypeImplicit);
19280 
19281   // We need to produce a map clause even if we don't have variables so that
19282   // other diagnostics related with non-existing map clauses are accurate.
19283   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19284                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19285                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19286                               MapperIdScopeSpec.getWithLocInContext(Context),
19287                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19288 }
19289 
19290 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19291                                                TypeResult ParsedType) {
19292   assert(ParsedType.isUsable());
19293 
19294   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19295   if (ReductionType.isNull())
19296     return QualType();
19297 
19298   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19299   // A type name in a declare reduction directive cannot be a function type, an
19300   // array type, a reference type, or a type qualified with const, volatile or
19301   // restrict.
19302   if (ReductionType.hasQualifiers()) {
19303     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19304     return QualType();
19305   }
19306 
19307   if (ReductionType->isFunctionType()) {
19308     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19309     return QualType();
19310   }
19311   if (ReductionType->isReferenceType()) {
19312     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19313     return QualType();
19314   }
19315   if (ReductionType->isArrayType()) {
19316     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
19317     return QualType();
19318   }
19319   return ReductionType;
19320 }
19321 
19322 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
19323     Scope *S, DeclContext *DC, DeclarationName Name,
19324     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
19325     AccessSpecifier AS, Decl *PrevDeclInScope) {
19326   SmallVector<Decl *, 8> Decls;
19327   Decls.reserve(ReductionTypes.size());
19328 
19329   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
19330                       forRedeclarationInCurContext());
19331   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
19332   // A reduction-identifier may not be re-declared in the current scope for the
19333   // same type or for a type that is compatible according to the base language
19334   // rules.
19335   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19336   OMPDeclareReductionDecl *PrevDRD = nullptr;
19337   bool InCompoundScope = true;
19338   if (S != nullptr) {
19339     // Find previous declaration with the same name not referenced in other
19340     // declarations.
19341     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19342     InCompoundScope =
19343         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19344     LookupName(Lookup, S);
19345     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19346                          /*AllowInlineNamespace=*/false);
19347     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
19348     LookupResult::Filter Filter = Lookup.makeFilter();
19349     while (Filter.hasNext()) {
19350       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
19351       if (InCompoundScope) {
19352         auto I = UsedAsPrevious.find(PrevDecl);
19353         if (I == UsedAsPrevious.end())
19354           UsedAsPrevious[PrevDecl] = false;
19355         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
19356           UsedAsPrevious[D] = true;
19357       }
19358       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19359           PrevDecl->getLocation();
19360     }
19361     Filter.done();
19362     if (InCompoundScope) {
19363       for (const auto &PrevData : UsedAsPrevious) {
19364         if (!PrevData.second) {
19365           PrevDRD = PrevData.first;
19366           break;
19367         }
19368       }
19369     }
19370   } else if (PrevDeclInScope != nullptr) {
19371     auto *PrevDRDInScope = PrevDRD =
19372         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
19373     do {
19374       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
19375           PrevDRDInScope->getLocation();
19376       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
19377     } while (PrevDRDInScope != nullptr);
19378   }
19379   for (const auto &TyData : ReductionTypes) {
19380     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
19381     bool Invalid = false;
19382     if (I != PreviousRedeclTypes.end()) {
19383       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
19384           << TyData.first;
19385       Diag(I->second, diag::note_previous_definition);
19386       Invalid = true;
19387     }
19388     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
19389     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
19390                                                 Name, TyData.first, PrevDRD);
19391     DC->addDecl(DRD);
19392     DRD->setAccess(AS);
19393     Decls.push_back(DRD);
19394     if (Invalid)
19395       DRD->setInvalidDecl();
19396     else
19397       PrevDRD = DRD;
19398   }
19399 
19400   return DeclGroupPtrTy::make(
19401       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
19402 }
19403 
19404 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
19405   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19406 
19407   // Enter new function scope.
19408   PushFunctionScope();
19409   setFunctionHasBranchProtectedScope();
19410   getCurFunction()->setHasOMPDeclareReductionCombiner();
19411 
19412   if (S != nullptr)
19413     PushDeclContext(S, DRD);
19414   else
19415     CurContext = DRD;
19416 
19417   PushExpressionEvaluationContext(
19418       ExpressionEvaluationContext::PotentiallyEvaluated);
19419 
19420   QualType ReductionType = DRD->getType();
19421   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
19422   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
19423   // uses semantics of argument handles by value, but it should be passed by
19424   // reference. C lang does not support references, so pass all parameters as
19425   // pointers.
19426   // Create 'T omp_in;' variable.
19427   VarDecl *OmpInParm =
19428       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
19429   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
19430   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
19431   // uses semantics of argument handles by value, but it should be passed by
19432   // reference. C lang does not support references, so pass all parameters as
19433   // pointers.
19434   // Create 'T omp_out;' variable.
19435   VarDecl *OmpOutParm =
19436       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
19437   if (S != nullptr) {
19438     PushOnScopeChains(OmpInParm, S);
19439     PushOnScopeChains(OmpOutParm, S);
19440   } else {
19441     DRD->addDecl(OmpInParm);
19442     DRD->addDecl(OmpOutParm);
19443   }
19444   Expr *InE =
19445       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
19446   Expr *OutE =
19447       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
19448   DRD->setCombinerData(InE, OutE);
19449 }
19450 
19451 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
19452   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19453   DiscardCleanupsInEvaluationContext();
19454   PopExpressionEvaluationContext();
19455 
19456   PopDeclContext();
19457   PopFunctionScopeInfo();
19458 
19459   if (Combiner != nullptr)
19460     DRD->setCombiner(Combiner);
19461   else
19462     DRD->setInvalidDecl();
19463 }
19464 
19465 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
19466   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19467 
19468   // Enter new function scope.
19469   PushFunctionScope();
19470   setFunctionHasBranchProtectedScope();
19471 
19472   if (S != nullptr)
19473     PushDeclContext(S, DRD);
19474   else
19475     CurContext = DRD;
19476 
19477   PushExpressionEvaluationContext(
19478       ExpressionEvaluationContext::PotentiallyEvaluated);
19479 
19480   QualType ReductionType = DRD->getType();
19481   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
19482   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
19483   // uses semantics of argument handles by value, but it should be passed by
19484   // reference. C lang does not support references, so pass all parameters as
19485   // pointers.
19486   // Create 'T omp_priv;' variable.
19487   VarDecl *OmpPrivParm =
19488       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
19489   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
19490   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
19491   // uses semantics of argument handles by value, but it should be passed by
19492   // reference. C lang does not support references, so pass all parameters as
19493   // pointers.
19494   // Create 'T omp_orig;' variable.
19495   VarDecl *OmpOrigParm =
19496       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
19497   if (S != nullptr) {
19498     PushOnScopeChains(OmpPrivParm, S);
19499     PushOnScopeChains(OmpOrigParm, S);
19500   } else {
19501     DRD->addDecl(OmpPrivParm);
19502     DRD->addDecl(OmpOrigParm);
19503   }
19504   Expr *OrigE =
19505       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
19506   Expr *PrivE =
19507       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
19508   DRD->setInitializerData(OrigE, PrivE);
19509   return OmpPrivParm;
19510 }
19511 
19512 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
19513                                                      VarDecl *OmpPrivParm) {
19514   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19515   DiscardCleanupsInEvaluationContext();
19516   PopExpressionEvaluationContext();
19517 
19518   PopDeclContext();
19519   PopFunctionScopeInfo();
19520 
19521   if (Initializer != nullptr) {
19522     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
19523   } else if (OmpPrivParm->hasInit()) {
19524     DRD->setInitializer(OmpPrivParm->getInit(),
19525                         OmpPrivParm->isDirectInit()
19526                             ? OMPDeclareReductionDecl::DirectInit
19527                             : OMPDeclareReductionDecl::CopyInit);
19528   } else {
19529     DRD->setInvalidDecl();
19530   }
19531 }
19532 
19533 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
19534     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
19535   for (Decl *D : DeclReductions.get()) {
19536     if (IsValid) {
19537       if (S)
19538         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
19539                           /*AddToContext=*/false);
19540     } else {
19541       D->setInvalidDecl();
19542     }
19543   }
19544   return DeclReductions;
19545 }
19546 
19547 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
19548   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
19549   QualType T = TInfo->getType();
19550   if (D.isInvalidType())
19551     return true;
19552 
19553   if (getLangOpts().CPlusPlus) {
19554     // Check that there are no default arguments (C++ only).
19555     CheckExtraCXXDefaultArguments(D);
19556   }
19557 
19558   return CreateParsedType(T, TInfo);
19559 }
19560 
19561 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
19562                                             TypeResult ParsedType) {
19563   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
19564 
19565   QualType MapperType = GetTypeFromParser(ParsedType.get());
19566   assert(!MapperType.isNull() && "Expect valid mapper type");
19567 
19568   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19569   //  The type must be of struct, union or class type in C and C++
19570   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
19571     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
19572     return QualType();
19573   }
19574   return MapperType;
19575 }
19576 
19577 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
19578     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
19579     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
19580     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
19581   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
19582                       forRedeclarationInCurContext());
19583   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19584   //  A mapper-identifier may not be redeclared in the current scope for the
19585   //  same type or for a type that is compatible according to the base language
19586   //  rules.
19587   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19588   OMPDeclareMapperDecl *PrevDMD = nullptr;
19589   bool InCompoundScope = true;
19590   if (S != nullptr) {
19591     // Find previous declaration with the same name not referenced in other
19592     // declarations.
19593     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19594     InCompoundScope =
19595         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19596     LookupName(Lookup, S);
19597     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19598                          /*AllowInlineNamespace=*/false);
19599     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
19600     LookupResult::Filter Filter = Lookup.makeFilter();
19601     while (Filter.hasNext()) {
19602       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
19603       if (InCompoundScope) {
19604         auto I = UsedAsPrevious.find(PrevDecl);
19605         if (I == UsedAsPrevious.end())
19606           UsedAsPrevious[PrevDecl] = false;
19607         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
19608           UsedAsPrevious[D] = true;
19609       }
19610       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19611           PrevDecl->getLocation();
19612     }
19613     Filter.done();
19614     if (InCompoundScope) {
19615       for (const auto &PrevData : UsedAsPrevious) {
19616         if (!PrevData.second) {
19617           PrevDMD = PrevData.first;
19618           break;
19619         }
19620       }
19621     }
19622   } else if (PrevDeclInScope) {
19623     auto *PrevDMDInScope = PrevDMD =
19624         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
19625     do {
19626       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
19627           PrevDMDInScope->getLocation();
19628       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
19629     } while (PrevDMDInScope != nullptr);
19630   }
19631   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
19632   bool Invalid = false;
19633   if (I != PreviousRedeclTypes.end()) {
19634     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
19635         << MapperType << Name;
19636     Diag(I->second, diag::note_previous_definition);
19637     Invalid = true;
19638   }
19639   // Build expressions for implicit maps of data members with 'default'
19640   // mappers.
19641   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
19642                                                   Clauses.end());
19643   if (LangOpts.OpenMP >= 50)
19644     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
19645   auto *DMD =
19646       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
19647                                    ClausesWithImplicit, PrevDMD);
19648   if (S)
19649     PushOnScopeChains(DMD, S);
19650   else
19651     DC->addDecl(DMD);
19652   DMD->setAccess(AS);
19653   if (Invalid)
19654     DMD->setInvalidDecl();
19655 
19656   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
19657   VD->setDeclContext(DMD);
19658   VD->setLexicalDeclContext(DMD);
19659   DMD->addDecl(VD);
19660   DMD->setMapperVarRef(MapperVarRef);
19661 
19662   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
19663 }
19664 
19665 ExprResult
19666 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
19667                                                SourceLocation StartLoc,
19668                                                DeclarationName VN) {
19669   TypeSourceInfo *TInfo =
19670       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
19671   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
19672                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
19673                              MapperType, TInfo, SC_None);
19674   if (S)
19675     PushOnScopeChains(VD, S, /*AddToContext=*/false);
19676   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
19677   DSAStack->addDeclareMapperVarRef(E);
19678   return E;
19679 }
19680 
19681 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
19682   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
19683   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
19684   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
19685     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
19686       return true;
19687     if (VD->isUsableInConstantExpressions(Context))
19688       return true;
19689     return false;
19690   }
19691   return true;
19692 }
19693 
19694 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
19695   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
19696   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
19697 }
19698 
19699 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
19700                                            SourceLocation StartLoc,
19701                                            SourceLocation LParenLoc,
19702                                            SourceLocation EndLoc) {
19703   Expr *ValExpr = NumTeams;
19704   Stmt *HelperValStmt = nullptr;
19705 
19706   // OpenMP [teams Constrcut, Restrictions]
19707   // The num_teams expression must evaluate to a positive integer value.
19708   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
19709                                  /*StrictlyPositive=*/true))
19710     return nullptr;
19711 
19712   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19713   OpenMPDirectiveKind CaptureRegion =
19714       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
19715   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19716     ValExpr = MakeFullExpr(ValExpr).get();
19717     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19718     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19719     HelperValStmt = buildPreInits(Context, Captures);
19720   }
19721 
19722   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
19723                                          StartLoc, LParenLoc, EndLoc);
19724 }
19725 
19726 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
19727                                               SourceLocation StartLoc,
19728                                               SourceLocation LParenLoc,
19729                                               SourceLocation EndLoc) {
19730   Expr *ValExpr = ThreadLimit;
19731   Stmt *HelperValStmt = nullptr;
19732 
19733   // OpenMP [teams Constrcut, Restrictions]
19734   // The thread_limit expression must evaluate to a positive integer value.
19735   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
19736                                  /*StrictlyPositive=*/true))
19737     return nullptr;
19738 
19739   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19740   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
19741       DKind, OMPC_thread_limit, LangOpts.OpenMP);
19742   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19743     ValExpr = MakeFullExpr(ValExpr).get();
19744     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19745     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19746     HelperValStmt = buildPreInits(Context, Captures);
19747   }
19748 
19749   return new (Context) OMPThreadLimitClause(
19750       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
19751 }
19752 
19753 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
19754                                            SourceLocation StartLoc,
19755                                            SourceLocation LParenLoc,
19756                                            SourceLocation EndLoc) {
19757   Expr *ValExpr = Priority;
19758   Stmt *HelperValStmt = nullptr;
19759   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19760 
19761   // OpenMP [2.9.1, task Constrcut]
19762   // The priority-value is a non-negative numerical scalar expression.
19763   if (!isNonNegativeIntegerValue(
19764           ValExpr, *this, OMPC_priority,
19765           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
19766           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19767     return nullptr;
19768 
19769   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
19770                                          StartLoc, LParenLoc, EndLoc);
19771 }
19772 
19773 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
19774                                             SourceLocation StartLoc,
19775                                             SourceLocation LParenLoc,
19776                                             SourceLocation EndLoc) {
19777   Expr *ValExpr = Grainsize;
19778   Stmt *HelperValStmt = nullptr;
19779   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19780 
19781   // OpenMP [2.9.2, taskloop Constrcut]
19782   // The parameter of the grainsize clause must be a positive integer
19783   // expression.
19784   if (!isNonNegativeIntegerValue(
19785           ValExpr, *this, OMPC_grainsize,
19786           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
19787           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19788     return nullptr;
19789 
19790   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
19791                                           StartLoc, LParenLoc, EndLoc);
19792 }
19793 
19794 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
19795                                            SourceLocation StartLoc,
19796                                            SourceLocation LParenLoc,
19797                                            SourceLocation EndLoc) {
19798   Expr *ValExpr = NumTasks;
19799   Stmt *HelperValStmt = nullptr;
19800   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19801 
19802   // OpenMP [2.9.2, taskloop Constrcut]
19803   // The parameter of the num_tasks clause must be a positive integer
19804   // expression.
19805   if (!isNonNegativeIntegerValue(
19806           ValExpr, *this, OMPC_num_tasks,
19807           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
19808           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19809     return nullptr;
19810 
19811   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
19812                                          StartLoc, LParenLoc, EndLoc);
19813 }
19814 
19815 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
19816                                        SourceLocation LParenLoc,
19817                                        SourceLocation EndLoc) {
19818   // OpenMP [2.13.2, critical construct, Description]
19819   // ... where hint-expression is an integer constant expression that evaluates
19820   // to a valid lock hint.
19821   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
19822   if (HintExpr.isInvalid())
19823     return nullptr;
19824   return new (Context)
19825       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
19826 }
19827 
19828 /// Tries to find omp_event_handle_t type.
19829 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
19830                                 DSAStackTy *Stack) {
19831   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
19832   if (!OMPEventHandleT.isNull())
19833     return true;
19834   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
19835   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
19836   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19837     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
19838     return false;
19839   }
19840   Stack->setOMPEventHandleT(PT.get());
19841   return true;
19842 }
19843 
19844 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
19845                                          SourceLocation LParenLoc,
19846                                          SourceLocation EndLoc) {
19847   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
19848       !Evt->isInstantiationDependent() &&
19849       !Evt->containsUnexpandedParameterPack()) {
19850     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
19851       return nullptr;
19852     // OpenMP 5.0, 2.10.1 task Construct.
19853     // event-handle is a variable of the omp_event_handle_t type.
19854     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
19855     if (!Ref) {
19856       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19857           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
19858       return nullptr;
19859     }
19860     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
19861     if (!VD) {
19862       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19863           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
19864       return nullptr;
19865     }
19866     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
19867                                         VD->getType()) ||
19868         VD->getType().isConstant(Context)) {
19869       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19870           << "omp_event_handle_t" << 1 << VD->getType()
19871           << Evt->getSourceRange();
19872       return nullptr;
19873     }
19874     // OpenMP 5.0, 2.10.1 task Construct
19875     // [detach clause]... The event-handle will be considered as if it was
19876     // specified on a firstprivate clause.
19877     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
19878     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
19879         DVar.RefExpr) {
19880       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
19881           << getOpenMPClauseName(DVar.CKind)
19882           << getOpenMPClauseName(OMPC_firstprivate);
19883       reportOriginalDsa(*this, DSAStack, VD, DVar);
19884       return nullptr;
19885     }
19886   }
19887 
19888   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
19889 }
19890 
19891 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
19892     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
19893     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
19894     SourceLocation EndLoc) {
19895   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
19896     std::string Values;
19897     Values += "'";
19898     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
19899     Values += "'";
19900     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19901         << Values << getOpenMPClauseName(OMPC_dist_schedule);
19902     return nullptr;
19903   }
19904   Expr *ValExpr = ChunkSize;
19905   Stmt *HelperValStmt = nullptr;
19906   if (ChunkSize) {
19907     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
19908         !ChunkSize->isInstantiationDependent() &&
19909         !ChunkSize->containsUnexpandedParameterPack()) {
19910       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
19911       ExprResult Val =
19912           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
19913       if (Val.isInvalid())
19914         return nullptr;
19915 
19916       ValExpr = Val.get();
19917 
19918       // OpenMP [2.7.1, Restrictions]
19919       //  chunk_size must be a loop invariant integer expression with a positive
19920       //  value.
19921       if (Optional<llvm::APSInt> Result =
19922               ValExpr->getIntegerConstantExpr(Context)) {
19923         if (Result->isSigned() && !Result->isStrictlyPositive()) {
19924           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
19925               << "dist_schedule" << ChunkSize->getSourceRange();
19926           return nullptr;
19927         }
19928       } else if (getOpenMPCaptureRegionForClause(
19929                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
19930                      LangOpts.OpenMP) != OMPD_unknown &&
19931                  !CurContext->isDependentContext()) {
19932         ValExpr = MakeFullExpr(ValExpr).get();
19933         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19934         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19935         HelperValStmt = buildPreInits(Context, Captures);
19936       }
19937     }
19938   }
19939 
19940   return new (Context)
19941       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
19942                             Kind, ValExpr, HelperValStmt);
19943 }
19944 
19945 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
19946     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
19947     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
19948     SourceLocation KindLoc, SourceLocation EndLoc) {
19949   if (getLangOpts().OpenMP < 50) {
19950     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
19951         Kind != OMPC_DEFAULTMAP_scalar) {
19952       std::string Value;
19953       SourceLocation Loc;
19954       Value += "'";
19955       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
19956         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
19957                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
19958         Loc = MLoc;
19959       } else {
19960         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
19961                                                OMPC_DEFAULTMAP_scalar);
19962         Loc = KindLoc;
19963       }
19964       Value += "'";
19965       Diag(Loc, diag::err_omp_unexpected_clause_value)
19966           << Value << getOpenMPClauseName(OMPC_defaultmap);
19967       return nullptr;
19968     }
19969   } else {
19970     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
19971     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
19972                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
19973     if (!isDefaultmapKind || !isDefaultmapModifier) {
19974       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
19975       if (LangOpts.OpenMP == 50) {
19976         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
19977                                   "'firstprivate', 'none', 'default'";
19978         if (!isDefaultmapKind && isDefaultmapModifier) {
19979           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19980               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19981         } else if (isDefaultmapKind && !isDefaultmapModifier) {
19982           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19983               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19984         } else {
19985           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19986               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19987           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19988               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19989         }
19990       } else {
19991         StringRef ModifierValue =
19992             "'alloc', 'from', 'to', 'tofrom', "
19993             "'firstprivate', 'none', 'default', 'present'";
19994         if (!isDefaultmapKind && isDefaultmapModifier) {
19995           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19996               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19997         } else if (isDefaultmapKind && !isDefaultmapModifier) {
19998           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19999               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20000         } else {
20001           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20002               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20003           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20004               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20005         }
20006       }
20007       return nullptr;
20008     }
20009 
20010     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
20011     //  At most one defaultmap clause for each category can appear on the
20012     //  directive.
20013     if (DSAStack->checkDefaultmapCategory(Kind)) {
20014       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
20015       return nullptr;
20016     }
20017   }
20018   if (Kind == OMPC_DEFAULTMAP_unknown) {
20019     // Variable category is not specified - mark all categories.
20020     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
20021     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
20022     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
20023   } else {
20024     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
20025   }
20026 
20027   return new (Context)
20028       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
20029 }
20030 
20031 bool Sema::ActOnStartOpenMPDeclareTargetContext(
20032     DeclareTargetContextInfo &DTCI) {
20033   DeclContext *CurLexicalContext = getCurLexicalContext();
20034   if (!CurLexicalContext->isFileContext() &&
20035       !CurLexicalContext->isExternCContext() &&
20036       !CurLexicalContext->isExternCXXContext() &&
20037       !isa<CXXRecordDecl>(CurLexicalContext) &&
20038       !isa<ClassTemplateDecl>(CurLexicalContext) &&
20039       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
20040       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
20041     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
20042     return false;
20043   }
20044   DeclareTargetNesting.push_back(DTCI);
20045   return true;
20046 }
20047 
20048 const Sema::DeclareTargetContextInfo
20049 Sema::ActOnOpenMPEndDeclareTargetDirective() {
20050   assert(!DeclareTargetNesting.empty() &&
20051          "check isInOpenMPDeclareTargetContext() first!");
20052   return DeclareTargetNesting.pop_back_val();
20053 }
20054 
20055 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
20056     DeclareTargetContextInfo &DTCI) {
20057   for (auto &It : DTCI.ExplicitlyMapped)
20058     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT,
20059                                  DTCI.DT);
20060 }
20061 
20062 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
20063                                                CXXScopeSpec &ScopeSpec,
20064                                                const DeclarationNameInfo &Id) {
20065   LookupResult Lookup(*this, Id, LookupOrdinaryName);
20066   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
20067 
20068   if (Lookup.isAmbiguous())
20069     return nullptr;
20070   Lookup.suppressDiagnostics();
20071 
20072   if (!Lookup.isSingleResult()) {
20073     VarOrFuncDeclFilterCCC CCC(*this);
20074     if (TypoCorrection Corrected =
20075             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
20076                         CTK_ErrorRecovery)) {
20077       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
20078                                   << Id.getName());
20079       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
20080       return nullptr;
20081     }
20082 
20083     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
20084     return nullptr;
20085   }
20086 
20087   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
20088   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
20089       !isa<FunctionTemplateDecl>(ND)) {
20090     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
20091     return nullptr;
20092   }
20093   return ND;
20094 }
20095 
20096 void Sema::ActOnOpenMPDeclareTargetName(
20097     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
20098     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
20099   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
20100           isa<FunctionTemplateDecl>(ND)) &&
20101          "Expected variable, function or function template.");
20102 
20103   // Diagnose marking after use as it may lead to incorrect diagnosis and
20104   // codegen.
20105   if (LangOpts.OpenMP >= 50 &&
20106       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
20107     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
20108 
20109   // Explicit declare target lists have precedence.
20110   const unsigned Level = -1;
20111 
20112   auto *VD = cast<ValueDecl>(ND);
20113   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20114       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20115   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT &&
20116       ActiveAttr.getValue()->getLevel() == Level) {
20117     Diag(Loc, diag::err_omp_device_type_mismatch)
20118         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
20119         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
20120                ActiveAttr.getValue()->getDevType());
20121     return;
20122   }
20123   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
20124       ActiveAttr.getValue()->getLevel() == Level) {
20125     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20126     return;
20127   }
20128 
20129   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
20130     return;
20131 
20132   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level,
20133                                                      SourceRange(Loc, Loc));
20134   ND->addAttr(A);
20135   if (ASTMutationListener *ML = Context.getASTMutationListener())
20136     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
20137   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20138 }
20139 
20140 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20141                                      Sema &SemaRef, Decl *D) {
20142   if (!D || !isa<VarDecl>(D))
20143     return;
20144   auto *VD = cast<VarDecl>(D);
20145   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20146       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20147   if (SemaRef.LangOpts.OpenMP >= 50 &&
20148       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20149        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20150       VD->hasGlobalStorage()) {
20151     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20152       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20153       // If a lambda declaration and definition appears between a
20154       // declare target directive and the matching end declare target
20155       // directive, all variables that are captured by the lambda
20156       // expression must also appear in a to clause.
20157       SemaRef.Diag(VD->getLocation(),
20158                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20159       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20160           << VD << 0 << SR;
20161       return;
20162     }
20163   }
20164   if (MapTy.hasValue())
20165     return;
20166   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20167   SemaRef.Diag(SL, diag::note_used_here) << SR;
20168 }
20169 
20170 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20171                                    Sema &SemaRef, DSAStackTy *Stack,
20172                                    ValueDecl *VD) {
20173   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20174          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20175                            /*FullCheck=*/false);
20176 }
20177 
20178 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20179                                             SourceLocation IdLoc) {
20180   if (!D || D->isInvalidDecl())
20181     return;
20182   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20183   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20184   if (auto *VD = dyn_cast<VarDecl>(D)) {
20185     // Only global variables can be marked as declare target.
20186     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20187         !VD->isStaticDataMember())
20188       return;
20189     // 2.10.6: threadprivate variable cannot appear in a declare target
20190     // directive.
20191     if (DSAStack->isThreadPrivate(VD)) {
20192       Diag(SL, diag::err_omp_threadprivate_in_target);
20193       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20194       return;
20195     }
20196   }
20197   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20198     D = FTD->getTemplatedDecl();
20199   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20200     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20201         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20202     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20203       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20204       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20205       return;
20206     }
20207   }
20208   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20209     // Problem if any with var declared with incomplete type will be reported
20210     // as normal, so no need to check it here.
20211     if ((E || !VD->getType()->isIncompleteType()) &&
20212         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20213       return;
20214     if (!E && isInOpenMPDeclareTargetContext()) {
20215       // Checking declaration inside declare target region.
20216       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20217           isa<FunctionTemplateDecl>(D)) {
20218         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20219             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20220         unsigned Level = DeclareTargetNesting.size();
20221         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
20222           return;
20223         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
20224         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20225             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level,
20226             SourceRange(DTCI.Loc, DTCI.Loc));
20227         D->addAttr(A);
20228         if (ASTMutationListener *ML = Context.getASTMutationListener())
20229           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20230       }
20231       return;
20232     }
20233   }
20234   if (!E)
20235     return;
20236   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20237 }
20238 
20239 OMPClause *Sema::ActOnOpenMPToClause(
20240     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20241     ArrayRef<SourceLocation> MotionModifiersLoc,
20242     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20243     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20244     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20245   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20246                                           OMPC_MOTION_MODIFIER_unknown};
20247   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20248 
20249   // Process motion-modifiers, flag errors for duplicate modifiers.
20250   unsigned Count = 0;
20251   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20252     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20253         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20254       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20255       continue;
20256     }
20257     assert(Count < NumberOfOMPMotionModifiers &&
20258            "Modifiers exceed the allowed number of motion modifiers");
20259     Modifiers[Count] = MotionModifiers[I];
20260     ModifiersLoc[Count] = MotionModifiersLoc[I];
20261     ++Count;
20262   }
20263 
20264   MappableVarListInfo MVLI(VarList);
20265   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20266                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20267   if (MVLI.ProcessedVarList.empty())
20268     return nullptr;
20269 
20270   return OMPToClause::Create(
20271       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20272       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20273       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20274 }
20275 
20276 OMPClause *Sema::ActOnOpenMPFromClause(
20277     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20278     ArrayRef<SourceLocation> MotionModifiersLoc,
20279     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20280     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20281     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20282   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20283                                           OMPC_MOTION_MODIFIER_unknown};
20284   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20285 
20286   // Process motion-modifiers, flag errors for duplicate modifiers.
20287   unsigned Count = 0;
20288   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20289     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20290         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20291       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20292       continue;
20293     }
20294     assert(Count < NumberOfOMPMotionModifiers &&
20295            "Modifiers exceed the allowed number of motion modifiers");
20296     Modifiers[Count] = MotionModifiers[I];
20297     ModifiersLoc[Count] = MotionModifiersLoc[I];
20298     ++Count;
20299   }
20300 
20301   MappableVarListInfo MVLI(VarList);
20302   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20303                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20304   if (MVLI.ProcessedVarList.empty())
20305     return nullptr;
20306 
20307   return OMPFromClause::Create(
20308       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20309       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20310       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20311 }
20312 
20313 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20314                                                const OMPVarListLocTy &Locs) {
20315   MappableVarListInfo MVLI(VarList);
20316   SmallVector<Expr *, 8> PrivateCopies;
20317   SmallVector<Expr *, 8> Inits;
20318 
20319   for (Expr *RefExpr : VarList) {
20320     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
20321     SourceLocation ELoc;
20322     SourceRange ERange;
20323     Expr *SimpleRefExpr = RefExpr;
20324     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20325     if (Res.second) {
20326       // It will be analyzed later.
20327       MVLI.ProcessedVarList.push_back(RefExpr);
20328       PrivateCopies.push_back(nullptr);
20329       Inits.push_back(nullptr);
20330     }
20331     ValueDecl *D = Res.first;
20332     if (!D)
20333       continue;
20334 
20335     QualType Type = D->getType();
20336     Type = Type.getNonReferenceType().getUnqualifiedType();
20337 
20338     auto *VD = dyn_cast<VarDecl>(D);
20339 
20340     // Item should be a pointer or reference to pointer.
20341     if (!Type->isPointerType()) {
20342       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
20343           << 0 << RefExpr->getSourceRange();
20344       continue;
20345     }
20346 
20347     // Build the private variable and the expression that refers to it.
20348     auto VDPrivate =
20349         buildVarDecl(*this, ELoc, Type, D->getName(),
20350                      D->hasAttrs() ? &D->getAttrs() : nullptr,
20351                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
20352     if (VDPrivate->isInvalidDecl())
20353       continue;
20354 
20355     CurContext->addDecl(VDPrivate);
20356     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
20357         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
20358 
20359     // Add temporary variable to initialize the private copy of the pointer.
20360     VarDecl *VDInit =
20361         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
20362     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
20363         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
20364     AddInitializerToDecl(VDPrivate,
20365                          DefaultLvalueConversion(VDInitRefExpr).get(),
20366                          /*DirectInit=*/false);
20367 
20368     // If required, build a capture to implement the privatization initialized
20369     // with the current list item value.
20370     DeclRefExpr *Ref = nullptr;
20371     if (!VD)
20372       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20373     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20374     PrivateCopies.push_back(VDPrivateRefExpr);
20375     Inits.push_back(VDInitRefExpr);
20376 
20377     // We need to add a data sharing attribute for this variable to make sure it
20378     // is correctly captured. A variable that shows up in a use_device_ptr has
20379     // similar properties of a first private variable.
20380     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20381 
20382     // Create a mappable component for the list item. List items in this clause
20383     // only need a component.
20384     MVLI.VarBaseDeclarations.push_back(D);
20385     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20386     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
20387                                            /*IsNonContiguous=*/false);
20388   }
20389 
20390   if (MVLI.ProcessedVarList.empty())
20391     return nullptr;
20392 
20393   return OMPUseDevicePtrClause::Create(
20394       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
20395       MVLI.VarBaseDeclarations, MVLI.VarComponents);
20396 }
20397 
20398 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
20399                                                 const OMPVarListLocTy &Locs) {
20400   MappableVarListInfo MVLI(VarList);
20401 
20402   for (Expr *RefExpr : VarList) {
20403     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
20404     SourceLocation ELoc;
20405     SourceRange ERange;
20406     Expr *SimpleRefExpr = RefExpr;
20407     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20408                               /*AllowArraySection=*/true);
20409     if (Res.second) {
20410       // It will be analyzed later.
20411       MVLI.ProcessedVarList.push_back(RefExpr);
20412     }
20413     ValueDecl *D = Res.first;
20414     if (!D)
20415       continue;
20416     auto *VD = dyn_cast<VarDecl>(D);
20417 
20418     // If required, build a capture to implement the privatization initialized
20419     // with the current list item value.
20420     DeclRefExpr *Ref = nullptr;
20421     if (!VD)
20422       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20423     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20424 
20425     // We need to add a data sharing attribute for this variable to make sure it
20426     // is correctly captured. A variable that shows up in a use_device_addr has
20427     // similar properties of a first private variable.
20428     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20429 
20430     // Create a mappable component for the list item. List items in this clause
20431     // only need a component.
20432     MVLI.VarBaseDeclarations.push_back(D);
20433     MVLI.VarComponents.emplace_back();
20434     Expr *Component = SimpleRefExpr;
20435     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
20436                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
20437       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
20438     MVLI.VarComponents.back().emplace_back(Component, D,
20439                                            /*IsNonContiguous=*/false);
20440   }
20441 
20442   if (MVLI.ProcessedVarList.empty())
20443     return nullptr;
20444 
20445   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20446                                         MVLI.VarBaseDeclarations,
20447                                         MVLI.VarComponents);
20448 }
20449 
20450 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
20451                                               const OMPVarListLocTy &Locs) {
20452   MappableVarListInfo MVLI(VarList);
20453   for (Expr *RefExpr : VarList) {
20454     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
20455     SourceLocation ELoc;
20456     SourceRange ERange;
20457     Expr *SimpleRefExpr = RefExpr;
20458     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20459     if (Res.second) {
20460       // It will be analyzed later.
20461       MVLI.ProcessedVarList.push_back(RefExpr);
20462     }
20463     ValueDecl *D = Res.first;
20464     if (!D)
20465       continue;
20466 
20467     QualType Type = D->getType();
20468     // item should be a pointer or array or reference to pointer or array
20469     if (!Type.getNonReferenceType()->isPointerType() &&
20470         !Type.getNonReferenceType()->isArrayType()) {
20471       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
20472           << 0 << RefExpr->getSourceRange();
20473       continue;
20474     }
20475 
20476     // Check if the declaration in the clause does not show up in any data
20477     // sharing attribute.
20478     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
20479     if (isOpenMPPrivate(DVar.CKind)) {
20480       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
20481           << getOpenMPClauseName(DVar.CKind)
20482           << getOpenMPClauseName(OMPC_is_device_ptr)
20483           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
20484       reportOriginalDsa(*this, DSAStack, D, DVar);
20485       continue;
20486     }
20487 
20488     const Expr *ConflictExpr;
20489     if (DSAStack->checkMappableExprComponentListsForDecl(
20490             D, /*CurrentRegionOnly=*/true,
20491             [&ConflictExpr](
20492                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
20493                 OpenMPClauseKind) -> bool {
20494               ConflictExpr = R.front().getAssociatedExpression();
20495               return true;
20496             })) {
20497       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
20498       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
20499           << ConflictExpr->getSourceRange();
20500       continue;
20501     }
20502 
20503     // Store the components in the stack so that they can be used to check
20504     // against other clauses later on.
20505     OMPClauseMappableExprCommon::MappableComponent MC(
20506         SimpleRefExpr, D, /*IsNonContiguous=*/false);
20507     DSAStack->addMappableExpressionComponents(
20508         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
20509 
20510     // Record the expression we've just processed.
20511     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
20512 
20513     // Create a mappable component for the list item. List items in this clause
20514     // only need a component. We use a null declaration to signal fields in
20515     // 'this'.
20516     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
20517             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
20518            "Unexpected device pointer expression!");
20519     MVLI.VarBaseDeclarations.push_back(
20520         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
20521     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20522     MVLI.VarComponents.back().push_back(MC);
20523   }
20524 
20525   if (MVLI.ProcessedVarList.empty())
20526     return nullptr;
20527 
20528   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20529                                       MVLI.VarBaseDeclarations,
20530                                       MVLI.VarComponents);
20531 }
20532 
20533 OMPClause *Sema::ActOnOpenMPAllocateClause(
20534     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
20535     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
20536   if (Allocator) {
20537     // OpenMP [2.11.4 allocate Clause, Description]
20538     // allocator is an expression of omp_allocator_handle_t type.
20539     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
20540       return nullptr;
20541 
20542     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
20543     if (AllocatorRes.isInvalid())
20544       return nullptr;
20545     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
20546                                              DSAStack->getOMPAllocatorHandleT(),
20547                                              Sema::AA_Initializing,
20548                                              /*AllowExplicit=*/true);
20549     if (AllocatorRes.isInvalid())
20550       return nullptr;
20551     Allocator = AllocatorRes.get();
20552   } else {
20553     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
20554     // allocate clauses that appear on a target construct or on constructs in a
20555     // target region must specify an allocator expression unless a requires
20556     // directive with the dynamic_allocators clause is present in the same
20557     // compilation unit.
20558     if (LangOpts.OpenMPIsDevice &&
20559         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
20560       targetDiag(StartLoc, diag::err_expected_allocator_expression);
20561   }
20562   // Analyze and build list of variables.
20563   SmallVector<Expr *, 8> Vars;
20564   for (Expr *RefExpr : VarList) {
20565     assert(RefExpr && "NULL expr in OpenMP private clause.");
20566     SourceLocation ELoc;
20567     SourceRange ERange;
20568     Expr *SimpleRefExpr = RefExpr;
20569     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20570     if (Res.second) {
20571       // It will be analyzed later.
20572       Vars.push_back(RefExpr);
20573     }
20574     ValueDecl *D = Res.first;
20575     if (!D)
20576       continue;
20577 
20578     auto *VD = dyn_cast<VarDecl>(D);
20579     DeclRefExpr *Ref = nullptr;
20580     if (!VD && !CurContext->isDependentContext())
20581       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
20582     Vars.push_back((VD || CurContext->isDependentContext())
20583                        ? RefExpr->IgnoreParens()
20584                        : Ref);
20585   }
20586 
20587   if (Vars.empty())
20588     return nullptr;
20589 
20590   if (Allocator)
20591     DSAStack->addInnerAllocatorExpr(Allocator);
20592   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
20593                                    ColonLoc, EndLoc, Vars);
20594 }
20595 
20596 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
20597                                               SourceLocation StartLoc,
20598                                               SourceLocation LParenLoc,
20599                                               SourceLocation EndLoc) {
20600   SmallVector<Expr *, 8> Vars;
20601   for (Expr *RefExpr : VarList) {
20602     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20603     SourceLocation ELoc;
20604     SourceRange ERange;
20605     Expr *SimpleRefExpr = RefExpr;
20606     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20607     if (Res.second)
20608       // It will be analyzed later.
20609       Vars.push_back(RefExpr);
20610     ValueDecl *D = Res.first;
20611     if (!D)
20612       continue;
20613 
20614     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
20615     // A list-item cannot appear in more than one nontemporal clause.
20616     if (const Expr *PrevRef =
20617             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
20618       Diag(ELoc, diag::err_omp_used_in_clause_twice)
20619           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
20620       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
20621           << getOpenMPClauseName(OMPC_nontemporal);
20622       continue;
20623     }
20624 
20625     Vars.push_back(RefExpr);
20626   }
20627 
20628   if (Vars.empty())
20629     return nullptr;
20630 
20631   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20632                                       Vars);
20633 }
20634 
20635 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
20636                                             SourceLocation StartLoc,
20637                                             SourceLocation LParenLoc,
20638                                             SourceLocation EndLoc) {
20639   SmallVector<Expr *, 8> Vars;
20640   for (Expr *RefExpr : VarList) {
20641     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20642     SourceLocation ELoc;
20643     SourceRange ERange;
20644     Expr *SimpleRefExpr = RefExpr;
20645     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20646                               /*AllowArraySection=*/true);
20647     if (Res.second)
20648       // It will be analyzed later.
20649       Vars.push_back(RefExpr);
20650     ValueDecl *D = Res.first;
20651     if (!D)
20652       continue;
20653 
20654     const DSAStackTy::DSAVarData DVar =
20655         DSAStack->getTopDSA(D, /*FromParent=*/true);
20656     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
20657     // A list item that appears in the inclusive or exclusive clause must appear
20658     // in a reduction clause with the inscan modifier on the enclosing
20659     // worksharing-loop, worksharing-loop SIMD, or simd construct.
20660     if (DVar.CKind != OMPC_reduction ||
20661         DVar.Modifier != OMPC_REDUCTION_inscan)
20662       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
20663           << RefExpr->getSourceRange();
20664 
20665     if (DSAStack->getParentDirective() != OMPD_unknown)
20666       DSAStack->markDeclAsUsedInScanDirective(D);
20667     Vars.push_back(RefExpr);
20668   }
20669 
20670   if (Vars.empty())
20671     return nullptr;
20672 
20673   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
20674 }
20675 
20676 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
20677                                             SourceLocation StartLoc,
20678                                             SourceLocation LParenLoc,
20679                                             SourceLocation EndLoc) {
20680   SmallVector<Expr *, 8> Vars;
20681   for (Expr *RefExpr : VarList) {
20682     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20683     SourceLocation ELoc;
20684     SourceRange ERange;
20685     Expr *SimpleRefExpr = RefExpr;
20686     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20687                               /*AllowArraySection=*/true);
20688     if (Res.second)
20689       // It will be analyzed later.
20690       Vars.push_back(RefExpr);
20691     ValueDecl *D = Res.first;
20692     if (!D)
20693       continue;
20694 
20695     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
20696     DSAStackTy::DSAVarData DVar;
20697     if (ParentDirective != OMPD_unknown)
20698       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
20699     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
20700     // A list item that appears in the inclusive or exclusive clause must appear
20701     // in a reduction clause with the inscan modifier on the enclosing
20702     // worksharing-loop, worksharing-loop SIMD, or simd construct.
20703     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
20704         DVar.Modifier != OMPC_REDUCTION_inscan) {
20705       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
20706           << RefExpr->getSourceRange();
20707     } else {
20708       DSAStack->markDeclAsUsedInScanDirective(D);
20709     }
20710     Vars.push_back(RefExpr);
20711   }
20712 
20713   if (Vars.empty())
20714     return nullptr;
20715 
20716   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
20717 }
20718 
20719 /// Tries to find omp_alloctrait_t type.
20720 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
20721   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
20722   if (!OMPAlloctraitT.isNull())
20723     return true;
20724   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
20725   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
20726   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20727     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
20728     return false;
20729   }
20730   Stack->setOMPAlloctraitT(PT.get());
20731   return true;
20732 }
20733 
20734 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
20735     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
20736     ArrayRef<UsesAllocatorsData> Data) {
20737   // OpenMP [2.12.5, target Construct]
20738   // allocator is an identifier of omp_allocator_handle_t type.
20739   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
20740     return nullptr;
20741   // OpenMP [2.12.5, target Construct]
20742   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
20743   if (llvm::any_of(
20744           Data,
20745           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
20746       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
20747     return nullptr;
20748   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
20749   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
20750     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
20751     StringRef Allocator =
20752         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
20753     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
20754     PredefinedAllocators.insert(LookupSingleName(
20755         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
20756   }
20757 
20758   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
20759   for (const UsesAllocatorsData &D : Data) {
20760     Expr *AllocatorExpr = nullptr;
20761     // Check allocator expression.
20762     if (D.Allocator->isTypeDependent()) {
20763       AllocatorExpr = D.Allocator;
20764     } else {
20765       // Traits were specified - need to assign new allocator to the specified
20766       // allocator, so it must be an lvalue.
20767       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
20768       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
20769       bool IsPredefinedAllocator = false;
20770       if (DRE)
20771         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
20772       if (!DRE ||
20773           !(Context.hasSameUnqualifiedType(
20774                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
20775             Context.typesAreCompatible(AllocatorExpr->getType(),
20776                                        DSAStack->getOMPAllocatorHandleT(),
20777                                        /*CompareUnqualified=*/true)) ||
20778           (!IsPredefinedAllocator &&
20779            (AllocatorExpr->getType().isConstant(Context) ||
20780             !AllocatorExpr->isLValue()))) {
20781         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
20782             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
20783             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
20784         continue;
20785       }
20786       // OpenMP [2.12.5, target Construct]
20787       // Predefined allocators appearing in a uses_allocators clause cannot have
20788       // traits specified.
20789       if (IsPredefinedAllocator && D.AllocatorTraits) {
20790         Diag(D.AllocatorTraits->getExprLoc(),
20791              diag::err_omp_predefined_allocator_with_traits)
20792             << D.AllocatorTraits->getSourceRange();
20793         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
20794             << cast<NamedDecl>(DRE->getDecl())->getName()
20795             << D.Allocator->getSourceRange();
20796         continue;
20797       }
20798       // OpenMP [2.12.5, target Construct]
20799       // Non-predefined allocators appearing in a uses_allocators clause must
20800       // have traits specified.
20801       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
20802         Diag(D.Allocator->getExprLoc(),
20803              diag::err_omp_nonpredefined_allocator_without_traits);
20804         continue;
20805       }
20806       // No allocator traits - just convert it to rvalue.
20807       if (!D.AllocatorTraits)
20808         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
20809       DSAStack->addUsesAllocatorsDecl(
20810           DRE->getDecl(),
20811           IsPredefinedAllocator
20812               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
20813               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
20814     }
20815     Expr *AllocatorTraitsExpr = nullptr;
20816     if (D.AllocatorTraits) {
20817       if (D.AllocatorTraits->isTypeDependent()) {
20818         AllocatorTraitsExpr = D.AllocatorTraits;
20819       } else {
20820         // OpenMP [2.12.5, target Construct]
20821         // Arrays that contain allocator traits that appear in a uses_allocators
20822         // clause must be constant arrays, have constant values and be defined
20823         // in the same scope as the construct in which the clause appears.
20824         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
20825         // Check that traits expr is a constant array.
20826         QualType TraitTy;
20827         if (const ArrayType *Ty =
20828                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
20829           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
20830             TraitTy = ConstArrayTy->getElementType();
20831         if (TraitTy.isNull() ||
20832             !(Context.hasSameUnqualifiedType(TraitTy,
20833                                              DSAStack->getOMPAlloctraitT()) ||
20834               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
20835                                          /*CompareUnqualified=*/true))) {
20836           Diag(D.AllocatorTraits->getExprLoc(),
20837                diag::err_omp_expected_array_alloctraits)
20838               << AllocatorTraitsExpr->getType();
20839           continue;
20840         }
20841         // Do not map by default allocator traits if it is a standalone
20842         // variable.
20843         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
20844           DSAStack->addUsesAllocatorsDecl(
20845               DRE->getDecl(),
20846               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
20847       }
20848     }
20849     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
20850     NewD.Allocator = AllocatorExpr;
20851     NewD.AllocatorTraits = AllocatorTraitsExpr;
20852     NewD.LParenLoc = D.LParenLoc;
20853     NewD.RParenLoc = D.RParenLoc;
20854   }
20855   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20856                                          NewData);
20857 }
20858 
20859 OMPClause *Sema::ActOnOpenMPAffinityClause(
20860     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
20861     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
20862   SmallVector<Expr *, 8> Vars;
20863   for (Expr *RefExpr : Locators) {
20864     assert(RefExpr && "NULL expr in OpenMP shared clause.");
20865     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
20866       // It will be analyzed later.
20867       Vars.push_back(RefExpr);
20868       continue;
20869     }
20870 
20871     SourceLocation ELoc = RefExpr->getExprLoc();
20872     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
20873 
20874     if (!SimpleExpr->isLValue()) {
20875       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
20876           << 1 << 0 << RefExpr->getSourceRange();
20877       continue;
20878     }
20879 
20880     ExprResult Res;
20881     {
20882       Sema::TentativeAnalysisScope Trap(*this);
20883       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
20884     }
20885     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
20886         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
20887       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
20888           << 1 << 0 << RefExpr->getSourceRange();
20889       continue;
20890     }
20891     Vars.push_back(SimpleExpr);
20892   }
20893 
20894   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
20895                                    EndLoc, Modifier, Vars);
20896 }
20897