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/Frontend/OpenMP/OMPConstants.h"
39 #include <set>
40 
41 using namespace clang;
42 using namespace llvm::omp;
43 
44 //===----------------------------------------------------------------------===//
45 // Stack of data-sharing attributes for variables
46 //===----------------------------------------------------------------------===//
47 
48 static const Expr *checkMapClauseExpressionBase(
49     Sema &SemaRef, Expr *E,
50     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
51     OpenMPClauseKind CKind, bool NoDiagnose);
52 
53 namespace {
54 /// Default data sharing attributes, which can be applied to directive.
55 enum DefaultDataSharingAttributes {
56   DSA_unspecified = 0, /// Data sharing attribute not specified.
57   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
58   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
59 };
60 
61 /// Stack for tracking declarations used in OpenMP directives and
62 /// clauses and their data-sharing attributes.
63 class DSAStackTy {
64 public:
65   struct DSAVarData {
66     OpenMPDirectiveKind DKind = OMPD_unknown;
67     OpenMPClauseKind CKind = OMPC_unknown;
68     unsigned Modifier = 0;
69     const Expr *RefExpr = nullptr;
70     DeclRefExpr *PrivateCopy = nullptr;
71     SourceLocation ImplicitDSALoc;
72     DSAVarData() = default;
73     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
74                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
75                SourceLocation ImplicitDSALoc, unsigned Modifier)
76         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
77           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
78   };
79   using OperatorOffsetTy =
80       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
81   using DoacrossDependMapTy =
82       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
83   /// Kind of the declaration used in the uses_allocators clauses.
84   enum class UsesAllocatorsDeclKind {
85     /// Predefined allocator
86     PredefinedAllocator,
87     /// User-defined allocator
88     UserDefinedAllocator,
89     /// The declaration that represent allocator trait
90     AllocatorTrait,
91   };
92 
93 private:
94   struct DSAInfo {
95     OpenMPClauseKind Attributes = OMPC_unknown;
96     unsigned Modifier = 0;
97     /// Pointer to a reference expression and a flag which shows that the
98     /// variable is marked as lastprivate(true) or not (false).
99     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
100     DeclRefExpr *PrivateCopy = nullptr;
101   };
102   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
103   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
104   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
105   using LoopControlVariablesMapTy =
106       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
107   /// Struct that associates a component with the clause kind where they are
108   /// found.
109   struct MappedExprComponentTy {
110     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
111     OpenMPClauseKind Kind = OMPC_unknown;
112   };
113   using MappedExprComponentsTy =
114       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
115   using CriticalsWithHintsTy =
116       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
117   struct ReductionData {
118     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
119     SourceRange ReductionRange;
120     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
121     ReductionData() = default;
122     void set(BinaryOperatorKind BO, SourceRange RR) {
123       ReductionRange = RR;
124       ReductionOp = BO;
125     }
126     void set(const Expr *RefExpr, SourceRange RR) {
127       ReductionRange = RR;
128       ReductionOp = RefExpr;
129     }
130   };
131   using DeclReductionMapTy =
132       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
133   struct DefaultmapInfo {
134     OpenMPDefaultmapClauseModifier ImplicitBehavior =
135         OMPC_DEFAULTMAP_MODIFIER_unknown;
136     SourceLocation SLoc;
137     DefaultmapInfo() = default;
138     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
139         : ImplicitBehavior(M), SLoc(Loc) {}
140   };
141 
142   struct SharingMapTy {
143     DeclSAMapTy SharingMap;
144     DeclReductionMapTy ReductionMap;
145     UsedRefMapTy AlignedMap;
146     UsedRefMapTy NontemporalMap;
147     MappedExprComponentsTy MappedExprComponents;
148     LoopControlVariablesMapTy LCVMap;
149     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
150     SourceLocation DefaultAttrLoc;
151     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
152     OpenMPDirectiveKind Directive = OMPD_unknown;
153     DeclarationNameInfo DirectiveName;
154     Scope *CurScope = nullptr;
155     SourceLocation ConstructLoc;
156     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
157     /// get the data (loop counters etc.) about enclosing loop-based construct.
158     /// This data is required during codegen.
159     DoacrossDependMapTy DoacrossDepends;
160     /// First argument (Expr *) contains optional argument of the
161     /// 'ordered' clause, the second one is true if the regions has 'ordered'
162     /// clause, false otherwise.
163     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
164     unsigned AssociatedLoops = 1;
165     bool HasMutipleLoops = false;
166     const Decl *PossiblyLoopCounter = nullptr;
167     bool NowaitRegion = false;
168     bool CancelRegion = false;
169     bool LoopStart = false;
170     bool BodyComplete = false;
171     SourceLocation PrevScanLocation;
172     SourceLocation InnerTeamsRegionLoc;
173     /// Reference to the taskgroup task_reduction reference expression.
174     Expr *TaskgroupReductionRef = nullptr;
175     llvm::DenseSet<QualType> MappedClassesQualTypes;
176     SmallVector<Expr *, 4> InnerUsedAllocators;
177     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
178     /// List of globals marked as declare target link in this target region
179     /// (isOpenMPTargetExecutionDirective(Directive) == true).
180     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
181     /// List of decls used in inclusive/exclusive clauses of the scan directive.
182     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
183     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
184         UsesAllocatorsDecls;
185     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
186                  Scope *CurScope, SourceLocation Loc)
187         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
188           ConstructLoc(Loc) {}
189     SharingMapTy() = default;
190   };
191 
192   using StackTy = SmallVector<SharingMapTy, 4>;
193 
194   /// Stack of used declaration and their data-sharing attributes.
195   DeclSAMapTy Threadprivates;
196   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
197   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
198   /// true, if check for DSA must be from parent directive, false, if
199   /// from current directive.
200   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
201   Sema &SemaRef;
202   bool ForceCapturing = false;
203   /// true if all the variables in the target executable directives must be
204   /// captured by reference.
205   bool ForceCaptureByReferenceInTargetExecutable = false;
206   CriticalsWithHintsTy Criticals;
207   unsigned IgnoredStackElements = 0;
208 
209   /// Iterators over the stack iterate in order from innermost to outermost
210   /// directive.
211   using const_iterator = StackTy::const_reverse_iterator;
212   const_iterator begin() const {
213     return Stack.empty() ? const_iterator()
214                          : Stack.back().first.rbegin() + IgnoredStackElements;
215   }
216   const_iterator end() const {
217     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
218   }
219   using iterator = StackTy::reverse_iterator;
220   iterator begin() {
221     return Stack.empty() ? iterator()
222                          : Stack.back().first.rbegin() + IgnoredStackElements;
223   }
224   iterator end() {
225     return Stack.empty() ? iterator() : Stack.back().first.rend();
226   }
227 
228   // Convenience operations to get at the elements of the stack.
229 
230   bool isStackEmpty() const {
231     return Stack.empty() ||
232            Stack.back().second != CurrentNonCapturingFunctionScope ||
233            Stack.back().first.size() <= IgnoredStackElements;
234   }
235   size_t getStackSize() const {
236     return isStackEmpty() ? 0
237                           : Stack.back().first.size() - IgnoredStackElements;
238   }
239 
240   SharingMapTy *getTopOfStackOrNull() {
241     size_t Size = getStackSize();
242     if (Size == 0)
243       return nullptr;
244     return &Stack.back().first[Size - 1];
245   }
246   const SharingMapTy *getTopOfStackOrNull() const {
247     return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
248   }
249   SharingMapTy &getTopOfStack() {
250     assert(!isStackEmpty() && "no current directive");
251     return *getTopOfStackOrNull();
252   }
253   const SharingMapTy &getTopOfStack() const {
254     return const_cast<DSAStackTy&>(*this).getTopOfStack();
255   }
256 
257   SharingMapTy *getSecondOnStackOrNull() {
258     size_t Size = getStackSize();
259     if (Size <= 1)
260       return nullptr;
261     return &Stack.back().first[Size - 2];
262   }
263   const SharingMapTy *getSecondOnStackOrNull() const {
264     return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
265   }
266 
267   /// Get the stack element at a certain level (previously returned by
268   /// \c getNestingLevel).
269   ///
270   /// Note that nesting levels count from outermost to innermost, and this is
271   /// the reverse of our iteration order where new inner levels are pushed at
272   /// the front of the stack.
273   SharingMapTy &getStackElemAtLevel(unsigned Level) {
274     assert(Level < getStackSize() && "no such stack element");
275     return Stack.back().first[Level];
276   }
277   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
278     return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
279   }
280 
281   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
282 
283   /// Checks if the variable is a local for OpenMP region.
284   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
285 
286   /// Vector of previously declared requires directives
287   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
288   /// omp_allocator_handle_t type.
289   QualType OMPAllocatorHandleT;
290   /// omp_depend_t type.
291   QualType OMPDependT;
292   /// omp_event_handle_t type.
293   QualType OMPEventHandleT;
294   /// omp_alloctrait_t type.
295   QualType OMPAlloctraitT;
296   /// Expression for the predefined allocators.
297   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
298       nullptr};
299   /// Vector of previously encountered target directives
300   SmallVector<SourceLocation, 2> TargetLocations;
301   SourceLocation AtomicLocation;
302 
303 public:
304   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
305 
306   /// Sets omp_allocator_handle_t type.
307   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
308   /// Gets omp_allocator_handle_t type.
309   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
310   /// Sets omp_alloctrait_t type.
311   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
312   /// Gets omp_alloctrait_t type.
313   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
314   /// Sets the given default allocator.
315   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
316                     Expr *Allocator) {
317     OMPPredefinedAllocators[AllocatorKind] = Allocator;
318   }
319   /// Returns the specified default allocator.
320   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
321     return OMPPredefinedAllocators[AllocatorKind];
322   }
323   /// Sets omp_depend_t type.
324   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
325   /// Gets omp_depend_t type.
326   QualType getOMPDependT() const { return OMPDependT; }
327 
328   /// Sets omp_event_handle_t type.
329   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
330   /// Gets omp_event_handle_t type.
331   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
332 
333   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
334   OpenMPClauseKind getClauseParsingMode() const {
335     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
336     return ClauseKindMode;
337   }
338   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
339 
340   bool isBodyComplete() const {
341     const SharingMapTy *Top = getTopOfStackOrNull();
342     return Top && Top->BodyComplete;
343   }
344   void setBodyComplete() {
345     getTopOfStack().BodyComplete = true;
346   }
347 
348   bool isForceVarCapturing() const { return ForceCapturing; }
349   void setForceVarCapturing(bool V) { ForceCapturing = V; }
350 
351   void setForceCaptureByReferenceInTargetExecutable(bool V) {
352     ForceCaptureByReferenceInTargetExecutable = V;
353   }
354   bool isForceCaptureByReferenceInTargetExecutable() const {
355     return ForceCaptureByReferenceInTargetExecutable;
356   }
357 
358   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
359             Scope *CurScope, SourceLocation Loc) {
360     assert(!IgnoredStackElements &&
361            "cannot change stack while ignoring elements");
362     if (Stack.empty() ||
363         Stack.back().second != CurrentNonCapturingFunctionScope)
364       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
365     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
366     Stack.back().first.back().DefaultAttrLoc = Loc;
367   }
368 
369   void pop() {
370     assert(!IgnoredStackElements &&
371            "cannot change stack while ignoring elements");
372     assert(!Stack.back().first.empty() &&
373            "Data-sharing attributes stack is empty!");
374     Stack.back().first.pop_back();
375   }
376 
377   /// RAII object to temporarily leave the scope of a directive when we want to
378   /// logically operate in its parent.
379   class ParentDirectiveScope {
380     DSAStackTy &Self;
381     bool Active;
382   public:
383     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
384         : Self(Self), Active(false) {
385       if (Activate)
386         enable();
387     }
388     ~ParentDirectiveScope() { disable(); }
389     void disable() {
390       if (Active) {
391         --Self.IgnoredStackElements;
392         Active = false;
393       }
394     }
395     void enable() {
396       if (!Active) {
397         ++Self.IgnoredStackElements;
398         Active = true;
399       }
400     }
401   };
402 
403   /// Marks that we're started loop parsing.
404   void loopInit() {
405     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
406            "Expected loop-based directive.");
407     getTopOfStack().LoopStart = true;
408   }
409   /// Start capturing of the variables in the loop context.
410   void loopStart() {
411     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
412            "Expected loop-based directive.");
413     getTopOfStack().LoopStart = false;
414   }
415   /// true, if variables are captured, false otherwise.
416   bool isLoopStarted() const {
417     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
418            "Expected loop-based directive.");
419     return !getTopOfStack().LoopStart;
420   }
421   /// Marks (or clears) declaration as possibly loop counter.
422   void resetPossibleLoopCounter(const Decl *D = nullptr) {
423     getTopOfStack().PossiblyLoopCounter =
424         D ? D->getCanonicalDecl() : D;
425   }
426   /// Gets the possible loop counter decl.
427   const Decl *getPossiblyLoopCunter() const {
428     return getTopOfStack().PossiblyLoopCounter;
429   }
430   /// Start new OpenMP region stack in new non-capturing function.
431   void pushFunction() {
432     assert(!IgnoredStackElements &&
433            "cannot change stack while ignoring elements");
434     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
435     assert(!isa<CapturingScopeInfo>(CurFnScope));
436     CurrentNonCapturingFunctionScope = CurFnScope;
437   }
438   /// Pop region stack for non-capturing function.
439   void popFunction(const FunctionScopeInfo *OldFSI) {
440     assert(!IgnoredStackElements &&
441            "cannot change stack while ignoring elements");
442     if (!Stack.empty() && Stack.back().second == OldFSI) {
443       assert(Stack.back().first.empty());
444       Stack.pop_back();
445     }
446     CurrentNonCapturingFunctionScope = nullptr;
447     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
448       if (!isa<CapturingScopeInfo>(FSI)) {
449         CurrentNonCapturingFunctionScope = FSI;
450         break;
451       }
452     }
453   }
454 
455   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
456     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
457   }
458   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
459   getCriticalWithHint(const DeclarationNameInfo &Name) const {
460     auto I = Criticals.find(Name.getAsString());
461     if (I != Criticals.end())
462       return I->second;
463     return std::make_pair(nullptr, llvm::APSInt());
464   }
465   /// If 'aligned' declaration for given variable \a D was not seen yet,
466   /// add it and return NULL; otherwise return previous occurrence's expression
467   /// for diagnostics.
468   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
469   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
470   /// add it and return NULL; otherwise return previous occurrence's expression
471   /// for diagnostics.
472   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
473 
474   /// Register specified variable as loop control variable.
475   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
476   /// Check if the specified variable is a loop control variable for
477   /// current region.
478   /// \return The index of the loop control variable in the list of associated
479   /// for-loops (from outer to inner).
480   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
481   /// Check if the specified variable is a loop control variable for
482   /// parent region.
483   /// \return The index of the loop control variable in the list of associated
484   /// for-loops (from outer to inner).
485   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
486   /// Check if the specified variable is a loop control variable for
487   /// current region.
488   /// \return The index of the loop control variable in the list of associated
489   /// for-loops (from outer to inner).
490   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
491                                          unsigned Level) const;
492   /// Get the loop control variable for the I-th loop (or nullptr) in
493   /// parent directive.
494   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
495 
496   /// Marks the specified decl \p D as used in scan directive.
497   void markDeclAsUsedInScanDirective(ValueDecl *D) {
498     if (SharingMapTy *Stack = getSecondOnStackOrNull())
499       Stack->UsedInScanDirective.insert(D);
500   }
501 
502   /// Checks if the specified declaration was used in the inner scan directive.
503   bool isUsedInScanDirective(ValueDecl *D) const {
504     if (const SharingMapTy *Stack = getTopOfStackOrNull())
505       return Stack->UsedInScanDirective.count(D) > 0;
506     return false;
507   }
508 
509   /// Adds explicit data sharing attribute to the specified declaration.
510   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
511               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0);
512 
513   /// Adds additional information for the reduction items with the reduction id
514   /// represented as an operator.
515   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
516                                  BinaryOperatorKind BOK);
517   /// Adds additional information for the reduction items with the reduction id
518   /// represented as reduction identifier.
519   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
520                                  const Expr *ReductionRef);
521   /// Returns the location and reduction operation from the innermost parent
522   /// region for the given \p D.
523   const DSAVarData
524   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
525                                    BinaryOperatorKind &BOK,
526                                    Expr *&TaskgroupDescriptor) const;
527   /// Returns the location and reduction operation from the innermost parent
528   /// region for the given \p D.
529   const DSAVarData
530   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
531                                    const Expr *&ReductionRef,
532                                    Expr *&TaskgroupDescriptor) const;
533   /// Return reduction reference expression for the current taskgroup or
534   /// parallel/worksharing directives with task reductions.
535   Expr *getTaskgroupReductionRef() const {
536     assert((getTopOfStack().Directive == OMPD_taskgroup ||
537             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
538               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
539              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
540            "taskgroup reference expression requested for non taskgroup or "
541            "parallel/worksharing directive.");
542     return getTopOfStack().TaskgroupReductionRef;
543   }
544   /// Checks if the given \p VD declaration is actually a taskgroup reduction
545   /// descriptor variable at the \p Level of OpenMP regions.
546   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
547     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
548            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
549                    ->getDecl() == VD;
550   }
551 
552   /// Returns data sharing attributes from top of the stack for the
553   /// specified declaration.
554   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
555   /// Returns data-sharing attributes for the specified declaration.
556   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
557   /// Returns data-sharing attributes for the specified declaration.
558   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
559   /// Checks if the specified variables has data-sharing attributes which
560   /// match specified \a CPred predicate in any directive which matches \a DPred
561   /// predicate.
562   const DSAVarData
563   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
564          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
565          bool FromParent) const;
566   /// Checks if the specified variables has data-sharing attributes which
567   /// match specified \a CPred predicate in any innermost directive which
568   /// matches \a DPred predicate.
569   const DSAVarData
570   hasInnermostDSA(ValueDecl *D,
571                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
572                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
573                   bool FromParent) const;
574   /// Checks if the specified variables has explicit data-sharing
575   /// attributes which match specified \a CPred predicate at the specified
576   /// OpenMP region.
577   bool hasExplicitDSA(const ValueDecl *D,
578                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
579                       unsigned Level, bool NotLastprivate = false) const;
580 
581   /// Returns true if the directive at level \Level matches in the
582   /// specified \a DPred predicate.
583   bool hasExplicitDirective(
584       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
585       unsigned Level) const;
586 
587   /// Finds a directive which matches specified \a DPred predicate.
588   bool hasDirective(
589       const llvm::function_ref<bool(
590           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
591           DPred,
592       bool FromParent) const;
593 
594   /// Returns currently analyzed directive.
595   OpenMPDirectiveKind getCurrentDirective() const {
596     const SharingMapTy *Top = getTopOfStackOrNull();
597     return Top ? Top->Directive : OMPD_unknown;
598   }
599   /// Returns directive kind at specified level.
600   OpenMPDirectiveKind getDirective(unsigned Level) const {
601     assert(!isStackEmpty() && "No directive at specified level.");
602     return getStackElemAtLevel(Level).Directive;
603   }
604   /// Returns the capture region at the specified level.
605   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
606                                        unsigned OpenMPCaptureLevel) const {
607     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
608     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
609     return CaptureRegions[OpenMPCaptureLevel];
610   }
611   /// Returns parent directive.
612   OpenMPDirectiveKind getParentDirective() const {
613     const SharingMapTy *Parent = getSecondOnStackOrNull();
614     return Parent ? Parent->Directive : OMPD_unknown;
615   }
616 
617   /// Add requires decl to internal vector
618   void addRequiresDecl(OMPRequiresDecl *RD) {
619     RequiresDecls.push_back(RD);
620   }
621 
622   /// Checks if the defined 'requires' directive has specified type of clause.
623   template <typename ClauseType>
624   bool hasRequiresDeclWithClause() const {
625     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
626       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
627         return isa<ClauseType>(C);
628       });
629     });
630   }
631 
632   /// Checks for a duplicate clause amongst previously declared requires
633   /// directives
634   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
635     bool IsDuplicate = false;
636     for (OMPClause *CNew : ClauseList) {
637       for (const OMPRequiresDecl *D : RequiresDecls) {
638         for (const OMPClause *CPrev : D->clauselists()) {
639           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
640             SemaRef.Diag(CNew->getBeginLoc(),
641                          diag::err_omp_requires_clause_redeclaration)
642                 << getOpenMPClauseName(CNew->getClauseKind());
643             SemaRef.Diag(CPrev->getBeginLoc(),
644                          diag::note_omp_requires_previous_clause)
645                 << getOpenMPClauseName(CPrev->getClauseKind());
646             IsDuplicate = true;
647           }
648         }
649       }
650     }
651     return IsDuplicate;
652   }
653 
654   /// Add location of previously encountered target to internal vector
655   void addTargetDirLocation(SourceLocation LocStart) {
656     TargetLocations.push_back(LocStart);
657   }
658 
659   /// Add location for the first encountered atomicc directive.
660   void addAtomicDirectiveLoc(SourceLocation Loc) {
661     if (AtomicLocation.isInvalid())
662       AtomicLocation = Loc;
663   }
664 
665   /// Returns the location of the first encountered atomic directive in the
666   /// module.
667   SourceLocation getAtomicDirectiveLoc() const {
668     return AtomicLocation;
669   }
670 
671   // Return previously encountered target region locations.
672   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
673     return TargetLocations;
674   }
675 
676   /// Set default data sharing attribute to none.
677   void setDefaultDSANone(SourceLocation Loc) {
678     getTopOfStack().DefaultAttr = DSA_none;
679     getTopOfStack().DefaultAttrLoc = Loc;
680   }
681   /// Set default data sharing attribute to shared.
682   void setDefaultDSAShared(SourceLocation Loc) {
683     getTopOfStack().DefaultAttr = DSA_shared;
684     getTopOfStack().DefaultAttrLoc = Loc;
685   }
686   /// Set default data mapping attribute to Modifier:Kind
687   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
688                          OpenMPDefaultmapClauseKind Kind,
689                          SourceLocation Loc) {
690     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
691     DMI.ImplicitBehavior = M;
692     DMI.SLoc = Loc;
693   }
694   /// Check whether the implicit-behavior has been set in defaultmap
695   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
696     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
697       return getTopOfStack()
698                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
699                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
700              getTopOfStack()
701                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
702                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
703              getTopOfStack()
704                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
705                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
706     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
707            OMPC_DEFAULTMAP_MODIFIER_unknown;
708   }
709 
710   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
711     return getStackSize() <= Level ? DSA_unspecified
712                                    : getStackElemAtLevel(Level).DefaultAttr;
713   }
714   DefaultDataSharingAttributes getDefaultDSA() const {
715     return isStackEmpty() ? DSA_unspecified
716                           : getTopOfStack().DefaultAttr;
717   }
718   SourceLocation getDefaultDSALocation() const {
719     return isStackEmpty() ? SourceLocation()
720                           : getTopOfStack().DefaultAttrLoc;
721   }
722   OpenMPDefaultmapClauseModifier
723   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
724     return isStackEmpty()
725                ? OMPC_DEFAULTMAP_MODIFIER_unknown
726                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
727   }
728   OpenMPDefaultmapClauseModifier
729   getDefaultmapModifierAtLevel(unsigned Level,
730                                OpenMPDefaultmapClauseKind Kind) const {
731     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
732   }
733   bool isDefaultmapCapturedByRef(unsigned Level,
734                                  OpenMPDefaultmapClauseKind Kind) const {
735     OpenMPDefaultmapClauseModifier M =
736         getDefaultmapModifierAtLevel(Level, Kind);
737     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
738       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
739              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
740              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
741              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
742     }
743     return true;
744   }
745   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
746                                      OpenMPDefaultmapClauseKind Kind) {
747     switch (Kind) {
748     case OMPC_DEFAULTMAP_scalar:
749     case OMPC_DEFAULTMAP_pointer:
750       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
751              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
752              (M == OMPC_DEFAULTMAP_MODIFIER_default);
753     case OMPC_DEFAULTMAP_aggregate:
754       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
755     default:
756       break;
757     }
758     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
759   }
760   bool mustBeFirstprivateAtLevel(unsigned Level,
761                                  OpenMPDefaultmapClauseKind Kind) const {
762     OpenMPDefaultmapClauseModifier M =
763         getDefaultmapModifierAtLevel(Level, Kind);
764     return mustBeFirstprivateBase(M, Kind);
765   }
766   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
767     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
768     return mustBeFirstprivateBase(M, Kind);
769   }
770 
771   /// Checks if the specified variable is a threadprivate.
772   bool isThreadPrivate(VarDecl *D) {
773     const DSAVarData DVar = getTopDSA(D, false);
774     return isOpenMPThreadPrivate(DVar.CKind);
775   }
776 
777   /// Marks current region as ordered (it has an 'ordered' clause).
778   void setOrderedRegion(bool IsOrdered, const Expr *Param,
779                         OMPOrderedClause *Clause) {
780     if (IsOrdered)
781       getTopOfStack().OrderedRegion.emplace(Param, Clause);
782     else
783       getTopOfStack().OrderedRegion.reset();
784   }
785   /// Returns true, if region is ordered (has associated 'ordered' clause),
786   /// false - otherwise.
787   bool isOrderedRegion() const {
788     if (const SharingMapTy *Top = getTopOfStackOrNull())
789       return Top->OrderedRegion.hasValue();
790     return false;
791   }
792   /// Returns optional parameter for the ordered region.
793   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
794     if (const SharingMapTy *Top = getTopOfStackOrNull())
795       if (Top->OrderedRegion.hasValue())
796         return Top->OrderedRegion.getValue();
797     return std::make_pair(nullptr, nullptr);
798   }
799   /// Returns true, if parent region is ordered (has associated
800   /// 'ordered' clause), false - otherwise.
801   bool isParentOrderedRegion() const {
802     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
803       return Parent->OrderedRegion.hasValue();
804     return false;
805   }
806   /// Returns optional parameter for the ordered region.
807   std::pair<const Expr *, OMPOrderedClause *>
808   getParentOrderedRegionParam() const {
809     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
810       if (Parent->OrderedRegion.hasValue())
811         return Parent->OrderedRegion.getValue();
812     return std::make_pair(nullptr, nullptr);
813   }
814   /// Marks current region as nowait (it has a 'nowait' clause).
815   void setNowaitRegion(bool IsNowait = true) {
816     getTopOfStack().NowaitRegion = IsNowait;
817   }
818   /// Returns true, if parent region is nowait (has associated
819   /// 'nowait' clause), false - otherwise.
820   bool isParentNowaitRegion() const {
821     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
822       return Parent->NowaitRegion;
823     return false;
824   }
825   /// Marks parent region as cancel region.
826   void setParentCancelRegion(bool Cancel = true) {
827     if (SharingMapTy *Parent = getSecondOnStackOrNull())
828       Parent->CancelRegion |= Cancel;
829   }
830   /// Return true if current region has inner cancel construct.
831   bool isCancelRegion() const {
832     const SharingMapTy *Top = getTopOfStackOrNull();
833     return Top ? Top->CancelRegion : false;
834   }
835 
836   /// Mark that parent region already has scan directive.
837   void setParentHasScanDirective(SourceLocation Loc) {
838     if (SharingMapTy *Parent = getSecondOnStackOrNull())
839       Parent->PrevScanLocation = Loc;
840   }
841   /// Return true if current region has inner cancel construct.
842   bool doesParentHasScanDirective() const {
843     const SharingMapTy *Top = getSecondOnStackOrNull();
844     return Top ? Top->PrevScanLocation.isValid() : false;
845   }
846   /// Return true if current region has inner cancel construct.
847   SourceLocation getParentScanDirectiveLoc() const {
848     const SharingMapTy *Top = getSecondOnStackOrNull();
849     return Top ? Top->PrevScanLocation : SourceLocation();
850   }
851 
852   /// Set collapse value for the region.
853   void setAssociatedLoops(unsigned Val) {
854     getTopOfStack().AssociatedLoops = Val;
855     if (Val > 1)
856       getTopOfStack().HasMutipleLoops = true;
857   }
858   /// Return collapse value for region.
859   unsigned getAssociatedLoops() const {
860     const SharingMapTy *Top = getTopOfStackOrNull();
861     return Top ? Top->AssociatedLoops : 0;
862   }
863   /// Returns true if the construct is associated with multiple loops.
864   bool hasMutipleLoops() const {
865     const SharingMapTy *Top = getTopOfStackOrNull();
866     return Top ? Top->HasMutipleLoops : false;
867   }
868 
869   /// Marks current target region as one with closely nested teams
870   /// region.
871   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
872     if (SharingMapTy *Parent = getSecondOnStackOrNull())
873       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
874   }
875   /// Returns true, if current region has closely nested teams region.
876   bool hasInnerTeamsRegion() const {
877     return getInnerTeamsRegionLoc().isValid();
878   }
879   /// Returns location of the nested teams region (if any).
880   SourceLocation getInnerTeamsRegionLoc() const {
881     const SharingMapTy *Top = getTopOfStackOrNull();
882     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
883   }
884 
885   Scope *getCurScope() const {
886     const SharingMapTy *Top = getTopOfStackOrNull();
887     return Top ? Top->CurScope : nullptr;
888   }
889   SourceLocation getConstructLoc() const {
890     const SharingMapTy *Top = getTopOfStackOrNull();
891     return Top ? Top->ConstructLoc : SourceLocation();
892   }
893 
894   /// Do the check specified in \a Check to all component lists and return true
895   /// if any issue is found.
896   bool checkMappableExprComponentListsForDecl(
897       const ValueDecl *VD, bool CurrentRegionOnly,
898       const llvm::function_ref<
899           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
900                OpenMPClauseKind)>
901           Check) const {
902     if (isStackEmpty())
903       return false;
904     auto SI = begin();
905     auto SE = end();
906 
907     if (SI == SE)
908       return false;
909 
910     if (CurrentRegionOnly)
911       SE = std::next(SI);
912     else
913       std::advance(SI, 1);
914 
915     for (; SI != SE; ++SI) {
916       auto MI = SI->MappedExprComponents.find(VD);
917       if (MI != SI->MappedExprComponents.end())
918         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
919              MI->second.Components)
920           if (Check(L, MI->second.Kind))
921             return true;
922     }
923     return false;
924   }
925 
926   /// Do the check specified in \a Check to all component lists at a given level
927   /// and return true if any issue is found.
928   bool checkMappableExprComponentListsForDeclAtLevel(
929       const ValueDecl *VD, unsigned Level,
930       const llvm::function_ref<
931           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
932                OpenMPClauseKind)>
933           Check) const {
934     if (getStackSize() <= Level)
935       return false;
936 
937     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
938     auto MI = StackElem.MappedExprComponents.find(VD);
939     if (MI != StackElem.MappedExprComponents.end())
940       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
941            MI->second.Components)
942         if (Check(L, MI->second.Kind))
943           return true;
944     return false;
945   }
946 
947   /// Create a new mappable expression component list associated with a given
948   /// declaration and initialize it with the provided list of components.
949   void addMappableExpressionComponents(
950       const ValueDecl *VD,
951       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
952       OpenMPClauseKind WhereFoundClauseKind) {
953     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
954     // Create new entry and append the new components there.
955     MEC.Components.resize(MEC.Components.size() + 1);
956     MEC.Components.back().append(Components.begin(), Components.end());
957     MEC.Kind = WhereFoundClauseKind;
958   }
959 
960   unsigned getNestingLevel() const {
961     assert(!isStackEmpty());
962     return getStackSize() - 1;
963   }
964   void addDoacrossDependClause(OMPDependClause *C,
965                                const OperatorOffsetTy &OpsOffs) {
966     SharingMapTy *Parent = getSecondOnStackOrNull();
967     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
968     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
969   }
970   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
971   getDoacrossDependClauses() const {
972     const SharingMapTy &StackElem = getTopOfStack();
973     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
974       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
975       return llvm::make_range(Ref.begin(), Ref.end());
976     }
977     return llvm::make_range(StackElem.DoacrossDepends.end(),
978                             StackElem.DoacrossDepends.end());
979   }
980 
981   // Store types of classes which have been explicitly mapped
982   void addMappedClassesQualTypes(QualType QT) {
983     SharingMapTy &StackElem = getTopOfStack();
984     StackElem.MappedClassesQualTypes.insert(QT);
985   }
986 
987   // Return set of mapped classes types
988   bool isClassPreviouslyMapped(QualType QT) const {
989     const SharingMapTy &StackElem = getTopOfStack();
990     return StackElem.MappedClassesQualTypes.count(QT) != 0;
991   }
992 
993   /// Adds global declare target to the parent target region.
994   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
995     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
996                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
997            "Expected declare target link global.");
998     for (auto &Elem : *this) {
999       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1000         Elem.DeclareTargetLinkVarDecls.push_back(E);
1001         return;
1002       }
1003     }
1004   }
1005 
1006   /// Returns the list of globals with declare target link if current directive
1007   /// is target.
1008   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1009     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1010            "Expected target executable directive.");
1011     return getTopOfStack().DeclareTargetLinkVarDecls;
1012   }
1013 
1014   /// Adds list of allocators expressions.
1015   void addInnerAllocatorExpr(Expr *E) {
1016     getTopOfStack().InnerUsedAllocators.push_back(E);
1017   }
1018   /// Return list of used allocators.
1019   ArrayRef<Expr *> getInnerAllocators() const {
1020     return getTopOfStack().InnerUsedAllocators;
1021   }
1022   /// Marks the declaration as implicitly firstprivate nin the task-based
1023   /// regions.
1024   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1025     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1026   }
1027   /// Checks if the decl is implicitly firstprivate in the task-based region.
1028   bool isImplicitTaskFirstprivate(Decl *D) const {
1029     return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0;
1030   }
1031 
1032   /// Marks decl as used in uses_allocators clause as the allocator.
1033   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1034     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1035   }
1036   /// Checks if specified decl is used in uses allocator clause as the
1037   /// allocator.
1038   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1039                                                         const Decl *D) const {
1040     const SharingMapTy &StackElem = getTopOfStack();
1041     auto I = StackElem.UsesAllocatorsDecls.find(D);
1042     if (I == StackElem.UsesAllocatorsDecls.end())
1043       return None;
1044     return I->getSecond();
1045   }
1046   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1047     const SharingMapTy &StackElem = getTopOfStack();
1048     auto I = StackElem.UsesAllocatorsDecls.find(D);
1049     if (I == StackElem.UsesAllocatorsDecls.end())
1050       return None;
1051     return I->getSecond();
1052   }
1053 };
1054 
1055 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1056   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1057 }
1058 
1059 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1060   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1061          DKind == OMPD_unknown;
1062 }
1063 
1064 } // namespace
1065 
1066 static const Expr *getExprAsWritten(const Expr *E) {
1067   if (const auto *FE = dyn_cast<FullExpr>(E))
1068     E = FE->getSubExpr();
1069 
1070   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1071     E = MTE->getSubExpr();
1072 
1073   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1074     E = Binder->getSubExpr();
1075 
1076   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1077     E = ICE->getSubExprAsWritten();
1078   return E->IgnoreParens();
1079 }
1080 
1081 static Expr *getExprAsWritten(Expr *E) {
1082   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1083 }
1084 
1085 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1086   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1087     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1088       D = ME->getMemberDecl();
1089   const auto *VD = dyn_cast<VarDecl>(D);
1090   const auto *FD = dyn_cast<FieldDecl>(D);
1091   if (VD != nullptr) {
1092     VD = VD->getCanonicalDecl();
1093     D = VD;
1094   } else {
1095     assert(FD);
1096     FD = FD->getCanonicalDecl();
1097     D = FD;
1098   }
1099   return D;
1100 }
1101 
1102 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1103   return const_cast<ValueDecl *>(
1104       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1105 }
1106 
1107 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1108                                           ValueDecl *D) const {
1109   D = getCanonicalDecl(D);
1110   auto *VD = dyn_cast<VarDecl>(D);
1111   const auto *FD = dyn_cast<FieldDecl>(D);
1112   DSAVarData DVar;
1113   if (Iter == end()) {
1114     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1115     // in a region but not in construct]
1116     //  File-scope or namespace-scope variables referenced in called routines
1117     //  in the region are shared unless they appear in a threadprivate
1118     //  directive.
1119     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1120       DVar.CKind = OMPC_shared;
1121 
1122     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1123     // in a region but not in construct]
1124     //  Variables with static storage duration that are declared in called
1125     //  routines in the region are shared.
1126     if (VD && VD->hasGlobalStorage())
1127       DVar.CKind = OMPC_shared;
1128 
1129     // Non-static data members are shared by default.
1130     if (FD)
1131       DVar.CKind = OMPC_shared;
1132 
1133     return DVar;
1134   }
1135 
1136   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1137   // in a Construct, C/C++, predetermined, p.1]
1138   // Variables with automatic storage duration that are declared in a scope
1139   // inside the construct are private.
1140   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1141       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1142     DVar.CKind = OMPC_private;
1143     return DVar;
1144   }
1145 
1146   DVar.DKind = Iter->Directive;
1147   // Explicitly specified attributes and local variables with predetermined
1148   // attributes.
1149   if (Iter->SharingMap.count(D)) {
1150     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1151     DVar.RefExpr = Data.RefExpr.getPointer();
1152     DVar.PrivateCopy = Data.PrivateCopy;
1153     DVar.CKind = Data.Attributes;
1154     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1155     DVar.Modifier = Data.Modifier;
1156     return DVar;
1157   }
1158 
1159   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1160   // in a Construct, C/C++, implicitly determined, p.1]
1161   //  In a parallel or task construct, the data-sharing attributes of these
1162   //  variables are determined by the default clause, if present.
1163   switch (Iter->DefaultAttr) {
1164   case DSA_shared:
1165     DVar.CKind = OMPC_shared;
1166     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1167     return DVar;
1168   case DSA_none:
1169     return DVar;
1170   case DSA_unspecified:
1171     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1172     // in a Construct, implicitly determined, p.2]
1173     //  In a parallel construct, if no default clause is present, these
1174     //  variables are shared.
1175     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1176     if ((isOpenMPParallelDirective(DVar.DKind) &&
1177          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1178         isOpenMPTeamsDirective(DVar.DKind)) {
1179       DVar.CKind = OMPC_shared;
1180       return DVar;
1181     }
1182 
1183     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1184     // in a Construct, implicitly determined, p.4]
1185     //  In a task construct, if no default clause is present, a variable that in
1186     //  the enclosing context is determined to be shared by all implicit tasks
1187     //  bound to the current team is shared.
1188     if (isOpenMPTaskingDirective(DVar.DKind)) {
1189       DSAVarData DVarTemp;
1190       const_iterator I = Iter, E = end();
1191       do {
1192         ++I;
1193         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1194         // Referenced in a Construct, implicitly determined, p.6]
1195         //  In a task construct, if no default clause is present, a variable
1196         //  whose data-sharing attribute is not determined by the rules above is
1197         //  firstprivate.
1198         DVarTemp = getDSA(I, D);
1199         if (DVarTemp.CKind != OMPC_shared) {
1200           DVar.RefExpr = nullptr;
1201           DVar.CKind = OMPC_firstprivate;
1202           return DVar;
1203         }
1204       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1205       DVar.CKind =
1206           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1207       return DVar;
1208     }
1209   }
1210   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1211   // in a Construct, implicitly determined, p.3]
1212   //  For constructs other than task, if no default clause is present, these
1213   //  variables inherit their data-sharing attributes from the enclosing
1214   //  context.
1215   return getDSA(++Iter, D);
1216 }
1217 
1218 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1219                                          const Expr *NewDE) {
1220   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1221   D = getCanonicalDecl(D);
1222   SharingMapTy &StackElem = getTopOfStack();
1223   auto It = StackElem.AlignedMap.find(D);
1224   if (It == StackElem.AlignedMap.end()) {
1225     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1226     StackElem.AlignedMap[D] = NewDE;
1227     return nullptr;
1228   }
1229   assert(It->second && "Unexpected nullptr expr in the aligned map");
1230   return It->second;
1231 }
1232 
1233 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1234                                              const Expr *NewDE) {
1235   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1236   D = getCanonicalDecl(D);
1237   SharingMapTy &StackElem = getTopOfStack();
1238   auto It = StackElem.NontemporalMap.find(D);
1239   if (It == StackElem.NontemporalMap.end()) {
1240     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1241     StackElem.NontemporalMap[D] = NewDE;
1242     return nullptr;
1243   }
1244   assert(It->second && "Unexpected nullptr expr in the aligned map");
1245   return It->second;
1246 }
1247 
1248 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1249   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1250   D = getCanonicalDecl(D);
1251   SharingMapTy &StackElem = getTopOfStack();
1252   StackElem.LCVMap.try_emplace(
1253       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1254 }
1255 
1256 const DSAStackTy::LCDeclInfo
1257 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1258   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1259   D = getCanonicalDecl(D);
1260   const SharingMapTy &StackElem = getTopOfStack();
1261   auto It = StackElem.LCVMap.find(D);
1262   if (It != StackElem.LCVMap.end())
1263     return It->second;
1264   return {0, nullptr};
1265 }
1266 
1267 const DSAStackTy::LCDeclInfo
1268 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1269   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1270   D = getCanonicalDecl(D);
1271   for (unsigned I = Level + 1; I > 0; --I) {
1272     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1273     auto It = StackElem.LCVMap.find(D);
1274     if (It != StackElem.LCVMap.end())
1275       return It->second;
1276   }
1277   return {0, nullptr};
1278 }
1279 
1280 const DSAStackTy::LCDeclInfo
1281 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1282   const SharingMapTy *Parent = getSecondOnStackOrNull();
1283   assert(Parent && "Data-sharing attributes stack is empty");
1284   D = getCanonicalDecl(D);
1285   auto It = Parent->LCVMap.find(D);
1286   if (It != Parent->LCVMap.end())
1287     return It->second;
1288   return {0, nullptr};
1289 }
1290 
1291 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1292   const SharingMapTy *Parent = getSecondOnStackOrNull();
1293   assert(Parent && "Data-sharing attributes stack is empty");
1294   if (Parent->LCVMap.size() < I)
1295     return nullptr;
1296   for (const auto &Pair : Parent->LCVMap)
1297     if (Pair.second.first == I)
1298       return Pair.first;
1299   return nullptr;
1300 }
1301 
1302 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1303                         DeclRefExpr *PrivateCopy, unsigned Modifier) {
1304   D = getCanonicalDecl(D);
1305   if (A == OMPC_threadprivate) {
1306     DSAInfo &Data = Threadprivates[D];
1307     Data.Attributes = A;
1308     Data.RefExpr.setPointer(E);
1309     Data.PrivateCopy = nullptr;
1310     Data.Modifier = Modifier;
1311   } else {
1312     DSAInfo &Data = getTopOfStack().SharingMap[D];
1313     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1314            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1315            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1316            (isLoopControlVariable(D).first && A == OMPC_private));
1317     Data.Modifier = Modifier;
1318     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1319       Data.RefExpr.setInt(/*IntVal=*/true);
1320       return;
1321     }
1322     const bool IsLastprivate =
1323         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1324     Data.Attributes = A;
1325     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1326     Data.PrivateCopy = PrivateCopy;
1327     if (PrivateCopy) {
1328       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1329       Data.Modifier = Modifier;
1330       Data.Attributes = A;
1331       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1332       Data.PrivateCopy = nullptr;
1333     }
1334   }
1335 }
1336 
1337 /// Build a variable declaration for OpenMP loop iteration variable.
1338 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1339                              StringRef Name, const AttrVec *Attrs = nullptr,
1340                              DeclRefExpr *OrigRef = nullptr) {
1341   DeclContext *DC = SemaRef.CurContext;
1342   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1343   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1344   auto *Decl =
1345       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1346   if (Attrs) {
1347     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1348          I != E; ++I)
1349       Decl->addAttr(*I);
1350   }
1351   Decl->setImplicit();
1352   if (OrigRef) {
1353     Decl->addAttr(
1354         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1355   }
1356   return Decl;
1357 }
1358 
1359 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1360                                      SourceLocation Loc,
1361                                      bool RefersToCapture = false) {
1362   D->setReferenced();
1363   D->markUsed(S.Context);
1364   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1365                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1366                              VK_LValue);
1367 }
1368 
1369 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1370                                            BinaryOperatorKind BOK) {
1371   D = getCanonicalDecl(D);
1372   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1373   assert(
1374       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1375       "Additional reduction info may be specified only for reduction items.");
1376   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1377   assert(ReductionData.ReductionRange.isInvalid() &&
1378          (getTopOfStack().Directive == OMPD_taskgroup ||
1379           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1380             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1381            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1382          "Additional reduction info may be specified only once for reduction "
1383          "items.");
1384   ReductionData.set(BOK, SR);
1385   Expr *&TaskgroupReductionRef =
1386       getTopOfStack().TaskgroupReductionRef;
1387   if (!TaskgroupReductionRef) {
1388     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1389                                SemaRef.Context.VoidPtrTy, ".task_red.");
1390     TaskgroupReductionRef =
1391         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1392   }
1393 }
1394 
1395 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1396                                            const Expr *ReductionRef) {
1397   D = getCanonicalDecl(D);
1398   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1399   assert(
1400       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1401       "Additional reduction info may be specified only for reduction items.");
1402   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1403   assert(ReductionData.ReductionRange.isInvalid() &&
1404          (getTopOfStack().Directive == OMPD_taskgroup ||
1405           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1406             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1407            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1408          "Additional reduction info may be specified only once for reduction "
1409          "items.");
1410   ReductionData.set(ReductionRef, SR);
1411   Expr *&TaskgroupReductionRef =
1412       getTopOfStack().TaskgroupReductionRef;
1413   if (!TaskgroupReductionRef) {
1414     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1415                                SemaRef.Context.VoidPtrTy, ".task_red.");
1416     TaskgroupReductionRef =
1417         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1418   }
1419 }
1420 
1421 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1422     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1423     Expr *&TaskgroupDescriptor) const {
1424   D = getCanonicalDecl(D);
1425   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1426   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1427     const DSAInfo &Data = I->SharingMap.lookup(D);
1428     if (Data.Attributes != OMPC_reduction ||
1429         Data.Modifier != OMPC_REDUCTION_task)
1430       continue;
1431     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1432     if (!ReductionData.ReductionOp ||
1433         ReductionData.ReductionOp.is<const Expr *>())
1434       return DSAVarData();
1435     SR = ReductionData.ReductionRange;
1436     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1437     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1438                                        "expression for the descriptor is not "
1439                                        "set.");
1440     TaskgroupDescriptor = I->TaskgroupReductionRef;
1441     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1442                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task);
1443   }
1444   return DSAVarData();
1445 }
1446 
1447 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1448     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1449     Expr *&TaskgroupDescriptor) const {
1450   D = getCanonicalDecl(D);
1451   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1452   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1453     const DSAInfo &Data = I->SharingMap.lookup(D);
1454     if (Data.Attributes != OMPC_reduction ||
1455         Data.Modifier != OMPC_REDUCTION_task)
1456       continue;
1457     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1458     if (!ReductionData.ReductionOp ||
1459         !ReductionData.ReductionOp.is<const Expr *>())
1460       return DSAVarData();
1461     SR = ReductionData.ReductionRange;
1462     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1463     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1464                                        "expression for the descriptor is not "
1465                                        "set.");
1466     TaskgroupDescriptor = I->TaskgroupReductionRef;
1467     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1468                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task);
1469   }
1470   return DSAVarData();
1471 }
1472 
1473 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1474   D = D->getCanonicalDecl();
1475   for (const_iterator E = end(); I != E; ++I) {
1476     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1477         isOpenMPTargetExecutionDirective(I->Directive)) {
1478       Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1479       Scope *CurScope = getCurScope();
1480       while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1481         CurScope = CurScope->getParent();
1482       return CurScope != TopScope;
1483     }
1484   }
1485   return false;
1486 }
1487 
1488 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1489                                   bool AcceptIfMutable = true,
1490                                   bool *IsClassType = nullptr) {
1491   ASTContext &Context = SemaRef.getASTContext();
1492   Type = Type.getNonReferenceType().getCanonicalType();
1493   bool IsConstant = Type.isConstant(Context);
1494   Type = Context.getBaseElementType(Type);
1495   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1496                                 ? Type->getAsCXXRecordDecl()
1497                                 : nullptr;
1498   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1499     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1500       RD = CTD->getTemplatedDecl();
1501   if (IsClassType)
1502     *IsClassType = RD;
1503   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1504                          RD->hasDefinition() && RD->hasMutableFields());
1505 }
1506 
1507 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1508                                       QualType Type, OpenMPClauseKind CKind,
1509                                       SourceLocation ELoc,
1510                                       bool AcceptIfMutable = true,
1511                                       bool ListItemNotVar = false) {
1512   ASTContext &Context = SemaRef.getASTContext();
1513   bool IsClassType;
1514   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1515     unsigned Diag = ListItemNotVar
1516                         ? diag::err_omp_const_list_item
1517                         : IsClassType ? diag::err_omp_const_not_mutable_variable
1518                                       : diag::err_omp_const_variable;
1519     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1520     if (!ListItemNotVar && D) {
1521       const VarDecl *VD = dyn_cast<VarDecl>(D);
1522       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1523                                VarDecl::DeclarationOnly;
1524       SemaRef.Diag(D->getLocation(),
1525                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1526           << D;
1527     }
1528     return true;
1529   }
1530   return false;
1531 }
1532 
1533 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1534                                                    bool FromParent) {
1535   D = getCanonicalDecl(D);
1536   DSAVarData DVar;
1537 
1538   auto *VD = dyn_cast<VarDecl>(D);
1539   auto TI = Threadprivates.find(D);
1540   if (TI != Threadprivates.end()) {
1541     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1542     DVar.CKind = OMPC_threadprivate;
1543     DVar.Modifier = TI->getSecond().Modifier;
1544     return DVar;
1545   }
1546   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1547     DVar.RefExpr = buildDeclRefExpr(
1548         SemaRef, VD, D->getType().getNonReferenceType(),
1549         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1550     DVar.CKind = OMPC_threadprivate;
1551     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1552     return DVar;
1553   }
1554   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1555   // in a Construct, C/C++, predetermined, p.1]
1556   //  Variables appearing in threadprivate directives are threadprivate.
1557   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1558        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1559          SemaRef.getLangOpts().OpenMPUseTLS &&
1560          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1561       (VD && VD->getStorageClass() == SC_Register &&
1562        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1563     DVar.RefExpr = buildDeclRefExpr(
1564         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1565     DVar.CKind = OMPC_threadprivate;
1566     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1567     return DVar;
1568   }
1569   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1570       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1571       !isLoopControlVariable(D).first) {
1572     const_iterator IterTarget =
1573         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1574           return isOpenMPTargetExecutionDirective(Data.Directive);
1575         });
1576     if (IterTarget != end()) {
1577       const_iterator ParentIterTarget = IterTarget + 1;
1578       for (const_iterator Iter = begin();
1579            Iter != ParentIterTarget; ++Iter) {
1580         if (isOpenMPLocal(VD, Iter)) {
1581           DVar.RefExpr =
1582               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1583                                D->getLocation());
1584           DVar.CKind = OMPC_threadprivate;
1585           return DVar;
1586         }
1587       }
1588       if (!isClauseParsingMode() || IterTarget != begin()) {
1589         auto DSAIter = IterTarget->SharingMap.find(D);
1590         if (DSAIter != IterTarget->SharingMap.end() &&
1591             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1592           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1593           DVar.CKind = OMPC_threadprivate;
1594           return DVar;
1595         }
1596         const_iterator End = end();
1597         if (!SemaRef.isOpenMPCapturedByRef(
1598                 D, std::distance(ParentIterTarget, End),
1599                 /*OpenMPCaptureLevel=*/0)) {
1600           DVar.RefExpr =
1601               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1602                                IterTarget->ConstructLoc);
1603           DVar.CKind = OMPC_threadprivate;
1604           return DVar;
1605         }
1606       }
1607     }
1608   }
1609 
1610   if (isStackEmpty())
1611     // Not in OpenMP execution region and top scope was already checked.
1612     return DVar;
1613 
1614   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1615   // in a Construct, C/C++, predetermined, p.4]
1616   //  Static data members are shared.
1617   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1618   // in a Construct, C/C++, predetermined, p.7]
1619   //  Variables with static storage duration that are declared in a scope
1620   //  inside the construct are shared.
1621   if (VD && VD->isStaticDataMember()) {
1622     // Check for explicitly specified attributes.
1623     const_iterator I = begin();
1624     const_iterator EndI = end();
1625     if (FromParent && I != EndI)
1626       ++I;
1627     if (I != EndI) {
1628       auto It = I->SharingMap.find(D);
1629       if (It != I->SharingMap.end()) {
1630         const DSAInfo &Data = It->getSecond();
1631         DVar.RefExpr = Data.RefExpr.getPointer();
1632         DVar.PrivateCopy = Data.PrivateCopy;
1633         DVar.CKind = Data.Attributes;
1634         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1635         DVar.DKind = I->Directive;
1636         DVar.Modifier = Data.Modifier;
1637         return DVar;
1638       }
1639     }
1640 
1641     DVar.CKind = OMPC_shared;
1642     return DVar;
1643   }
1644 
1645   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1646   // The predetermined shared attribute for const-qualified types having no
1647   // mutable members was removed after OpenMP 3.1.
1648   if (SemaRef.LangOpts.OpenMP <= 31) {
1649     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1650     // in a Construct, C/C++, predetermined, p.6]
1651     //  Variables with const qualified type having no mutable member are
1652     //  shared.
1653     if (isConstNotMutableType(SemaRef, D->getType())) {
1654       // Variables with const-qualified type having no mutable member may be
1655       // listed in a firstprivate clause, even if they are static data members.
1656       DSAVarData DVarTemp = hasInnermostDSA(
1657           D,
1658           [](OpenMPClauseKind C) {
1659             return C == OMPC_firstprivate || C == OMPC_shared;
1660           },
1661           MatchesAlways, FromParent);
1662       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1663         return DVarTemp;
1664 
1665       DVar.CKind = OMPC_shared;
1666       return DVar;
1667     }
1668   }
1669 
1670   // Explicitly specified attributes and local variables with predetermined
1671   // attributes.
1672   const_iterator I = begin();
1673   const_iterator EndI = end();
1674   if (FromParent && I != EndI)
1675     ++I;
1676   if (I == EndI)
1677     return DVar;
1678   auto It = I->SharingMap.find(D);
1679   if (It != I->SharingMap.end()) {
1680     const DSAInfo &Data = It->getSecond();
1681     DVar.RefExpr = Data.RefExpr.getPointer();
1682     DVar.PrivateCopy = Data.PrivateCopy;
1683     DVar.CKind = Data.Attributes;
1684     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1685     DVar.DKind = I->Directive;
1686     DVar.Modifier = Data.Modifier;
1687   }
1688 
1689   return DVar;
1690 }
1691 
1692 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1693                                                         bool FromParent) const {
1694   if (isStackEmpty()) {
1695     const_iterator I;
1696     return getDSA(I, D);
1697   }
1698   D = getCanonicalDecl(D);
1699   const_iterator StartI = begin();
1700   const_iterator EndI = end();
1701   if (FromParent && StartI != EndI)
1702     ++StartI;
1703   return getDSA(StartI, D);
1704 }
1705 
1706 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1707                                                         unsigned Level) const {
1708   if (getStackSize() <= Level)
1709     return DSAVarData();
1710   D = getCanonicalDecl(D);
1711   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1712   return getDSA(StartI, D);
1713 }
1714 
1715 const DSAStackTy::DSAVarData
1716 DSAStackTy::hasDSA(ValueDecl *D,
1717                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1718                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1719                    bool FromParent) const {
1720   if (isStackEmpty())
1721     return {};
1722   D = getCanonicalDecl(D);
1723   const_iterator I = begin();
1724   const_iterator EndI = end();
1725   if (FromParent && I != EndI)
1726     ++I;
1727   for (; I != EndI; ++I) {
1728     if (!DPred(I->Directive) &&
1729         !isImplicitOrExplicitTaskingRegion(I->Directive))
1730       continue;
1731     const_iterator NewI = I;
1732     DSAVarData DVar = getDSA(NewI, D);
1733     if (I == NewI && CPred(DVar.CKind))
1734       return DVar;
1735   }
1736   return {};
1737 }
1738 
1739 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1740     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1741     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1742     bool FromParent) const {
1743   if (isStackEmpty())
1744     return {};
1745   D = getCanonicalDecl(D);
1746   const_iterator StartI = begin();
1747   const_iterator EndI = end();
1748   if (FromParent && StartI != EndI)
1749     ++StartI;
1750   if (StartI == EndI || !DPred(StartI->Directive))
1751     return {};
1752   const_iterator NewI = StartI;
1753   DSAVarData DVar = getDSA(NewI, D);
1754   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1755 }
1756 
1757 bool DSAStackTy::hasExplicitDSA(
1758     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1759     unsigned Level, bool NotLastprivate) const {
1760   if (getStackSize() <= Level)
1761     return false;
1762   D = getCanonicalDecl(D);
1763   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1764   auto I = StackElem.SharingMap.find(D);
1765   if (I != StackElem.SharingMap.end() &&
1766       I->getSecond().RefExpr.getPointer() &&
1767       CPred(I->getSecond().Attributes) &&
1768       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1769     return true;
1770   // Check predetermined rules for the loop control variables.
1771   auto LI = StackElem.LCVMap.find(D);
1772   if (LI != StackElem.LCVMap.end())
1773     return CPred(OMPC_private);
1774   return false;
1775 }
1776 
1777 bool DSAStackTy::hasExplicitDirective(
1778     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1779     unsigned Level) const {
1780   if (getStackSize() <= Level)
1781     return false;
1782   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1783   return DPred(StackElem.Directive);
1784 }
1785 
1786 bool DSAStackTy::hasDirective(
1787     const llvm::function_ref<bool(OpenMPDirectiveKind,
1788                                   const DeclarationNameInfo &, SourceLocation)>
1789         DPred,
1790     bool FromParent) const {
1791   // We look only in the enclosing region.
1792   size_t Skip = FromParent ? 2 : 1;
1793   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1794        I != E; ++I) {
1795     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1796       return true;
1797   }
1798   return false;
1799 }
1800 
1801 void Sema::InitDataSharingAttributesStack() {
1802   VarDataSharingAttributesStack = new DSAStackTy(*this);
1803 }
1804 
1805 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1806 
1807 void Sema::pushOpenMPFunctionRegion() {
1808   DSAStack->pushFunction();
1809 }
1810 
1811 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1812   DSAStack->popFunction(OldFSI);
1813 }
1814 
1815 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1816   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1817          "Expected OpenMP device compilation.");
1818   return !S.isInOpenMPTargetExecutionDirective() &&
1819          !S.isInOpenMPDeclareTargetContext();
1820 }
1821 
1822 namespace {
1823 /// Status of the function emission on the host/device.
1824 enum class FunctionEmissionStatus {
1825   Emitted,
1826   Discarded,
1827   Unknown,
1828 };
1829 } // anonymous namespace
1830 
1831 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1832                                                      unsigned DiagID) {
1833   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1834          "Expected OpenMP device compilation.");
1835 
1836   FunctionDecl *FD = getCurFunctionDecl();
1837   DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1838   if (FD) {
1839     FunctionEmissionStatus FES = getEmissionStatus(FD);
1840     switch (FES) {
1841     case FunctionEmissionStatus::Emitted:
1842       Kind = DeviceDiagBuilder::K_Immediate;
1843       break;
1844     case FunctionEmissionStatus::Unknown:
1845       Kind = isOpenMPDeviceDelayedContext(*this)
1846                  ? DeviceDiagBuilder::K_Deferred
1847                  : DeviceDiagBuilder::K_Immediate;
1848       break;
1849     case FunctionEmissionStatus::TemplateDiscarded:
1850     case FunctionEmissionStatus::OMPDiscarded:
1851       Kind = DeviceDiagBuilder::K_Nop;
1852       break;
1853     case FunctionEmissionStatus::CUDADiscarded:
1854       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1855       break;
1856     }
1857   }
1858 
1859   return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1860 }
1861 
1862 Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1863                                                    unsigned DiagID) {
1864   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1865          "Expected OpenMP host compilation.");
1866   FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1867   DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1868   switch (FES) {
1869   case FunctionEmissionStatus::Emitted:
1870     Kind = DeviceDiagBuilder::K_Immediate;
1871     break;
1872   case FunctionEmissionStatus::Unknown:
1873     Kind = DeviceDiagBuilder::K_Deferred;
1874     break;
1875   case FunctionEmissionStatus::TemplateDiscarded:
1876   case FunctionEmissionStatus::OMPDiscarded:
1877   case FunctionEmissionStatus::CUDADiscarded:
1878     Kind = DeviceDiagBuilder::K_Nop;
1879     break;
1880   }
1881 
1882   return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1883 }
1884 
1885 static OpenMPDefaultmapClauseKind
1886 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1887   if (LO.OpenMP <= 45) {
1888     if (VD->getType().getNonReferenceType()->isScalarType())
1889       return OMPC_DEFAULTMAP_scalar;
1890     return OMPC_DEFAULTMAP_aggregate;
1891   }
1892   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1893     return OMPC_DEFAULTMAP_pointer;
1894   if (VD->getType().getNonReferenceType()->isScalarType())
1895     return OMPC_DEFAULTMAP_scalar;
1896   return OMPC_DEFAULTMAP_aggregate;
1897 }
1898 
1899 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1900                                  unsigned OpenMPCaptureLevel) const {
1901   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1902 
1903   ASTContext &Ctx = getASTContext();
1904   bool IsByRef = true;
1905 
1906   // Find the directive that is associated with the provided scope.
1907   D = cast<ValueDecl>(D->getCanonicalDecl());
1908   QualType Ty = D->getType();
1909 
1910   bool IsVariableUsedInMapClause = false;
1911   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1912     // This table summarizes how a given variable should be passed to the device
1913     // given its type and the clauses where it appears. This table is based on
1914     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1915     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1916     //
1917     // =========================================================================
1918     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1919     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1920     // =========================================================================
1921     // | scl  |               |     |       |       -       |          | bycopy|
1922     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1923     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1924     // | scl  |       x       |     |       |       -       |          | byref |
1925     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1926     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1927     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1928     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1929     //
1930     // | agg  |      n.a.     |     |       |       -       |          | byref |
1931     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1932     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1933     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1934     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1935     //
1936     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1937     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1938     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1939     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1940     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1941     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1942     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1943     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1944     // =========================================================================
1945     // Legend:
1946     //  scl - scalar
1947     //  ptr - pointer
1948     //  agg - aggregate
1949     //  x - applies
1950     //  - - invalid in this combination
1951     //  [] - mapped with an array section
1952     //  byref - should be mapped by reference
1953     //  byval - should be mapped by value
1954     //  null - initialize a local variable to null on the device
1955     //
1956     // Observations:
1957     //  - All scalar declarations that show up in a map clause have to be passed
1958     //    by reference, because they may have been mapped in the enclosing data
1959     //    environment.
1960     //  - If the scalar value does not fit the size of uintptr, it has to be
1961     //    passed by reference, regardless the result in the table above.
1962     //  - For pointers mapped by value that have either an implicit map or an
1963     //    array section, the runtime library may pass the NULL value to the
1964     //    device instead of the value passed to it by the compiler.
1965 
1966     if (Ty->isReferenceType())
1967       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1968 
1969     // Locate map clauses and see if the variable being captured is referred to
1970     // in any of those clauses. Here we only care about variables, not fields,
1971     // because fields are part of aggregates.
1972     bool IsVariableAssociatedWithSection = false;
1973 
1974     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1975         D, Level,
1976         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1977             OMPClauseMappableExprCommon::MappableExprComponentListRef
1978                 MapExprComponents,
1979             OpenMPClauseKind WhereFoundClauseKind) {
1980           // Only the map clause information influences how a variable is
1981           // captured. E.g. is_device_ptr does not require changing the default
1982           // behavior.
1983           if (WhereFoundClauseKind != OMPC_map)
1984             return false;
1985 
1986           auto EI = MapExprComponents.rbegin();
1987           auto EE = MapExprComponents.rend();
1988 
1989           assert(EI != EE && "Invalid map expression!");
1990 
1991           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1992             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1993 
1994           ++EI;
1995           if (EI == EE)
1996             return false;
1997 
1998           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1999               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2000               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2001               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2002             IsVariableAssociatedWithSection = true;
2003             // There is nothing more we need to know about this variable.
2004             return true;
2005           }
2006 
2007           // Keep looking for more map info.
2008           return false;
2009         });
2010 
2011     if (IsVariableUsedInMapClause) {
2012       // If variable is identified in a map clause it is always captured by
2013       // reference except if it is a pointer that is dereferenced somehow.
2014       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2015     } else {
2016       // By default, all the data that has a scalar type is mapped by copy
2017       // (except for reduction variables).
2018       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2019       IsByRef =
2020           (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2021            !Ty->isAnyPointerType()) ||
2022           !Ty->isScalarType() ||
2023           DSAStack->isDefaultmapCapturedByRef(
2024               Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2025           DSAStack->hasExplicitDSA(
2026               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
2027     }
2028   }
2029 
2030   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2031     IsByRef =
2032         ((IsVariableUsedInMapClause &&
2033           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2034               OMPD_target) ||
2035          !(DSAStack->hasExplicitDSA(
2036                D,
2037                [](OpenMPClauseKind K) -> bool {
2038                  return K == OMPC_firstprivate;
2039                },
2040                Level, /*NotLastprivate=*/true) ||
2041            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2042         // If the variable is artificial and must be captured by value - try to
2043         // capture by value.
2044         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2045           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
2046   }
2047 
2048   // When passing data by copy, we need to make sure it fits the uintptr size
2049   // and alignment, because the runtime library only deals with uintptr types.
2050   // If it does not fit the uintptr size, we need to pass the data by reference
2051   // instead.
2052   if (!IsByRef &&
2053       (Ctx.getTypeSizeInChars(Ty) >
2054            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2055        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2056     IsByRef = true;
2057   }
2058 
2059   return IsByRef;
2060 }
2061 
2062 unsigned Sema::getOpenMPNestingLevel() const {
2063   assert(getLangOpts().OpenMP);
2064   return DSAStack->getNestingLevel();
2065 }
2066 
2067 bool Sema::isInOpenMPTargetExecutionDirective() const {
2068   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2069           !DSAStack->isClauseParsingMode()) ||
2070          DSAStack->hasDirective(
2071              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2072                 SourceLocation) -> bool {
2073                return isOpenMPTargetExecutionDirective(K);
2074              },
2075              false);
2076 }
2077 
2078 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2079                                     unsigned StopAt) {
2080   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2081   D = getCanonicalDecl(D);
2082 
2083   auto *VD = dyn_cast<VarDecl>(D);
2084   // Do not capture constexpr variables.
2085   if (VD && VD->isConstexpr())
2086     return nullptr;
2087 
2088   // If we want to determine whether the variable should be captured from the
2089   // perspective of the current capturing scope, and we've already left all the
2090   // capturing scopes of the top directive on the stack, check from the
2091   // perspective of its parent directive (if any) instead.
2092   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2093       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2094 
2095   // If we are attempting to capture a global variable in a directive with
2096   // 'target' we return true so that this global is also mapped to the device.
2097   //
2098   if (VD && !VD->hasLocalStorage() &&
2099       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2100     if (isInOpenMPDeclareTargetContext()) {
2101       // Try to mark variable as declare target if it is used in capturing
2102       // regions.
2103       if (LangOpts.OpenMP <= 45 &&
2104           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2105         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2106       return nullptr;
2107     } else if (isInOpenMPTargetExecutionDirective()) {
2108       // If the declaration is enclosed in a 'declare target' directive,
2109       // then it should not be captured.
2110       //
2111       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2112         return nullptr;
2113       CapturedRegionScopeInfo *CSI = nullptr;
2114       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2115                llvm::reverse(FunctionScopes),
2116                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2117         if (!isa<CapturingScopeInfo>(FSI))
2118           return nullptr;
2119         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2120           if (RSI->CapRegionKind == CR_OpenMP) {
2121             CSI = RSI;
2122             break;
2123           }
2124       }
2125       SmallVector<OpenMPDirectiveKind, 4> Regions;
2126       getOpenMPCaptureRegions(Regions,
2127                               DSAStack->getDirective(CSI->OpenMPLevel));
2128       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2129         return VD;
2130     }
2131   }
2132 
2133   if (CheckScopeInfo) {
2134     bool OpenMPFound = false;
2135     for (unsigned I = StopAt + 1; I > 0; --I) {
2136       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2137       if(!isa<CapturingScopeInfo>(FSI))
2138         return nullptr;
2139       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2140         if (RSI->CapRegionKind == CR_OpenMP) {
2141           OpenMPFound = true;
2142           break;
2143         }
2144     }
2145     if (!OpenMPFound)
2146       return nullptr;
2147   }
2148 
2149   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2150       (!DSAStack->isClauseParsingMode() ||
2151        DSAStack->getParentDirective() != OMPD_unknown)) {
2152     auto &&Info = DSAStack->isLoopControlVariable(D);
2153     if (Info.first ||
2154         (VD && VD->hasLocalStorage() &&
2155          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2156         (VD && DSAStack->isForceVarCapturing()))
2157       return VD ? VD : Info.second;
2158     DSAStackTy::DSAVarData DVarTop =
2159         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2160     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind))
2161       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2162     // Threadprivate variables must not be captured.
2163     if (isOpenMPThreadPrivate(DVarTop.CKind))
2164       return nullptr;
2165     // The variable is not private or it is the variable in the directive with
2166     // default(none) clause and not used in any clause.
2167     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2168         D, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
2169         DSAStack->isClauseParsingMode());
2170     // Global shared must not be captured.
2171     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2172         (DSAStack->getDefaultDSA() != DSA_none || DVarTop.CKind == OMPC_shared))
2173       return nullptr;
2174     if (DVarPrivate.CKind != OMPC_unknown ||
2175         (VD && DSAStack->getDefaultDSA() == DSA_none))
2176       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2177   }
2178   return nullptr;
2179 }
2180 
2181 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2182                                         unsigned Level) const {
2183   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2184 }
2185 
2186 void Sema::startOpenMPLoop() {
2187   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2188   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2189     DSAStack->loopInit();
2190 }
2191 
2192 void Sema::startOpenMPCXXRangeFor() {
2193   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2194   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2195     DSAStack->resetPossibleLoopCounter();
2196     DSAStack->loopStart();
2197   }
2198 }
2199 
2200 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2201                                            unsigned CapLevel) const {
2202   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2203   if (DSAStack->hasExplicitDirective(
2204           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2205           Level)) {
2206     bool IsTriviallyCopyable =
2207         D->getType().getNonReferenceType().isTriviallyCopyableType(Context);
2208     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2209     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2210     getOpenMPCaptureRegions(CaptureRegions, DKind);
2211     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2212         (IsTriviallyCopyable ||
2213          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2214       if (DSAStack->hasExplicitDSA(
2215               D, [](OpenMPClauseKind K) { return K == OMPC_firstprivate; },
2216               Level, /*NotLastprivate=*/true))
2217         return OMPC_firstprivate;
2218       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2219       if (DVar.CKind != OMPC_shared &&
2220           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2221         DSAStack->addImplicitTaskFirstprivate(Level, D);
2222         return OMPC_firstprivate;
2223       }
2224     }
2225   }
2226   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2227     if (DSAStack->getAssociatedLoops() > 0 &&
2228         !DSAStack->isLoopStarted()) {
2229       DSAStack->resetPossibleLoopCounter(D);
2230       DSAStack->loopStart();
2231       return OMPC_private;
2232     }
2233     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2234          DSAStack->isLoopControlVariable(D).first) &&
2235         !DSAStack->hasExplicitDSA(
2236             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2237         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2238       return OMPC_private;
2239   }
2240   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2241     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2242         DSAStack->isForceVarCapturing() &&
2243         !DSAStack->hasExplicitDSA(
2244             D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2245       return OMPC_private;
2246   }
2247   // User-defined allocators are private since they must be defined in the
2248   // context of target region.
2249   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2250       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2251           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2252           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2253     return OMPC_private;
2254   return (DSAStack->hasExplicitDSA(
2255               D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
2256           (DSAStack->isClauseParsingMode() &&
2257            DSAStack->getClauseParsingMode() == OMPC_private) ||
2258           // Consider taskgroup reduction descriptor variable a private
2259           // to avoid possible capture in the region.
2260           (DSAStack->hasExplicitDirective(
2261                [](OpenMPDirectiveKind K) {
2262                  return K == OMPD_taskgroup ||
2263                         ((isOpenMPParallelDirective(K) ||
2264                           isOpenMPWorksharingDirective(K)) &&
2265                          !isOpenMPSimdDirective(K));
2266                },
2267                Level) &&
2268            DSAStack->isTaskgroupReductionRef(D, Level)))
2269              ? OMPC_private
2270              : OMPC_unknown;
2271 }
2272 
2273 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2274                                 unsigned Level) {
2275   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2276   D = getCanonicalDecl(D);
2277   OpenMPClauseKind OMPC = OMPC_unknown;
2278   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2279     const unsigned NewLevel = I - 1;
2280     if (DSAStack->hasExplicitDSA(D,
2281                                  [&OMPC](const OpenMPClauseKind K) {
2282                                    if (isOpenMPPrivate(K)) {
2283                                      OMPC = K;
2284                                      return true;
2285                                    }
2286                                    return false;
2287                                  },
2288                                  NewLevel))
2289       break;
2290     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2291             D, NewLevel,
2292             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2293                OpenMPClauseKind) { return true; })) {
2294       OMPC = OMPC_map;
2295       break;
2296     }
2297     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2298                                        NewLevel)) {
2299       OMPC = OMPC_map;
2300       if (DSAStack->mustBeFirstprivateAtLevel(
2301               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2302         OMPC = OMPC_firstprivate;
2303       break;
2304     }
2305   }
2306   if (OMPC != OMPC_unknown)
2307     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2308 }
2309 
2310 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2311                                       unsigned CaptureLevel) const {
2312   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2313   // Return true if the current level is no longer enclosed in a target region.
2314 
2315   SmallVector<OpenMPDirectiveKind, 4> Regions;
2316   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2317   const auto *VD = dyn_cast<VarDecl>(D);
2318   return VD && !VD->hasLocalStorage() &&
2319          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2320                                         Level) &&
2321          Regions[CaptureLevel] != OMPD_task;
2322 }
2323 
2324 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2325                                       unsigned CaptureLevel) const {
2326   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2327   // Return true if the current level is no longer enclosed in a target region.
2328 
2329   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2330     if (!VD->hasLocalStorage()) {
2331       DSAStackTy::DSAVarData TopDVar =
2332           DSAStack->getTopDSA(D, /*FromParent=*/false);
2333       unsigned NumLevels =
2334           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2335       if (Level == 0)
2336         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2337       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level - 1);
2338       return DVar.CKind != OMPC_shared ||
2339              isOpenMPGlobalCapturedDecl(
2340                  D, Level - 1,
2341                  getOpenMPCaptureLevels(DSAStack->getDirective(Level - 1)) - 1);
2342     }
2343   }
2344   return true;
2345 }
2346 
2347 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2348 
2349 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2350                                           OMPTraitInfo &TI) {
2351   if (!OMPDeclareVariantScopes.empty()) {
2352     Diag(Loc, diag::warn_nested_declare_variant);
2353     return;
2354   }
2355   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2356 }
2357 
2358 void Sema::ActOnOpenMPEndDeclareVariant() {
2359   assert(isInOpenMPDeclareVariantScope() &&
2360          "Not in OpenMP declare variant scope!");
2361 
2362   OMPDeclareVariantScopes.pop_back();
2363 }
2364 
2365 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2366                                          const FunctionDecl *Callee,
2367                                          SourceLocation Loc) {
2368   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2369   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2370       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2371   // Ignore host functions during device analyzis.
2372   if (LangOpts.OpenMPIsDevice && DevTy &&
2373       *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2374     return;
2375   // Ignore nohost functions during host analyzis.
2376   if (!LangOpts.OpenMPIsDevice && DevTy &&
2377       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2378     return;
2379   const FunctionDecl *FD = Callee->getMostRecentDecl();
2380   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2381   if (LangOpts.OpenMPIsDevice && DevTy &&
2382       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2383     // Diagnose host function called during device codegen.
2384     StringRef HostDevTy =
2385         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2386     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2387     Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2388          diag::note_omp_marked_device_type_here)
2389         << HostDevTy;
2390     return;
2391   }
2392       if (!LangOpts.OpenMPIsDevice && DevTy &&
2393           *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2394         // Diagnose nohost function called during host codegen.
2395         StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2396             OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2397         Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2398         Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2399              diag::note_omp_marked_device_type_here)
2400             << NoHostDevTy;
2401       }
2402 }
2403 
2404 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2405                                const DeclarationNameInfo &DirName,
2406                                Scope *CurScope, SourceLocation Loc) {
2407   DSAStack->push(DKind, DirName, CurScope, Loc);
2408   PushExpressionEvaluationContext(
2409       ExpressionEvaluationContext::PotentiallyEvaluated);
2410 }
2411 
2412 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2413   DSAStack->setClauseParsingMode(K);
2414 }
2415 
2416 void Sema::EndOpenMPClause() {
2417   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2418 }
2419 
2420 static std::pair<ValueDecl *, bool>
2421 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2422                SourceRange &ERange, bool AllowArraySection = false);
2423 
2424 /// Check consistency of the reduction clauses.
2425 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2426                                   ArrayRef<OMPClause *> Clauses) {
2427   bool InscanFound = false;
2428   SourceLocation InscanLoc;
2429   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2430   // A reduction clause without the inscan reduction-modifier may not appear on
2431   // a construct on which a reduction clause with the inscan reduction-modifier
2432   // appears.
2433   for (OMPClause *C : Clauses) {
2434     if (C->getClauseKind() != OMPC_reduction)
2435       continue;
2436     auto *RC = cast<OMPReductionClause>(C);
2437     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2438       InscanFound = true;
2439       InscanLoc = RC->getModifierLoc();
2440       continue;
2441     }
2442     if (RC->getModifier() == OMPC_REDUCTION_task) {
2443       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2444       // A reduction clause with the task reduction-modifier may only appear on
2445       // a parallel construct, a worksharing construct or a combined or
2446       // composite construct for which any of the aforementioned constructs is a
2447       // constituent construct and simd or loop are not constituent constructs.
2448       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2449       if (!(isOpenMPParallelDirective(CurDir) ||
2450             isOpenMPWorksharingDirective(CurDir)) ||
2451           isOpenMPSimdDirective(CurDir))
2452         S.Diag(RC->getModifierLoc(),
2453                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2454       continue;
2455     }
2456   }
2457   if (InscanFound) {
2458     for (OMPClause *C : Clauses) {
2459       if (C->getClauseKind() != OMPC_reduction)
2460         continue;
2461       auto *RC = cast<OMPReductionClause>(C);
2462       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2463         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2464                    ? RC->getBeginLoc()
2465                    : RC->getModifierLoc(),
2466                diag::err_omp_inscan_reduction_expected);
2467         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2468         continue;
2469       }
2470       for (Expr *Ref : RC->varlists()) {
2471         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2472         SourceLocation ELoc;
2473         SourceRange ERange;
2474         Expr *SimpleRefExpr = Ref;
2475         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2476                                   /*AllowArraySection=*/true);
2477         ValueDecl *D = Res.first;
2478         if (!D)
2479           continue;
2480         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2481           S.Diag(Ref->getExprLoc(),
2482                  diag::err_omp_reduction_not_inclusive_exclusive)
2483               << Ref->getSourceRange();
2484         }
2485       }
2486     }
2487   }
2488 }
2489 
2490 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2491                                  ArrayRef<OMPClause *> Clauses);
2492 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2493                                  bool WithInit);
2494 
2495 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2496                               const ValueDecl *D,
2497                               const DSAStackTy::DSAVarData &DVar,
2498                               bool IsLoopIterVar = false);
2499 
2500 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2501   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2502   //  A variable of class type (or array thereof) that appears in a lastprivate
2503   //  clause requires an accessible, unambiguous default constructor for the
2504   //  class type, unless the list item is also specified in a firstprivate
2505   //  clause.
2506   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2507     for (OMPClause *C : D->clauses()) {
2508       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2509         SmallVector<Expr *, 8> PrivateCopies;
2510         for (Expr *DE : Clause->varlists()) {
2511           if (DE->isValueDependent() || DE->isTypeDependent()) {
2512             PrivateCopies.push_back(nullptr);
2513             continue;
2514           }
2515           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2516           auto *VD = cast<VarDecl>(DRE->getDecl());
2517           QualType Type = VD->getType().getNonReferenceType();
2518           const DSAStackTy::DSAVarData DVar =
2519               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2520           if (DVar.CKind == OMPC_lastprivate) {
2521             // Generate helper private variable and initialize it with the
2522             // default value. The address of the original variable is replaced
2523             // by the address of the new private variable in CodeGen. This new
2524             // variable is not added to IdResolver, so the code in the OpenMP
2525             // region uses original variable for proper diagnostics.
2526             VarDecl *VDPrivate = buildVarDecl(
2527                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2528                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2529             ActOnUninitializedDecl(VDPrivate);
2530             if (VDPrivate->isInvalidDecl()) {
2531               PrivateCopies.push_back(nullptr);
2532               continue;
2533             }
2534             PrivateCopies.push_back(buildDeclRefExpr(
2535                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2536           } else {
2537             // The variable is also a firstprivate, so initialization sequence
2538             // for private copy is generated already.
2539             PrivateCopies.push_back(nullptr);
2540           }
2541         }
2542         Clause->setPrivateCopies(PrivateCopies);
2543         continue;
2544       }
2545       // Finalize nontemporal clause by handling private copies, if any.
2546       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2547         SmallVector<Expr *, 8> PrivateRefs;
2548         for (Expr *RefExpr : Clause->varlists()) {
2549           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2550           SourceLocation ELoc;
2551           SourceRange ERange;
2552           Expr *SimpleRefExpr = RefExpr;
2553           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2554           if (Res.second)
2555             // It will be analyzed later.
2556             PrivateRefs.push_back(RefExpr);
2557           ValueDecl *D = Res.first;
2558           if (!D)
2559             continue;
2560 
2561           const DSAStackTy::DSAVarData DVar =
2562               DSAStack->getTopDSA(D, /*FromParent=*/false);
2563           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2564                                                  : SimpleRefExpr);
2565         }
2566         Clause->setPrivateRefs(PrivateRefs);
2567         continue;
2568       }
2569       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2570         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2571           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2572           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2573           if (!DRE)
2574             continue;
2575           ValueDecl *VD = DRE->getDecl();
2576           if (!VD || !isa<VarDecl>(VD))
2577             continue;
2578           DSAStackTy::DSAVarData DVar =
2579               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2580           // OpenMP [2.12.5, target Construct]
2581           // Memory allocators that appear in a uses_allocators clause cannot
2582           // appear in other data-sharing attribute clauses or data-mapping
2583           // attribute clauses in the same construct.
2584           Expr *MapExpr = nullptr;
2585           if (DVar.RefExpr ||
2586               DSAStack->checkMappableExprComponentListsForDecl(
2587                   VD, /*CurrentRegionOnly=*/true,
2588                   [VD, &MapExpr](
2589                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2590                           MapExprComponents,
2591                       OpenMPClauseKind C) {
2592                     auto MI = MapExprComponents.rbegin();
2593                     auto ME = MapExprComponents.rend();
2594                     if (MI != ME &&
2595                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2596                             VD->getCanonicalDecl()) {
2597                       MapExpr = MI->getAssociatedExpression();
2598                       return true;
2599                     }
2600                     return false;
2601                   })) {
2602             Diag(D.Allocator->getExprLoc(),
2603                  diag::err_omp_allocator_used_in_clauses)
2604                 << D.Allocator->getSourceRange();
2605             if (DVar.RefExpr)
2606               reportOriginalDsa(*this, DSAStack, VD, DVar);
2607             else
2608               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2609                   << MapExpr->getSourceRange();
2610           }
2611         }
2612         continue;
2613       }
2614     }
2615     // Check allocate clauses.
2616     if (!CurContext->isDependentContext())
2617       checkAllocateClauses(*this, DSAStack, D->clauses());
2618     checkReductionClauses(*this, DSAStack, D->clauses());
2619   }
2620 
2621   DSAStack->pop();
2622   DiscardCleanupsInEvaluationContext();
2623   PopExpressionEvaluationContext();
2624 }
2625 
2626 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2627                                      Expr *NumIterations, Sema &SemaRef,
2628                                      Scope *S, DSAStackTy *Stack);
2629 
2630 namespace {
2631 
2632 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2633 private:
2634   Sema &SemaRef;
2635 
2636 public:
2637   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2638   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2639     NamedDecl *ND = Candidate.getCorrectionDecl();
2640     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2641       return VD->hasGlobalStorage() &&
2642              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2643                                    SemaRef.getCurScope());
2644     }
2645     return false;
2646   }
2647 
2648   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2649     return std::make_unique<VarDeclFilterCCC>(*this);
2650   }
2651 
2652 };
2653 
2654 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2655 private:
2656   Sema &SemaRef;
2657 
2658 public:
2659   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2660   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2661     NamedDecl *ND = Candidate.getCorrectionDecl();
2662     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2663                isa<FunctionDecl>(ND))) {
2664       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2665                                    SemaRef.getCurScope());
2666     }
2667     return false;
2668   }
2669 
2670   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2671     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2672   }
2673 };
2674 
2675 } // namespace
2676 
2677 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2678                                          CXXScopeSpec &ScopeSpec,
2679                                          const DeclarationNameInfo &Id,
2680                                          OpenMPDirectiveKind Kind) {
2681   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2682   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2683 
2684   if (Lookup.isAmbiguous())
2685     return ExprError();
2686 
2687   VarDecl *VD;
2688   if (!Lookup.isSingleResult()) {
2689     VarDeclFilterCCC CCC(*this);
2690     if (TypoCorrection Corrected =
2691             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2692                         CTK_ErrorRecovery)) {
2693       diagnoseTypo(Corrected,
2694                    PDiag(Lookup.empty()
2695                              ? diag::err_undeclared_var_use_suggest
2696                              : diag::err_omp_expected_var_arg_suggest)
2697                        << Id.getName());
2698       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2699     } else {
2700       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2701                                        : diag::err_omp_expected_var_arg)
2702           << Id.getName();
2703       return ExprError();
2704     }
2705   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2706     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2707     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2708     return ExprError();
2709   }
2710   Lookup.suppressDiagnostics();
2711 
2712   // OpenMP [2.9.2, Syntax, C/C++]
2713   //   Variables must be file-scope, namespace-scope, or static block-scope.
2714   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2715     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2716         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2717     bool IsDecl =
2718         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2719     Diag(VD->getLocation(),
2720          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2721         << VD;
2722     return ExprError();
2723   }
2724 
2725   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2726   NamedDecl *ND = CanonicalVD;
2727   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2728   //   A threadprivate directive for file-scope variables must appear outside
2729   //   any definition or declaration.
2730   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2731       !getCurLexicalContext()->isTranslationUnit()) {
2732     Diag(Id.getLoc(), diag::err_omp_var_scope)
2733         << getOpenMPDirectiveName(Kind) << VD;
2734     bool IsDecl =
2735         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2736     Diag(VD->getLocation(),
2737          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2738         << VD;
2739     return ExprError();
2740   }
2741   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2742   //   A threadprivate directive for static class member variables must appear
2743   //   in the class definition, in the same scope in which the member
2744   //   variables are declared.
2745   if (CanonicalVD->isStaticDataMember() &&
2746       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2747     Diag(Id.getLoc(), diag::err_omp_var_scope)
2748         << getOpenMPDirectiveName(Kind) << VD;
2749     bool IsDecl =
2750         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2751     Diag(VD->getLocation(),
2752          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2753         << VD;
2754     return ExprError();
2755   }
2756   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2757   //   A threadprivate directive for namespace-scope variables must appear
2758   //   outside any definition or declaration other than the namespace
2759   //   definition itself.
2760   if (CanonicalVD->getDeclContext()->isNamespace() &&
2761       (!getCurLexicalContext()->isFileContext() ||
2762        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2763     Diag(Id.getLoc(), diag::err_omp_var_scope)
2764         << getOpenMPDirectiveName(Kind) << VD;
2765     bool IsDecl =
2766         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2767     Diag(VD->getLocation(),
2768          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2769         << VD;
2770     return ExprError();
2771   }
2772   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2773   //   A threadprivate directive for static block-scope variables must appear
2774   //   in the scope of the variable and not in a nested scope.
2775   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2776       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2777     Diag(Id.getLoc(), diag::err_omp_var_scope)
2778         << getOpenMPDirectiveName(Kind) << VD;
2779     bool IsDecl =
2780         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2781     Diag(VD->getLocation(),
2782          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2783         << VD;
2784     return ExprError();
2785   }
2786 
2787   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2788   //   A threadprivate directive must lexically precede all references to any
2789   //   of the variables in its list.
2790   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2791       !DSAStack->isThreadPrivate(VD)) {
2792     Diag(Id.getLoc(), diag::err_omp_var_used)
2793         << getOpenMPDirectiveName(Kind) << VD;
2794     return ExprError();
2795   }
2796 
2797   QualType ExprType = VD->getType().getNonReferenceType();
2798   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2799                              SourceLocation(), VD,
2800                              /*RefersToEnclosingVariableOrCapture=*/false,
2801                              Id.getLoc(), ExprType, VK_LValue);
2802 }
2803 
2804 Sema::DeclGroupPtrTy
2805 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2806                                         ArrayRef<Expr *> VarList) {
2807   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2808     CurContext->addDecl(D);
2809     return DeclGroupPtrTy::make(DeclGroupRef(D));
2810   }
2811   return nullptr;
2812 }
2813 
2814 namespace {
2815 class LocalVarRefChecker final
2816     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2817   Sema &SemaRef;
2818 
2819 public:
2820   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2821     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2822       if (VD->hasLocalStorage()) {
2823         SemaRef.Diag(E->getBeginLoc(),
2824                      diag::err_omp_local_var_in_threadprivate_init)
2825             << E->getSourceRange();
2826         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2827             << VD << VD->getSourceRange();
2828         return true;
2829       }
2830     }
2831     return false;
2832   }
2833   bool VisitStmt(const Stmt *S) {
2834     for (const Stmt *Child : S->children()) {
2835       if (Child && Visit(Child))
2836         return true;
2837     }
2838     return false;
2839   }
2840   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2841 };
2842 } // namespace
2843 
2844 OMPThreadPrivateDecl *
2845 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2846   SmallVector<Expr *, 8> Vars;
2847   for (Expr *RefExpr : VarList) {
2848     auto *DE = cast<DeclRefExpr>(RefExpr);
2849     auto *VD = cast<VarDecl>(DE->getDecl());
2850     SourceLocation ILoc = DE->getExprLoc();
2851 
2852     // Mark variable as used.
2853     VD->setReferenced();
2854     VD->markUsed(Context);
2855 
2856     QualType QType = VD->getType();
2857     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2858       // It will be analyzed later.
2859       Vars.push_back(DE);
2860       continue;
2861     }
2862 
2863     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2864     //   A threadprivate variable must not have an incomplete type.
2865     if (RequireCompleteType(ILoc, VD->getType(),
2866                             diag::err_omp_threadprivate_incomplete_type)) {
2867       continue;
2868     }
2869 
2870     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2871     //   A threadprivate variable must not have a reference type.
2872     if (VD->getType()->isReferenceType()) {
2873       Diag(ILoc, diag::err_omp_ref_type_arg)
2874           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2875       bool IsDecl =
2876           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2877       Diag(VD->getLocation(),
2878            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2879           << VD;
2880       continue;
2881     }
2882 
2883     // Check if this is a TLS variable. If TLS is not being supported, produce
2884     // the corresponding diagnostic.
2885     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2886          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2887            getLangOpts().OpenMPUseTLS &&
2888            getASTContext().getTargetInfo().isTLSSupported())) ||
2889         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2890          !VD->isLocalVarDecl())) {
2891       Diag(ILoc, diag::err_omp_var_thread_local)
2892           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2893       bool IsDecl =
2894           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2895       Diag(VD->getLocation(),
2896            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2897           << VD;
2898       continue;
2899     }
2900 
2901     // Check if initial value of threadprivate variable reference variable with
2902     // local storage (it is not supported by runtime).
2903     if (const Expr *Init = VD->getAnyInitializer()) {
2904       LocalVarRefChecker Checker(*this);
2905       if (Checker.Visit(Init))
2906         continue;
2907     }
2908 
2909     Vars.push_back(RefExpr);
2910     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2911     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2912         Context, SourceRange(Loc, Loc)));
2913     if (ASTMutationListener *ML = Context.getASTMutationListener())
2914       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2915   }
2916   OMPThreadPrivateDecl *D = nullptr;
2917   if (!Vars.empty()) {
2918     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2919                                      Vars);
2920     D->setAccess(AS_public);
2921   }
2922   return D;
2923 }
2924 
2925 static OMPAllocateDeclAttr::AllocatorTypeTy
2926 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2927   if (!Allocator)
2928     return OMPAllocateDeclAttr::OMPNullMemAlloc;
2929   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2930       Allocator->isInstantiationDependent() ||
2931       Allocator->containsUnexpandedParameterPack())
2932     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2933   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2934   const Expr *AE = Allocator->IgnoreParenImpCasts();
2935   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2936     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2937     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2938     llvm::FoldingSetNodeID AEId, DAEId;
2939     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2940     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2941     if (AEId == DAEId) {
2942       AllocatorKindRes = AllocatorKind;
2943       break;
2944     }
2945   }
2946   return AllocatorKindRes;
2947 }
2948 
2949 static bool checkPreviousOMPAllocateAttribute(
2950     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2951     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2952   if (!VD->hasAttr<OMPAllocateDeclAttr>())
2953     return false;
2954   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2955   Expr *PrevAllocator = A->getAllocator();
2956   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2957       getAllocatorKind(S, Stack, PrevAllocator);
2958   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2959   if (AllocatorsMatch &&
2960       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2961       Allocator && PrevAllocator) {
2962     const Expr *AE = Allocator->IgnoreParenImpCasts();
2963     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2964     llvm::FoldingSetNodeID AEId, PAEId;
2965     AE->Profile(AEId, S.Context, /*Canonical=*/true);
2966     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2967     AllocatorsMatch = AEId == PAEId;
2968   }
2969   if (!AllocatorsMatch) {
2970     SmallString<256> AllocatorBuffer;
2971     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2972     if (Allocator)
2973       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2974     SmallString<256> PrevAllocatorBuffer;
2975     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2976     if (PrevAllocator)
2977       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2978                                  S.getPrintingPolicy());
2979 
2980     SourceLocation AllocatorLoc =
2981         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2982     SourceRange AllocatorRange =
2983         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2984     SourceLocation PrevAllocatorLoc =
2985         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2986     SourceRange PrevAllocatorRange =
2987         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2988     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2989         << (Allocator ? 1 : 0) << AllocatorStream.str()
2990         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2991         << AllocatorRange;
2992     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2993         << PrevAllocatorRange;
2994     return true;
2995   }
2996   return false;
2997 }
2998 
2999 static void
3000 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3001                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3002                           Expr *Allocator, SourceRange SR) {
3003   if (VD->hasAttr<OMPAllocateDeclAttr>())
3004     return;
3005   if (Allocator &&
3006       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3007        Allocator->isInstantiationDependent() ||
3008        Allocator->containsUnexpandedParameterPack()))
3009     return;
3010   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3011                                                 Allocator, SR);
3012   VD->addAttr(A);
3013   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3014     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3015 }
3016 
3017 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3018     SourceLocation Loc, ArrayRef<Expr *> VarList,
3019     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3020   assert(Clauses.size() <= 1 && "Expected at most one clause.");
3021   Expr *Allocator = nullptr;
3022   if (Clauses.empty()) {
3023     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3024     // allocate directives that appear in a target region must specify an
3025     // allocator clause unless a requires directive with the dynamic_allocators
3026     // clause is present in the same compilation unit.
3027     if (LangOpts.OpenMPIsDevice &&
3028         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3029       targetDiag(Loc, diag::err_expected_allocator_clause);
3030   } else {
3031     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3032   }
3033   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3034       getAllocatorKind(*this, DSAStack, Allocator);
3035   SmallVector<Expr *, 8> Vars;
3036   for (Expr *RefExpr : VarList) {
3037     auto *DE = cast<DeclRefExpr>(RefExpr);
3038     auto *VD = cast<VarDecl>(DE->getDecl());
3039 
3040     // Check if this is a TLS variable or global register.
3041     if (VD->getTLSKind() != VarDecl::TLS_None ||
3042         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3043         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3044          !VD->isLocalVarDecl()))
3045       continue;
3046 
3047     // If the used several times in the allocate directive, the same allocator
3048     // must be used.
3049     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3050                                           AllocatorKind, Allocator))
3051       continue;
3052 
3053     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3054     // If a list item has a static storage type, the allocator expression in the
3055     // allocator clause must be a constant expression that evaluates to one of
3056     // the predefined memory allocator values.
3057     if (Allocator && VD->hasGlobalStorage()) {
3058       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3059         Diag(Allocator->getExprLoc(),
3060              diag::err_omp_expected_predefined_allocator)
3061             << Allocator->getSourceRange();
3062         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3063                       VarDecl::DeclarationOnly;
3064         Diag(VD->getLocation(),
3065              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3066             << VD;
3067         continue;
3068       }
3069     }
3070 
3071     Vars.push_back(RefExpr);
3072     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3073                               DE->getSourceRange());
3074   }
3075   if (Vars.empty())
3076     return nullptr;
3077   if (!Owner)
3078     Owner = getCurLexicalContext();
3079   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3080   D->setAccess(AS_public);
3081   Owner->addDecl(D);
3082   return DeclGroupPtrTy::make(DeclGroupRef(D));
3083 }
3084 
3085 Sema::DeclGroupPtrTy
3086 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3087                                    ArrayRef<OMPClause *> ClauseList) {
3088   OMPRequiresDecl *D = nullptr;
3089   if (!CurContext->isFileContext()) {
3090     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3091   } else {
3092     D = CheckOMPRequiresDecl(Loc, ClauseList);
3093     if (D) {
3094       CurContext->addDecl(D);
3095       DSAStack->addRequiresDecl(D);
3096     }
3097   }
3098   return DeclGroupPtrTy::make(DeclGroupRef(D));
3099 }
3100 
3101 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3102                                             ArrayRef<OMPClause *> ClauseList) {
3103   /// For target specific clauses, the requires directive cannot be
3104   /// specified after the handling of any of the target regions in the
3105   /// current compilation unit.
3106   ArrayRef<SourceLocation> TargetLocations =
3107       DSAStack->getEncounteredTargetLocs();
3108   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3109   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3110     for (const OMPClause *CNew : ClauseList) {
3111       // Check if any of the requires clauses affect target regions.
3112       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3113           isa<OMPUnifiedAddressClause>(CNew) ||
3114           isa<OMPReverseOffloadClause>(CNew) ||
3115           isa<OMPDynamicAllocatorsClause>(CNew)) {
3116         Diag(Loc, diag::err_omp_directive_before_requires)
3117             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3118         for (SourceLocation TargetLoc : TargetLocations) {
3119           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3120               << "target";
3121         }
3122       } else if (!AtomicLoc.isInvalid() &&
3123                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3124         Diag(Loc, diag::err_omp_directive_before_requires)
3125             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3126         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3127             << "atomic";
3128       }
3129     }
3130   }
3131 
3132   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3133     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3134                                    ClauseList);
3135   return nullptr;
3136 }
3137 
3138 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3139                               const ValueDecl *D,
3140                               const DSAStackTy::DSAVarData &DVar,
3141                               bool IsLoopIterVar) {
3142   if (DVar.RefExpr) {
3143     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3144         << getOpenMPClauseName(DVar.CKind);
3145     return;
3146   }
3147   enum {
3148     PDSA_StaticMemberShared,
3149     PDSA_StaticLocalVarShared,
3150     PDSA_LoopIterVarPrivate,
3151     PDSA_LoopIterVarLinear,
3152     PDSA_LoopIterVarLastprivate,
3153     PDSA_ConstVarShared,
3154     PDSA_GlobalVarShared,
3155     PDSA_TaskVarFirstprivate,
3156     PDSA_LocalVarPrivate,
3157     PDSA_Implicit
3158   } Reason = PDSA_Implicit;
3159   bool ReportHint = false;
3160   auto ReportLoc = D->getLocation();
3161   auto *VD = dyn_cast<VarDecl>(D);
3162   if (IsLoopIterVar) {
3163     if (DVar.CKind == OMPC_private)
3164       Reason = PDSA_LoopIterVarPrivate;
3165     else if (DVar.CKind == OMPC_lastprivate)
3166       Reason = PDSA_LoopIterVarLastprivate;
3167     else
3168       Reason = PDSA_LoopIterVarLinear;
3169   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3170              DVar.CKind == OMPC_firstprivate) {
3171     Reason = PDSA_TaskVarFirstprivate;
3172     ReportLoc = DVar.ImplicitDSALoc;
3173   } else if (VD && VD->isStaticLocal())
3174     Reason = PDSA_StaticLocalVarShared;
3175   else if (VD && VD->isStaticDataMember())
3176     Reason = PDSA_StaticMemberShared;
3177   else if (VD && VD->isFileVarDecl())
3178     Reason = PDSA_GlobalVarShared;
3179   else if (D->getType().isConstant(SemaRef.getASTContext()))
3180     Reason = PDSA_ConstVarShared;
3181   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3182     ReportHint = true;
3183     Reason = PDSA_LocalVarPrivate;
3184   }
3185   if (Reason != PDSA_Implicit) {
3186     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3187         << Reason << ReportHint
3188         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3189   } else if (DVar.ImplicitDSALoc.isValid()) {
3190     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3191         << getOpenMPClauseName(DVar.CKind);
3192   }
3193 }
3194 
3195 static OpenMPMapClauseKind
3196 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3197                              bool IsAggregateOrDeclareTarget) {
3198   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3199   switch (M) {
3200   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3201     Kind = OMPC_MAP_alloc;
3202     break;
3203   case OMPC_DEFAULTMAP_MODIFIER_to:
3204     Kind = OMPC_MAP_to;
3205     break;
3206   case OMPC_DEFAULTMAP_MODIFIER_from:
3207     Kind = OMPC_MAP_from;
3208     break;
3209   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3210     Kind = OMPC_MAP_tofrom;
3211     break;
3212   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3213   case OMPC_DEFAULTMAP_MODIFIER_last:
3214     llvm_unreachable("Unexpected defaultmap implicit behavior");
3215   case OMPC_DEFAULTMAP_MODIFIER_none:
3216   case OMPC_DEFAULTMAP_MODIFIER_default:
3217   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3218     // IsAggregateOrDeclareTarget could be true if:
3219     // 1. the implicit behavior for aggregate is tofrom
3220     // 2. it's a declare target link
3221     if (IsAggregateOrDeclareTarget) {
3222       Kind = OMPC_MAP_tofrom;
3223       break;
3224     }
3225     llvm_unreachable("Unexpected defaultmap implicit behavior");
3226   }
3227   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3228   return Kind;
3229 }
3230 
3231 namespace {
3232 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3233   DSAStackTy *Stack;
3234   Sema &SemaRef;
3235   bool ErrorFound = false;
3236   bool TryCaptureCXXThisMembers = false;
3237   CapturedStmt *CS = nullptr;
3238   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3239   llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
3240   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3241   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3242 
3243   void VisitSubCaptures(OMPExecutableDirective *S) {
3244     // Check implicitly captured variables.
3245     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3246       return;
3247     visitSubCaptures(S->getInnermostCapturedStmt());
3248     // Try to capture inner this->member references to generate correct mappings
3249     // and diagnostics.
3250     if (TryCaptureCXXThisMembers ||
3251         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3252          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3253                       [](const CapturedStmt::Capture &C) {
3254                         return C.capturesThis();
3255                       }))) {
3256       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3257       TryCaptureCXXThisMembers = true;
3258       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3259       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3260     }
3261     // In tasks firstprivates are not captured anymore, need to analyze them
3262     // explicitly.
3263     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3264         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3265       for (OMPClause *C : S->clauses())
3266         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3267           for (Expr *Ref : FC->varlists())
3268             Visit(Ref);
3269         }
3270     }
3271   }
3272 
3273 public:
3274   void VisitDeclRefExpr(DeclRefExpr *E) {
3275     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3276         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3277         E->isInstantiationDependent())
3278       return;
3279     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3280       // Check the datasharing rules for the expressions in the clauses.
3281       if (!CS) {
3282         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3283           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3284             Visit(CED->getInit());
3285             return;
3286           }
3287       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3288         // Do not analyze internal variables and do not enclose them into
3289         // implicit clauses.
3290         return;
3291       VD = VD->getCanonicalDecl();
3292       // Skip internally declared variables.
3293       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3294           !Stack->isImplicitTaskFirstprivate(VD))
3295         return;
3296       // Skip allocators in uses_allocators clauses.
3297       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3298         return;
3299 
3300       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3301       // Check if the variable has explicit DSA set and stop analysis if it so.
3302       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3303         return;
3304 
3305       // Skip internally declared static variables.
3306       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3307           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3308       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3309           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3310            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3311           !Stack->isImplicitTaskFirstprivate(VD))
3312         return;
3313 
3314       SourceLocation ELoc = E->getExprLoc();
3315       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3316       // The default(none) clause requires that each variable that is referenced
3317       // in the construct, and does not have a predetermined data-sharing
3318       // attribute, must have its data-sharing attribute explicitly determined
3319       // by being listed in a data-sharing attribute clause.
3320       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
3321           isImplicitOrExplicitTaskingRegion(DKind) &&
3322           VarsWithInheritedDSA.count(VD) == 0) {
3323         VarsWithInheritedDSA[VD] = E;
3324         return;
3325       }
3326 
3327       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3328       // If implicit-behavior is none, each variable referenced in the
3329       // construct that does not have a predetermined data-sharing attribute
3330       // and does not appear in a to or link clause on a declare target
3331       // directive must be listed in a data-mapping attribute clause, a
3332       // data-haring attribute clause (including a data-sharing attribute
3333       // clause on a combined construct where target. is one of the
3334       // constituent constructs), or an is_device_ptr clause.
3335       OpenMPDefaultmapClauseKind ClauseKind =
3336           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3337       if (SemaRef.getLangOpts().OpenMP >= 50) {
3338         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3339                               OMPC_DEFAULTMAP_MODIFIER_none;
3340         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3341             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3342           // Only check for data-mapping attribute and is_device_ptr here
3343           // since we have already make sure that the declaration does not
3344           // have a data-sharing attribute above
3345           if (!Stack->checkMappableExprComponentListsForDecl(
3346                   VD, /*CurrentRegionOnly=*/true,
3347                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3348                            MapExprComponents,
3349                        OpenMPClauseKind) {
3350                     auto MI = MapExprComponents.rbegin();
3351                     auto ME = MapExprComponents.rend();
3352                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3353                   })) {
3354             VarsWithInheritedDSA[VD] = E;
3355             return;
3356           }
3357         }
3358       }
3359 
3360       if (isOpenMPTargetExecutionDirective(DKind) &&
3361           !Stack->isLoopControlVariable(VD).first) {
3362         if (!Stack->checkMappableExprComponentListsForDecl(
3363                 VD, /*CurrentRegionOnly=*/true,
3364                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3365                        StackComponents,
3366                    OpenMPClauseKind) {
3367                   // Variable is used if it has been marked as an array, array
3368                   // section, array shaping or the variable iself.
3369                   return StackComponents.size() == 1 ||
3370                          std::all_of(
3371                              std::next(StackComponents.rbegin()),
3372                              StackComponents.rend(),
3373                              [](const OMPClauseMappableExprCommon::
3374                                     MappableComponent &MC) {
3375                                return MC.getAssociatedDeclaration() ==
3376                                           nullptr &&
3377                                       (isa<OMPArraySectionExpr>(
3378                                            MC.getAssociatedExpression()) ||
3379                                        isa<OMPArrayShapingExpr>(
3380                                            MC.getAssociatedExpression()) ||
3381                                        isa<ArraySubscriptExpr>(
3382                                            MC.getAssociatedExpression()));
3383                              });
3384                 })) {
3385           bool IsFirstprivate = false;
3386           // By default lambdas are captured as firstprivates.
3387           if (const auto *RD =
3388                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3389             IsFirstprivate = RD->isLambda();
3390           IsFirstprivate =
3391               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3392           if (IsFirstprivate) {
3393             ImplicitFirstprivate.emplace_back(E);
3394           } else {
3395             OpenMPDefaultmapClauseModifier M =
3396                 Stack->getDefaultmapModifier(ClauseKind);
3397             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3398                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3399             ImplicitMap[Kind].emplace_back(E);
3400           }
3401           return;
3402         }
3403       }
3404 
3405       // OpenMP [2.9.3.6, Restrictions, p.2]
3406       //  A list item that appears in a reduction clause of the innermost
3407       //  enclosing worksharing or parallel construct may not be accessed in an
3408       //  explicit task.
3409       DVar = Stack->hasInnermostDSA(
3410           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3411           [](OpenMPDirectiveKind K) {
3412             return isOpenMPParallelDirective(K) ||
3413                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3414           },
3415           /*FromParent=*/true);
3416       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3417         ErrorFound = true;
3418         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3419         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3420         return;
3421       }
3422 
3423       // Define implicit data-sharing attributes for task.
3424       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3425       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3426           !Stack->isLoopControlVariable(VD).first) {
3427         ImplicitFirstprivate.push_back(E);
3428         return;
3429       }
3430 
3431       // Store implicitly used globals with declare target link for parent
3432       // target.
3433       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3434           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3435         Stack->addToParentTargetRegionLinkGlobals(E);
3436         return;
3437       }
3438     }
3439   }
3440   void VisitMemberExpr(MemberExpr *E) {
3441     if (E->isTypeDependent() || E->isValueDependent() ||
3442         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3443       return;
3444     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3445     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3446     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3447       if (!FD)
3448         return;
3449       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3450       // Check if the variable has explicit DSA set and stop analysis if it
3451       // so.
3452       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3453         return;
3454 
3455       if (isOpenMPTargetExecutionDirective(DKind) &&
3456           !Stack->isLoopControlVariable(FD).first &&
3457           !Stack->checkMappableExprComponentListsForDecl(
3458               FD, /*CurrentRegionOnly=*/true,
3459               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3460                      StackComponents,
3461                  OpenMPClauseKind) {
3462                 return isa<CXXThisExpr>(
3463                     cast<MemberExpr>(
3464                         StackComponents.back().getAssociatedExpression())
3465                         ->getBase()
3466                         ->IgnoreParens());
3467               })) {
3468         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3469         //  A bit-field cannot appear in a map clause.
3470         //
3471         if (FD->isBitField())
3472           return;
3473 
3474         // Check to see if the member expression is referencing a class that
3475         // has already been explicitly mapped
3476         if (Stack->isClassPreviouslyMapped(TE->getType()))
3477           return;
3478 
3479         OpenMPDefaultmapClauseModifier Modifier =
3480             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3481         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3482             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3483         ImplicitMap[Kind].emplace_back(E);
3484         return;
3485       }
3486 
3487       SourceLocation ELoc = E->getExprLoc();
3488       // OpenMP [2.9.3.6, Restrictions, p.2]
3489       //  A list item that appears in a reduction clause of the innermost
3490       //  enclosing worksharing or parallel construct may not be accessed in
3491       //  an  explicit task.
3492       DVar = Stack->hasInnermostDSA(
3493           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3494           [](OpenMPDirectiveKind K) {
3495             return isOpenMPParallelDirective(K) ||
3496                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3497           },
3498           /*FromParent=*/true);
3499       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3500         ErrorFound = true;
3501         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3502         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3503         return;
3504       }
3505 
3506       // Define implicit data-sharing attributes for task.
3507       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3508       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3509           !Stack->isLoopControlVariable(FD).first) {
3510         // Check if there is a captured expression for the current field in the
3511         // region. Do not mark it as firstprivate unless there is no captured
3512         // expression.
3513         // TODO: try to make it firstprivate.
3514         if (DVar.CKind != OMPC_unknown)
3515           ImplicitFirstprivate.push_back(E);
3516       }
3517       return;
3518     }
3519     if (isOpenMPTargetExecutionDirective(DKind)) {
3520       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3521       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3522                                         /*NoDiagnose=*/true))
3523         return;
3524       const auto *VD = cast<ValueDecl>(
3525           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3526       if (!Stack->checkMappableExprComponentListsForDecl(
3527               VD, /*CurrentRegionOnly=*/true,
3528               [&CurComponents](
3529                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3530                       StackComponents,
3531                   OpenMPClauseKind) {
3532                 auto CCI = CurComponents.rbegin();
3533                 auto CCE = CurComponents.rend();
3534                 for (const auto &SC : llvm::reverse(StackComponents)) {
3535                   // Do both expressions have the same kind?
3536                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3537                       SC.getAssociatedExpression()->getStmtClass())
3538                     if (!((isa<OMPArraySectionExpr>(
3539                                SC.getAssociatedExpression()) ||
3540                            isa<OMPArrayShapingExpr>(
3541                                SC.getAssociatedExpression())) &&
3542                           isa<ArraySubscriptExpr>(
3543                               CCI->getAssociatedExpression())))
3544                       return false;
3545 
3546                   const Decl *CCD = CCI->getAssociatedDeclaration();
3547                   const Decl *SCD = SC.getAssociatedDeclaration();
3548                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3549                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3550                   if (SCD != CCD)
3551                     return false;
3552                   std::advance(CCI, 1);
3553                   if (CCI == CCE)
3554                     break;
3555                 }
3556                 return true;
3557               })) {
3558         Visit(E->getBase());
3559       }
3560     } else if (!TryCaptureCXXThisMembers) {
3561       Visit(E->getBase());
3562     }
3563   }
3564   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3565     for (OMPClause *C : S->clauses()) {
3566       // Skip analysis of arguments of implicitly defined firstprivate clause
3567       // for task|target directives.
3568       // Skip analysis of arguments of implicitly defined map clause for target
3569       // directives.
3570       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3571                  C->isImplicit())) {
3572         for (Stmt *CC : C->children()) {
3573           if (CC)
3574             Visit(CC);
3575         }
3576       }
3577     }
3578     // Check implicitly captured variables.
3579     VisitSubCaptures(S);
3580   }
3581   void VisitStmt(Stmt *S) {
3582     for (Stmt *C : S->children()) {
3583       if (C) {
3584         // Check implicitly captured variables in the task-based directives to
3585         // check if they must be firstprivatized.
3586         Visit(C);
3587       }
3588     }
3589   }
3590 
3591   void visitSubCaptures(CapturedStmt *S) {
3592     for (const CapturedStmt::Capture &Cap : S->captures()) {
3593       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3594         continue;
3595       VarDecl *VD = Cap.getCapturedVar();
3596       // Do not try to map the variable if it or its sub-component was mapped
3597       // already.
3598       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3599           Stack->checkMappableExprComponentListsForDecl(
3600               VD, /*CurrentRegionOnly=*/true,
3601               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3602                  OpenMPClauseKind) { return true; }))
3603         continue;
3604       DeclRefExpr *DRE = buildDeclRefExpr(
3605           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3606           Cap.getLocation(), /*RefersToCapture=*/true);
3607       Visit(DRE);
3608     }
3609   }
3610   bool isErrorFound() const { return ErrorFound; }
3611   ArrayRef<Expr *> getImplicitFirstprivate() const {
3612     return ImplicitFirstprivate;
3613   }
3614   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3615     return ImplicitMap[Kind];
3616   }
3617   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3618     return VarsWithInheritedDSA;
3619   }
3620 
3621   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3622       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3623     // Process declare target link variables for the target directives.
3624     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3625       for (DeclRefExpr *E : Stack->getLinkGlobals())
3626         Visit(E);
3627     }
3628   }
3629 };
3630 } // namespace
3631 
3632 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3633   switch (DKind) {
3634   case OMPD_parallel:
3635   case OMPD_parallel_for:
3636   case OMPD_parallel_for_simd:
3637   case OMPD_parallel_sections:
3638   case OMPD_parallel_master:
3639   case OMPD_teams:
3640   case OMPD_teams_distribute:
3641   case OMPD_teams_distribute_simd: {
3642     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3643     QualType KmpInt32PtrTy =
3644         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3645     Sema::CapturedParamNameType Params[] = {
3646         std::make_pair(".global_tid.", KmpInt32PtrTy),
3647         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3648         std::make_pair(StringRef(), QualType()) // __context with shared vars
3649     };
3650     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3651                              Params);
3652     break;
3653   }
3654   case OMPD_target_teams:
3655   case OMPD_target_parallel:
3656   case OMPD_target_parallel_for:
3657   case OMPD_target_parallel_for_simd:
3658   case OMPD_target_teams_distribute:
3659   case OMPD_target_teams_distribute_simd: {
3660     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3661     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3662     QualType KmpInt32PtrTy =
3663         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3664     QualType Args[] = {VoidPtrTy};
3665     FunctionProtoType::ExtProtoInfo EPI;
3666     EPI.Variadic = true;
3667     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3668     Sema::CapturedParamNameType Params[] = {
3669         std::make_pair(".global_tid.", KmpInt32Ty),
3670         std::make_pair(".part_id.", KmpInt32PtrTy),
3671         std::make_pair(".privates.", VoidPtrTy),
3672         std::make_pair(
3673             ".copy_fn.",
3674             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3675         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3676         std::make_pair(StringRef(), QualType()) // __context with shared vars
3677     };
3678     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3679                              Params, /*OpenMPCaptureLevel=*/0);
3680     // Mark this captured region as inlined, because we don't use outlined
3681     // function directly.
3682     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3683         AlwaysInlineAttr::CreateImplicit(
3684             Context, {}, AttributeCommonInfo::AS_Keyword,
3685             AlwaysInlineAttr::Keyword_forceinline));
3686     Sema::CapturedParamNameType ParamsTarget[] = {
3687         std::make_pair(StringRef(), QualType()) // __context with shared vars
3688     };
3689     // Start a captured region for 'target' with no implicit parameters.
3690     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3691                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3692     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3693         std::make_pair(".global_tid.", KmpInt32PtrTy),
3694         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3695         std::make_pair(StringRef(), QualType()) // __context with shared vars
3696     };
3697     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3698     // the same implicit parameters.
3699     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3700                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3701     break;
3702   }
3703   case OMPD_target:
3704   case OMPD_target_simd: {
3705     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3706     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3707     QualType KmpInt32PtrTy =
3708         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3709     QualType Args[] = {VoidPtrTy};
3710     FunctionProtoType::ExtProtoInfo EPI;
3711     EPI.Variadic = true;
3712     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3713     Sema::CapturedParamNameType Params[] = {
3714         std::make_pair(".global_tid.", KmpInt32Ty),
3715         std::make_pair(".part_id.", KmpInt32PtrTy),
3716         std::make_pair(".privates.", VoidPtrTy),
3717         std::make_pair(
3718             ".copy_fn.",
3719             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3720         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3721         std::make_pair(StringRef(), QualType()) // __context with shared vars
3722     };
3723     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3724                              Params, /*OpenMPCaptureLevel=*/0);
3725     // Mark this captured region as inlined, because we don't use outlined
3726     // function directly.
3727     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3728         AlwaysInlineAttr::CreateImplicit(
3729             Context, {}, AttributeCommonInfo::AS_Keyword,
3730             AlwaysInlineAttr::Keyword_forceinline));
3731     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3732                              std::make_pair(StringRef(), QualType()),
3733                              /*OpenMPCaptureLevel=*/1);
3734     break;
3735   }
3736   case OMPD_simd:
3737   case OMPD_for:
3738   case OMPD_for_simd:
3739   case OMPD_sections:
3740   case OMPD_section:
3741   case OMPD_single:
3742   case OMPD_master:
3743   case OMPD_critical:
3744   case OMPD_taskgroup:
3745   case OMPD_distribute:
3746   case OMPD_distribute_simd:
3747   case OMPD_ordered:
3748   case OMPD_atomic:
3749   case OMPD_target_data: {
3750     Sema::CapturedParamNameType Params[] = {
3751         std::make_pair(StringRef(), QualType()) // __context with shared vars
3752     };
3753     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3754                              Params);
3755     break;
3756   }
3757   case OMPD_task: {
3758     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3759     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3760     QualType KmpInt32PtrTy =
3761         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3762     QualType Args[] = {VoidPtrTy};
3763     FunctionProtoType::ExtProtoInfo EPI;
3764     EPI.Variadic = true;
3765     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3766     Sema::CapturedParamNameType Params[] = {
3767         std::make_pair(".global_tid.", KmpInt32Ty),
3768         std::make_pair(".part_id.", KmpInt32PtrTy),
3769         std::make_pair(".privates.", VoidPtrTy),
3770         std::make_pair(
3771             ".copy_fn.",
3772             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3773         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3774         std::make_pair(StringRef(), QualType()) // __context with shared vars
3775     };
3776     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3777                              Params);
3778     // Mark this captured region as inlined, because we don't use outlined
3779     // function directly.
3780     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3781         AlwaysInlineAttr::CreateImplicit(
3782             Context, {}, AttributeCommonInfo::AS_Keyword,
3783             AlwaysInlineAttr::Keyword_forceinline));
3784     break;
3785   }
3786   case OMPD_taskloop:
3787   case OMPD_taskloop_simd:
3788   case OMPD_master_taskloop:
3789   case OMPD_master_taskloop_simd: {
3790     QualType KmpInt32Ty =
3791         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3792             .withConst();
3793     QualType KmpUInt64Ty =
3794         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3795             .withConst();
3796     QualType KmpInt64Ty =
3797         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3798             .withConst();
3799     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3800     QualType KmpInt32PtrTy =
3801         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3802     QualType Args[] = {VoidPtrTy};
3803     FunctionProtoType::ExtProtoInfo EPI;
3804     EPI.Variadic = true;
3805     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3806     Sema::CapturedParamNameType Params[] = {
3807         std::make_pair(".global_tid.", KmpInt32Ty),
3808         std::make_pair(".part_id.", KmpInt32PtrTy),
3809         std::make_pair(".privates.", VoidPtrTy),
3810         std::make_pair(
3811             ".copy_fn.",
3812             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3813         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3814         std::make_pair(".lb.", KmpUInt64Ty),
3815         std::make_pair(".ub.", KmpUInt64Ty),
3816         std::make_pair(".st.", KmpInt64Ty),
3817         std::make_pair(".liter.", KmpInt32Ty),
3818         std::make_pair(".reductions.", VoidPtrTy),
3819         std::make_pair(StringRef(), QualType()) // __context with shared vars
3820     };
3821     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3822                              Params);
3823     // Mark this captured region as inlined, because we don't use outlined
3824     // function directly.
3825     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3826         AlwaysInlineAttr::CreateImplicit(
3827             Context, {}, AttributeCommonInfo::AS_Keyword,
3828             AlwaysInlineAttr::Keyword_forceinline));
3829     break;
3830   }
3831   case OMPD_parallel_master_taskloop:
3832   case OMPD_parallel_master_taskloop_simd: {
3833     QualType KmpInt32Ty =
3834         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3835             .withConst();
3836     QualType KmpUInt64Ty =
3837         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3838             .withConst();
3839     QualType KmpInt64Ty =
3840         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3841             .withConst();
3842     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3843     QualType KmpInt32PtrTy =
3844         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3845     Sema::CapturedParamNameType ParamsParallel[] = {
3846         std::make_pair(".global_tid.", KmpInt32PtrTy),
3847         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3848         std::make_pair(StringRef(), QualType()) // __context with shared vars
3849     };
3850     // Start a captured region for 'parallel'.
3851     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3852                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
3853     QualType Args[] = {VoidPtrTy};
3854     FunctionProtoType::ExtProtoInfo EPI;
3855     EPI.Variadic = true;
3856     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3857     Sema::CapturedParamNameType Params[] = {
3858         std::make_pair(".global_tid.", KmpInt32Ty),
3859         std::make_pair(".part_id.", KmpInt32PtrTy),
3860         std::make_pair(".privates.", VoidPtrTy),
3861         std::make_pair(
3862             ".copy_fn.",
3863             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3864         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3865         std::make_pair(".lb.", KmpUInt64Ty),
3866         std::make_pair(".ub.", KmpUInt64Ty),
3867         std::make_pair(".st.", KmpInt64Ty),
3868         std::make_pair(".liter.", KmpInt32Ty),
3869         std::make_pair(".reductions.", VoidPtrTy),
3870         std::make_pair(StringRef(), QualType()) // __context with shared vars
3871     };
3872     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3873                              Params, /*OpenMPCaptureLevel=*/1);
3874     // Mark this captured region as inlined, because we don't use outlined
3875     // function directly.
3876     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3877         AlwaysInlineAttr::CreateImplicit(
3878             Context, {}, AttributeCommonInfo::AS_Keyword,
3879             AlwaysInlineAttr::Keyword_forceinline));
3880     break;
3881   }
3882   case OMPD_distribute_parallel_for_simd:
3883   case OMPD_distribute_parallel_for: {
3884     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3885     QualType KmpInt32PtrTy =
3886         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3887     Sema::CapturedParamNameType Params[] = {
3888         std::make_pair(".global_tid.", KmpInt32PtrTy),
3889         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3890         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3891         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3892         std::make_pair(StringRef(), QualType()) // __context with shared vars
3893     };
3894     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3895                              Params);
3896     break;
3897   }
3898   case OMPD_target_teams_distribute_parallel_for:
3899   case OMPD_target_teams_distribute_parallel_for_simd: {
3900     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3901     QualType KmpInt32PtrTy =
3902         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3903     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3904 
3905     QualType Args[] = {VoidPtrTy};
3906     FunctionProtoType::ExtProtoInfo EPI;
3907     EPI.Variadic = true;
3908     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3909     Sema::CapturedParamNameType Params[] = {
3910         std::make_pair(".global_tid.", KmpInt32Ty),
3911         std::make_pair(".part_id.", KmpInt32PtrTy),
3912         std::make_pair(".privates.", VoidPtrTy),
3913         std::make_pair(
3914             ".copy_fn.",
3915             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3916         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3917         std::make_pair(StringRef(), QualType()) // __context with shared vars
3918     };
3919     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3920                              Params, /*OpenMPCaptureLevel=*/0);
3921     // Mark this captured region as inlined, because we don't use outlined
3922     // function directly.
3923     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3924         AlwaysInlineAttr::CreateImplicit(
3925             Context, {}, AttributeCommonInfo::AS_Keyword,
3926             AlwaysInlineAttr::Keyword_forceinline));
3927     Sema::CapturedParamNameType ParamsTarget[] = {
3928         std::make_pair(StringRef(), QualType()) // __context with shared vars
3929     };
3930     // Start a captured region for 'target' with no implicit parameters.
3931     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3932                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3933 
3934     Sema::CapturedParamNameType ParamsTeams[] = {
3935         std::make_pair(".global_tid.", KmpInt32PtrTy),
3936         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3937         std::make_pair(StringRef(), QualType()) // __context with shared vars
3938     };
3939     // Start a captured region for 'target' with no implicit parameters.
3940     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3941                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
3942 
3943     Sema::CapturedParamNameType ParamsParallel[] = {
3944         std::make_pair(".global_tid.", KmpInt32PtrTy),
3945         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3946         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3947         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3948         std::make_pair(StringRef(), QualType()) // __context with shared vars
3949     };
3950     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3951     // the same implicit parameters.
3952     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3953                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
3954     break;
3955   }
3956 
3957   case OMPD_teams_distribute_parallel_for:
3958   case OMPD_teams_distribute_parallel_for_simd: {
3959     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3960     QualType KmpInt32PtrTy =
3961         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3962 
3963     Sema::CapturedParamNameType ParamsTeams[] = {
3964         std::make_pair(".global_tid.", KmpInt32PtrTy),
3965         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3966         std::make_pair(StringRef(), QualType()) // __context with shared vars
3967     };
3968     // Start a captured region for 'target' with no implicit parameters.
3969     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3970                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
3971 
3972     Sema::CapturedParamNameType ParamsParallel[] = {
3973         std::make_pair(".global_tid.", KmpInt32PtrTy),
3974         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3975         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3976         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3977         std::make_pair(StringRef(), QualType()) // __context with shared vars
3978     };
3979     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3980     // the same implicit parameters.
3981     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3982                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
3983     break;
3984   }
3985   case OMPD_target_update:
3986   case OMPD_target_enter_data:
3987   case OMPD_target_exit_data: {
3988     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3989     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3990     QualType KmpInt32PtrTy =
3991         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3992     QualType Args[] = {VoidPtrTy};
3993     FunctionProtoType::ExtProtoInfo EPI;
3994     EPI.Variadic = true;
3995     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3996     Sema::CapturedParamNameType Params[] = {
3997         std::make_pair(".global_tid.", KmpInt32Ty),
3998         std::make_pair(".part_id.", KmpInt32PtrTy),
3999         std::make_pair(".privates.", VoidPtrTy),
4000         std::make_pair(
4001             ".copy_fn.",
4002             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4003         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4004         std::make_pair(StringRef(), QualType()) // __context with shared vars
4005     };
4006     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4007                              Params);
4008     // Mark this captured region as inlined, because we don't use outlined
4009     // function directly.
4010     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4011         AlwaysInlineAttr::CreateImplicit(
4012             Context, {}, AttributeCommonInfo::AS_Keyword,
4013             AlwaysInlineAttr::Keyword_forceinline));
4014     break;
4015   }
4016   case OMPD_threadprivate:
4017   case OMPD_allocate:
4018   case OMPD_taskyield:
4019   case OMPD_barrier:
4020   case OMPD_taskwait:
4021   case OMPD_cancellation_point:
4022   case OMPD_cancel:
4023   case OMPD_flush:
4024   case OMPD_depobj:
4025   case OMPD_scan:
4026   case OMPD_declare_reduction:
4027   case OMPD_declare_mapper:
4028   case OMPD_declare_simd:
4029   case OMPD_declare_target:
4030   case OMPD_end_declare_target:
4031   case OMPD_requires:
4032   case OMPD_declare_variant:
4033   case OMPD_begin_declare_variant:
4034   case OMPD_end_declare_variant:
4035     llvm_unreachable("OpenMP Directive is not allowed");
4036   case OMPD_unknown:
4037     llvm_unreachable("Unknown OpenMP directive");
4038   }
4039 }
4040 
4041 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4042   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4043 }
4044 
4045 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4046   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4047   getOpenMPCaptureRegions(CaptureRegions, DKind);
4048   return CaptureRegions.size();
4049 }
4050 
4051 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4052                                              Expr *CaptureExpr, bool WithInit,
4053                                              bool AsExpression) {
4054   assert(CaptureExpr);
4055   ASTContext &C = S.getASTContext();
4056   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4057   QualType Ty = Init->getType();
4058   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4059     if (S.getLangOpts().CPlusPlus) {
4060       Ty = C.getLValueReferenceType(Ty);
4061     } else {
4062       Ty = C.getPointerType(Ty);
4063       ExprResult Res =
4064           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4065       if (!Res.isUsable())
4066         return nullptr;
4067       Init = Res.get();
4068     }
4069     WithInit = true;
4070   }
4071   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4072                                           CaptureExpr->getBeginLoc());
4073   if (!WithInit)
4074     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4075   S.CurContext->addHiddenDecl(CED);
4076   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4077   return CED;
4078 }
4079 
4080 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4081                                  bool WithInit) {
4082   OMPCapturedExprDecl *CD;
4083   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4084     CD = cast<OMPCapturedExprDecl>(VD);
4085   else
4086     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4087                           /*AsExpression=*/false);
4088   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4089                           CaptureExpr->getExprLoc());
4090 }
4091 
4092 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4093   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4094   if (!Ref) {
4095     OMPCapturedExprDecl *CD = buildCaptureDecl(
4096         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4097         /*WithInit=*/true, /*AsExpression=*/true);
4098     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4099                            CaptureExpr->getExprLoc());
4100   }
4101   ExprResult Res = Ref;
4102   if (!S.getLangOpts().CPlusPlus &&
4103       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4104       Ref->getType()->isPointerType()) {
4105     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4106     if (!Res.isUsable())
4107       return ExprError();
4108   }
4109   return S.DefaultLvalueConversion(Res.get());
4110 }
4111 
4112 namespace {
4113 // OpenMP directives parsed in this section are represented as a
4114 // CapturedStatement with an associated statement.  If a syntax error
4115 // is detected during the parsing of the associated statement, the
4116 // compiler must abort processing and close the CapturedStatement.
4117 //
4118 // Combined directives such as 'target parallel' have more than one
4119 // nested CapturedStatements.  This RAII ensures that we unwind out
4120 // of all the nested CapturedStatements when an error is found.
4121 class CaptureRegionUnwinderRAII {
4122 private:
4123   Sema &S;
4124   bool &ErrorFound;
4125   OpenMPDirectiveKind DKind = OMPD_unknown;
4126 
4127 public:
4128   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4129                             OpenMPDirectiveKind DKind)
4130       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4131   ~CaptureRegionUnwinderRAII() {
4132     if (ErrorFound) {
4133       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4134       while (--ThisCaptureLevel >= 0)
4135         S.ActOnCapturedRegionError();
4136     }
4137   }
4138 };
4139 } // namespace
4140 
4141 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4142   // Capture variables captured by reference in lambdas for target-based
4143   // directives.
4144   if (!CurContext->isDependentContext() &&
4145       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4146        isOpenMPTargetDataManagementDirective(
4147            DSAStack->getCurrentDirective()))) {
4148     QualType Type = V->getType();
4149     if (const auto *RD = Type.getCanonicalType()
4150                              .getNonReferenceType()
4151                              ->getAsCXXRecordDecl()) {
4152       bool SavedForceCaptureByReferenceInTargetExecutable =
4153           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4154       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4155           /*V=*/true);
4156       if (RD->isLambda()) {
4157         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4158         FieldDecl *ThisCapture;
4159         RD->getCaptureFields(Captures, ThisCapture);
4160         for (const LambdaCapture &LC : RD->captures()) {
4161           if (LC.getCaptureKind() == LCK_ByRef) {
4162             VarDecl *VD = LC.getCapturedVar();
4163             DeclContext *VDC = VD->getDeclContext();
4164             if (!VDC->Encloses(CurContext))
4165               continue;
4166             MarkVariableReferenced(LC.getLocation(), VD);
4167           } else if (LC.getCaptureKind() == LCK_This) {
4168             QualType ThisTy = getCurrentThisType();
4169             if (!ThisTy.isNull() &&
4170                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4171               CheckCXXThisCapture(LC.getLocation());
4172           }
4173         }
4174       }
4175       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4176           SavedForceCaptureByReferenceInTargetExecutable);
4177     }
4178   }
4179 }
4180 
4181 static bool checkOrderedOrderSpecified(Sema &S,
4182                                        const ArrayRef<OMPClause *> Clauses) {
4183   const OMPOrderedClause *Ordered = nullptr;
4184   const OMPOrderClause *Order = nullptr;
4185 
4186   for (const OMPClause *Clause : Clauses) {
4187     if (Clause->getClauseKind() == OMPC_ordered)
4188       Ordered = cast<OMPOrderedClause>(Clause);
4189     else if (Clause->getClauseKind() == OMPC_order) {
4190       Order = cast<OMPOrderClause>(Clause);
4191       if (Order->getKind() != OMPC_ORDER_concurrent)
4192         Order = nullptr;
4193     }
4194     if (Ordered && Order)
4195       break;
4196   }
4197 
4198   if (Ordered && Order) {
4199     S.Diag(Order->getKindKwLoc(),
4200            diag::err_omp_simple_clause_incompatible_with_ordered)
4201         << getOpenMPClauseName(OMPC_order)
4202         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4203         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4204     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4205         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4206     return true;
4207   }
4208   return false;
4209 }
4210 
4211 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4212                                       ArrayRef<OMPClause *> Clauses) {
4213   bool ErrorFound = false;
4214   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4215       *this, ErrorFound, DSAStack->getCurrentDirective());
4216   if (!S.isUsable()) {
4217     ErrorFound = true;
4218     return StmtError();
4219   }
4220 
4221   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4222   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4223   OMPOrderedClause *OC = nullptr;
4224   OMPScheduleClause *SC = nullptr;
4225   SmallVector<const OMPLinearClause *, 4> LCs;
4226   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4227   // This is required for proper codegen.
4228   for (OMPClause *Clause : Clauses) {
4229     if (!LangOpts.OpenMPSimd &&
4230         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4231         Clause->getClauseKind() == OMPC_in_reduction) {
4232       // Capture taskgroup task_reduction descriptors inside the tasking regions
4233       // with the corresponding in_reduction items.
4234       auto *IRC = cast<OMPInReductionClause>(Clause);
4235       for (Expr *E : IRC->taskgroup_descriptors())
4236         if (E)
4237           MarkDeclarationsReferencedInExpr(E);
4238     }
4239     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4240         Clause->getClauseKind() == OMPC_copyprivate ||
4241         (getLangOpts().OpenMPUseTLS &&
4242          getASTContext().getTargetInfo().isTLSSupported() &&
4243          Clause->getClauseKind() == OMPC_copyin)) {
4244       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4245       // Mark all variables in private list clauses as used in inner region.
4246       for (Stmt *VarRef : Clause->children()) {
4247         if (auto *E = cast_or_null<Expr>(VarRef)) {
4248           MarkDeclarationsReferencedInExpr(E);
4249         }
4250       }
4251       DSAStack->setForceVarCapturing(/*V=*/false);
4252     } else if (CaptureRegions.size() > 1 ||
4253                CaptureRegions.back() != OMPD_unknown) {
4254       if (auto *C = OMPClauseWithPreInit::get(Clause))
4255         PICs.push_back(C);
4256       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4257         if (Expr *E = C->getPostUpdateExpr())
4258           MarkDeclarationsReferencedInExpr(E);
4259       }
4260     }
4261     if (Clause->getClauseKind() == OMPC_schedule)
4262       SC = cast<OMPScheduleClause>(Clause);
4263     else if (Clause->getClauseKind() == OMPC_ordered)
4264       OC = cast<OMPOrderedClause>(Clause);
4265     else if (Clause->getClauseKind() == OMPC_linear)
4266       LCs.push_back(cast<OMPLinearClause>(Clause));
4267   }
4268   // Capture allocator expressions if used.
4269   for (Expr *E : DSAStack->getInnerAllocators())
4270     MarkDeclarationsReferencedInExpr(E);
4271   // OpenMP, 2.7.1 Loop Construct, Restrictions
4272   // The nonmonotonic modifier cannot be specified if an ordered clause is
4273   // specified.
4274   if (SC &&
4275       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4276        SC->getSecondScheduleModifier() ==
4277            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4278       OC) {
4279     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4280              ? SC->getFirstScheduleModifierLoc()
4281              : SC->getSecondScheduleModifierLoc(),
4282          diag::err_omp_simple_clause_incompatible_with_ordered)
4283         << getOpenMPClauseName(OMPC_schedule)
4284         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4285                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4286         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4287     ErrorFound = true;
4288   }
4289   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4290   // If an order(concurrent) clause is present, an ordered clause may not appear
4291   // on the same directive.
4292   if (checkOrderedOrderSpecified(*this, Clauses))
4293     ErrorFound = true;
4294   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4295     for (const OMPLinearClause *C : LCs) {
4296       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4297           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4298     }
4299     ErrorFound = true;
4300   }
4301   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4302       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4303       OC->getNumForLoops()) {
4304     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4305         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4306     ErrorFound = true;
4307   }
4308   if (ErrorFound) {
4309     return StmtError();
4310   }
4311   StmtResult SR = S;
4312   unsigned CompletedRegions = 0;
4313   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4314     // Mark all variables in private list clauses as used in inner region.
4315     // Required for proper codegen of combined directives.
4316     // TODO: add processing for other clauses.
4317     if (ThisCaptureRegion != OMPD_unknown) {
4318       for (const clang::OMPClauseWithPreInit *C : PICs) {
4319         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4320         // Find the particular capture region for the clause if the
4321         // directive is a combined one with multiple capture regions.
4322         // If the directive is not a combined one, the capture region
4323         // associated with the clause is OMPD_unknown and is generated
4324         // only once.
4325         if (CaptureRegion == ThisCaptureRegion ||
4326             CaptureRegion == OMPD_unknown) {
4327           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4328             for (Decl *D : DS->decls())
4329               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4330           }
4331         }
4332       }
4333     }
4334     if (ThisCaptureRegion == OMPD_target) {
4335       // Capture allocator traits in the target region. They are used implicitly
4336       // and, thus, are not captured by default.
4337       for (OMPClause *C : Clauses) {
4338         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4339           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4340                ++I) {
4341             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4342             if (Expr *E = D.AllocatorTraits)
4343               MarkDeclarationsReferencedInExpr(E);
4344           }
4345           continue;
4346         }
4347       }
4348     }
4349     if (++CompletedRegions == CaptureRegions.size())
4350       DSAStack->setBodyComplete();
4351     SR = ActOnCapturedRegionEnd(SR.get());
4352   }
4353   return SR;
4354 }
4355 
4356 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4357                               OpenMPDirectiveKind CancelRegion,
4358                               SourceLocation StartLoc) {
4359   // CancelRegion is only needed for cancel and cancellation_point.
4360   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4361     return false;
4362 
4363   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4364       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4365     return false;
4366 
4367   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4368       << getOpenMPDirectiveName(CancelRegion);
4369   return true;
4370 }
4371 
4372 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4373                                   OpenMPDirectiveKind CurrentRegion,
4374                                   const DeclarationNameInfo &CurrentName,
4375                                   OpenMPDirectiveKind CancelRegion,
4376                                   SourceLocation StartLoc) {
4377   if (Stack->getCurScope()) {
4378     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4379     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4380     bool NestingProhibited = false;
4381     bool CloseNesting = true;
4382     bool OrphanSeen = false;
4383     enum {
4384       NoRecommend,
4385       ShouldBeInParallelRegion,
4386       ShouldBeInOrderedRegion,
4387       ShouldBeInTargetRegion,
4388       ShouldBeInTeamsRegion,
4389       ShouldBeInLoopSimdRegion,
4390     } Recommend = NoRecommend;
4391     if (isOpenMPSimdDirective(ParentRegion) &&
4392         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4393          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4394           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4395           CurrentRegion != OMPD_scan))) {
4396       // OpenMP [2.16, Nesting of Regions]
4397       // OpenMP constructs may not be nested inside a simd region.
4398       // OpenMP [2.8.1,simd Construct, Restrictions]
4399       // An ordered construct with the simd clause is the only OpenMP
4400       // construct that can appear in the simd region.
4401       // Allowing a SIMD construct nested in another SIMD construct is an
4402       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4403       // message.
4404       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4405       // The only OpenMP constructs that can be encountered during execution of
4406       // a simd region are the atomic construct, the loop construct, the simd
4407       // construct and the ordered construct with the simd clause.
4408       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4409                                  ? diag::err_omp_prohibited_region_simd
4410                                  : diag::warn_omp_nesting_simd)
4411           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4412       return CurrentRegion != OMPD_simd;
4413     }
4414     if (ParentRegion == OMPD_atomic) {
4415       // OpenMP [2.16, Nesting of Regions]
4416       // OpenMP constructs may not be nested inside an atomic region.
4417       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4418       return true;
4419     }
4420     if (CurrentRegion == OMPD_section) {
4421       // OpenMP [2.7.2, sections Construct, Restrictions]
4422       // Orphaned section directives are prohibited. That is, the section
4423       // directives must appear within the sections construct and must not be
4424       // encountered elsewhere in the sections region.
4425       if (ParentRegion != OMPD_sections &&
4426           ParentRegion != OMPD_parallel_sections) {
4427         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4428             << (ParentRegion != OMPD_unknown)
4429             << getOpenMPDirectiveName(ParentRegion);
4430         return true;
4431       }
4432       return false;
4433     }
4434     // Allow some constructs (except teams and cancellation constructs) to be
4435     // orphaned (they could be used in functions, called from OpenMP regions
4436     // with the required preconditions).
4437     if (ParentRegion == OMPD_unknown &&
4438         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4439         CurrentRegion != OMPD_cancellation_point &&
4440         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4441       return false;
4442     if (CurrentRegion == OMPD_cancellation_point ||
4443         CurrentRegion == OMPD_cancel) {
4444       // OpenMP [2.16, Nesting of Regions]
4445       // A cancellation point construct for which construct-type-clause is
4446       // taskgroup must be nested inside a task construct. A cancellation
4447       // point construct for which construct-type-clause is not taskgroup must
4448       // be closely nested inside an OpenMP construct that matches the type
4449       // specified in construct-type-clause.
4450       // A cancel construct for which construct-type-clause is taskgroup must be
4451       // nested inside a task construct. A cancel construct for which
4452       // construct-type-clause is not taskgroup must be closely nested inside an
4453       // OpenMP construct that matches the type specified in
4454       // construct-type-clause.
4455       NestingProhibited =
4456           !((CancelRegion == OMPD_parallel &&
4457              (ParentRegion == OMPD_parallel ||
4458               ParentRegion == OMPD_target_parallel)) ||
4459             (CancelRegion == OMPD_for &&
4460              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4461               ParentRegion == OMPD_target_parallel_for ||
4462               ParentRegion == OMPD_distribute_parallel_for ||
4463               ParentRegion == OMPD_teams_distribute_parallel_for ||
4464               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4465             (CancelRegion == OMPD_taskgroup &&
4466              (ParentRegion == OMPD_task ||
4467               (SemaRef.getLangOpts().OpenMP >= 50 &&
4468                (ParentRegion == OMPD_taskloop ||
4469                 ParentRegion == OMPD_master_taskloop ||
4470                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4471             (CancelRegion == OMPD_sections &&
4472              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4473               ParentRegion == OMPD_parallel_sections)));
4474       OrphanSeen = ParentRegion == OMPD_unknown;
4475     } else if (CurrentRegion == OMPD_master) {
4476       // OpenMP [2.16, Nesting of Regions]
4477       // A master region may not be closely nested inside a worksharing,
4478       // atomic, or explicit task region.
4479       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4480                           isOpenMPTaskingDirective(ParentRegion);
4481     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4482       // OpenMP [2.16, Nesting of Regions]
4483       // A critical region may not be nested (closely or otherwise) inside a
4484       // critical region with the same name. Note that this restriction is not
4485       // sufficient to prevent deadlock.
4486       SourceLocation PreviousCriticalLoc;
4487       bool DeadLock = Stack->hasDirective(
4488           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4489                                               const DeclarationNameInfo &DNI,
4490                                               SourceLocation Loc) {
4491             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4492               PreviousCriticalLoc = Loc;
4493               return true;
4494             }
4495             return false;
4496           },
4497           false /* skip top directive */);
4498       if (DeadLock) {
4499         SemaRef.Diag(StartLoc,
4500                      diag::err_omp_prohibited_region_critical_same_name)
4501             << CurrentName.getName();
4502         if (PreviousCriticalLoc.isValid())
4503           SemaRef.Diag(PreviousCriticalLoc,
4504                        diag::note_omp_previous_critical_region);
4505         return true;
4506       }
4507     } else if (CurrentRegion == OMPD_barrier) {
4508       // OpenMP [2.16, Nesting of Regions]
4509       // A barrier region may not be closely nested inside a worksharing,
4510       // explicit task, critical, ordered, atomic, or master region.
4511       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4512                           isOpenMPTaskingDirective(ParentRegion) ||
4513                           ParentRegion == OMPD_master ||
4514                           ParentRegion == OMPD_parallel_master ||
4515                           ParentRegion == OMPD_critical ||
4516                           ParentRegion == OMPD_ordered;
4517     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4518                !isOpenMPParallelDirective(CurrentRegion) &&
4519                !isOpenMPTeamsDirective(CurrentRegion)) {
4520       // OpenMP [2.16, Nesting of Regions]
4521       // A worksharing region may not be closely nested inside a worksharing,
4522       // explicit task, critical, ordered, atomic, or master region.
4523       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4524                           isOpenMPTaskingDirective(ParentRegion) ||
4525                           ParentRegion == OMPD_master ||
4526                           ParentRegion == OMPD_parallel_master ||
4527                           ParentRegion == OMPD_critical ||
4528                           ParentRegion == OMPD_ordered;
4529       Recommend = ShouldBeInParallelRegion;
4530     } else if (CurrentRegion == OMPD_ordered) {
4531       // OpenMP [2.16, Nesting of Regions]
4532       // An ordered region may not be closely nested inside a critical,
4533       // atomic, or explicit task region.
4534       // An ordered region must be closely nested inside a loop region (or
4535       // parallel loop region) with an ordered clause.
4536       // OpenMP [2.8.1,simd Construct, Restrictions]
4537       // An ordered construct with the simd clause is the only OpenMP construct
4538       // that can appear in the simd region.
4539       NestingProhibited = ParentRegion == OMPD_critical ||
4540                           isOpenMPTaskingDirective(ParentRegion) ||
4541                           !(isOpenMPSimdDirective(ParentRegion) ||
4542                             Stack->isParentOrderedRegion());
4543       Recommend = ShouldBeInOrderedRegion;
4544     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4545       // OpenMP [2.16, Nesting of Regions]
4546       // If specified, a teams construct must be contained within a target
4547       // construct.
4548       NestingProhibited =
4549           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4550           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4551            ParentRegion != OMPD_target);
4552       OrphanSeen = ParentRegion == OMPD_unknown;
4553       Recommend = ShouldBeInTargetRegion;
4554     } else if (CurrentRegion == OMPD_scan) {
4555       // OpenMP [2.16, Nesting of Regions]
4556       // If specified, a teams construct must be contained within a target
4557       // construct.
4558       NestingProhibited =
4559           SemaRef.LangOpts.OpenMP < 50 ||
4560           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4561            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4562            ParentRegion != OMPD_parallel_for_simd);
4563       OrphanSeen = ParentRegion == OMPD_unknown;
4564       Recommend = ShouldBeInLoopSimdRegion;
4565     }
4566     if (!NestingProhibited &&
4567         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4568         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4569         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4570       // OpenMP [2.16, Nesting of Regions]
4571       // distribute, parallel, parallel sections, parallel workshare, and the
4572       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4573       // constructs that can be closely nested in the teams region.
4574       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4575                           !isOpenMPDistributeDirective(CurrentRegion);
4576       Recommend = ShouldBeInParallelRegion;
4577     }
4578     if (!NestingProhibited &&
4579         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4580       // OpenMP 4.5 [2.17 Nesting of Regions]
4581       // The region associated with the distribute construct must be strictly
4582       // nested inside a teams region
4583       NestingProhibited =
4584           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4585       Recommend = ShouldBeInTeamsRegion;
4586     }
4587     if (!NestingProhibited &&
4588         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4589          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4590       // OpenMP 4.5 [2.17 Nesting of Regions]
4591       // If a target, target update, target data, target enter data, or
4592       // target exit data construct is encountered during execution of a
4593       // target region, the behavior is unspecified.
4594       NestingProhibited = Stack->hasDirective(
4595           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4596                              SourceLocation) {
4597             if (isOpenMPTargetExecutionDirective(K)) {
4598               OffendingRegion = K;
4599               return true;
4600             }
4601             return false;
4602           },
4603           false /* don't skip top directive */);
4604       CloseNesting = false;
4605     }
4606     if (NestingProhibited) {
4607       if (OrphanSeen) {
4608         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4609             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4610       } else {
4611         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4612             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4613             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4614       }
4615       return true;
4616     }
4617   }
4618   return false;
4619 }
4620 
4621 struct Kind2Unsigned {
4622   using argument_type = OpenMPDirectiveKind;
4623   unsigned operator()(argument_type DK) { return unsigned(DK); }
4624 };
4625 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4626                            ArrayRef<OMPClause *> Clauses,
4627                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4628   bool ErrorFound = false;
4629   unsigned NamedModifiersNumber = 0;
4630   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4631   FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
4632   SmallVector<SourceLocation, 4> NameModifierLoc;
4633   for (const OMPClause *C : Clauses) {
4634     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4635       // At most one if clause without a directive-name-modifier can appear on
4636       // the directive.
4637       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4638       if (FoundNameModifiers[CurNM]) {
4639         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4640             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4641             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4642         ErrorFound = true;
4643       } else if (CurNM != OMPD_unknown) {
4644         NameModifierLoc.push_back(IC->getNameModifierLoc());
4645         ++NamedModifiersNumber;
4646       }
4647       FoundNameModifiers[CurNM] = IC;
4648       if (CurNM == OMPD_unknown)
4649         continue;
4650       // Check if the specified name modifier is allowed for the current
4651       // directive.
4652       // At most one if clause with the particular directive-name-modifier can
4653       // appear on the directive.
4654       bool MatchFound = false;
4655       for (auto NM : AllowedNameModifiers) {
4656         if (CurNM == NM) {
4657           MatchFound = true;
4658           break;
4659         }
4660       }
4661       if (!MatchFound) {
4662         S.Diag(IC->getNameModifierLoc(),
4663                diag::err_omp_wrong_if_directive_name_modifier)
4664             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4665         ErrorFound = true;
4666       }
4667     }
4668   }
4669   // If any if clause on the directive includes a directive-name-modifier then
4670   // all if clauses on the directive must include a directive-name-modifier.
4671   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4672     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4673       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4674              diag::err_omp_no_more_if_clause);
4675     } else {
4676       std::string Values;
4677       std::string Sep(", ");
4678       unsigned AllowedCnt = 0;
4679       unsigned TotalAllowedNum =
4680           AllowedNameModifiers.size() - NamedModifiersNumber;
4681       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4682            ++Cnt) {
4683         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4684         if (!FoundNameModifiers[NM]) {
4685           Values += "'";
4686           Values += getOpenMPDirectiveName(NM);
4687           Values += "'";
4688           if (AllowedCnt + 2 == TotalAllowedNum)
4689             Values += " or ";
4690           else if (AllowedCnt + 1 != TotalAllowedNum)
4691             Values += Sep;
4692           ++AllowedCnt;
4693         }
4694       }
4695       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4696              diag::err_omp_unnamed_if_clause)
4697           << (TotalAllowedNum > 1) << Values;
4698     }
4699     for (SourceLocation Loc : NameModifierLoc) {
4700       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4701     }
4702     ErrorFound = true;
4703   }
4704   return ErrorFound;
4705 }
4706 
4707 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4708                                                    SourceLocation &ELoc,
4709                                                    SourceRange &ERange,
4710                                                    bool AllowArraySection) {
4711   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4712       RefExpr->containsUnexpandedParameterPack())
4713     return std::make_pair(nullptr, true);
4714 
4715   // OpenMP [3.1, C/C++]
4716   //  A list item is a variable name.
4717   // OpenMP  [2.9.3.3, Restrictions, p.1]
4718   //  A variable that is part of another variable (as an array or
4719   //  structure element) cannot appear in a private clause.
4720   RefExpr = RefExpr->IgnoreParens();
4721   enum {
4722     NoArrayExpr = -1,
4723     ArraySubscript = 0,
4724     OMPArraySection = 1
4725   } IsArrayExpr = NoArrayExpr;
4726   if (AllowArraySection) {
4727     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4728       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4729       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4730         Base = TempASE->getBase()->IgnoreParenImpCasts();
4731       RefExpr = Base;
4732       IsArrayExpr = ArraySubscript;
4733     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4734       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4735       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4736         Base = TempOASE->getBase()->IgnoreParenImpCasts();
4737       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4738         Base = TempASE->getBase()->IgnoreParenImpCasts();
4739       RefExpr = Base;
4740       IsArrayExpr = OMPArraySection;
4741     }
4742   }
4743   ELoc = RefExpr->getExprLoc();
4744   ERange = RefExpr->getSourceRange();
4745   RefExpr = RefExpr->IgnoreParenImpCasts();
4746   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4747   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4748   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4749       (S.getCurrentThisType().isNull() || !ME ||
4750        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4751        !isa<FieldDecl>(ME->getMemberDecl()))) {
4752     if (IsArrayExpr != NoArrayExpr) {
4753       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4754                                                          << ERange;
4755     } else {
4756       S.Diag(ELoc,
4757              AllowArraySection
4758                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
4759                  : diag::err_omp_expected_var_name_member_expr)
4760           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4761     }
4762     return std::make_pair(nullptr, false);
4763   }
4764   return std::make_pair(
4765       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4766 }
4767 
4768 namespace {
4769 /// Checks if the allocator is used in uses_allocators clause to be allowed in
4770 /// target regions.
4771 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
4772   DSAStackTy *S = nullptr;
4773 
4774 public:
4775   bool VisitDeclRefExpr(const DeclRefExpr *E) {
4776     return S->isUsesAllocatorsDecl(E->getDecl())
4777                .getValueOr(
4778                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
4779            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
4780   }
4781   bool VisitStmt(const Stmt *S) {
4782     for (const Stmt *Child : S->children()) {
4783       if (Child && Visit(Child))
4784         return true;
4785     }
4786     return false;
4787   }
4788   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
4789 };
4790 } // namespace
4791 
4792 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
4793                                  ArrayRef<OMPClause *> Clauses) {
4794   assert(!S.CurContext->isDependentContext() &&
4795          "Expected non-dependent context.");
4796   auto AllocateRange =
4797       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
4798   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4799       DeclToCopy;
4800   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4801     return isOpenMPPrivate(C->getClauseKind());
4802   });
4803   for (OMPClause *Cl : PrivateRange) {
4804     MutableArrayRef<Expr *>::iterator I, It, Et;
4805     if (Cl->getClauseKind() == OMPC_private) {
4806       auto *PC = cast<OMPPrivateClause>(Cl);
4807       I = PC->private_copies().begin();
4808       It = PC->varlist_begin();
4809       Et = PC->varlist_end();
4810     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4811       auto *PC = cast<OMPFirstprivateClause>(Cl);
4812       I = PC->private_copies().begin();
4813       It = PC->varlist_begin();
4814       Et = PC->varlist_end();
4815     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4816       auto *PC = cast<OMPLastprivateClause>(Cl);
4817       I = PC->private_copies().begin();
4818       It = PC->varlist_begin();
4819       Et = PC->varlist_end();
4820     } else if (Cl->getClauseKind() == OMPC_linear) {
4821       auto *PC = cast<OMPLinearClause>(Cl);
4822       I = PC->privates().begin();
4823       It = PC->varlist_begin();
4824       Et = PC->varlist_end();
4825     } else if (Cl->getClauseKind() == OMPC_reduction) {
4826       auto *PC = cast<OMPReductionClause>(Cl);
4827       I = PC->privates().begin();
4828       It = PC->varlist_begin();
4829       Et = PC->varlist_end();
4830     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4831       auto *PC = cast<OMPTaskReductionClause>(Cl);
4832       I = PC->privates().begin();
4833       It = PC->varlist_begin();
4834       Et = PC->varlist_end();
4835     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4836       auto *PC = cast<OMPInReductionClause>(Cl);
4837       I = PC->privates().begin();
4838       It = PC->varlist_begin();
4839       Et = PC->varlist_end();
4840     } else {
4841       llvm_unreachable("Expected private clause.");
4842     }
4843     for (Expr *E : llvm::make_range(It, Et)) {
4844       if (!*I) {
4845         ++I;
4846         continue;
4847       }
4848       SourceLocation ELoc;
4849       SourceRange ERange;
4850       Expr *SimpleRefExpr = E;
4851       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4852                                 /*AllowArraySection=*/true);
4853       DeclToCopy.try_emplace(Res.first,
4854                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4855       ++I;
4856     }
4857   }
4858   for (OMPClause *C : AllocateRange) {
4859     auto *AC = cast<OMPAllocateClause>(C);
4860     if (S.getLangOpts().OpenMP >= 50 &&
4861         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
4862         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
4863         AC->getAllocator()) {
4864       Expr *Allocator = AC->getAllocator();
4865       // OpenMP, 2.12.5 target Construct
4866       // Memory allocators that do not appear in a uses_allocators clause cannot
4867       // appear as an allocator in an allocate clause or be used in the target
4868       // region unless a requires directive with the dynamic_allocators clause
4869       // is present in the same compilation unit.
4870       AllocatorChecker Checker(Stack);
4871       if (Checker.Visit(Allocator))
4872         S.Diag(Allocator->getExprLoc(),
4873                diag::err_omp_allocator_not_in_uses_allocators)
4874             << Allocator->getSourceRange();
4875     }
4876     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4877         getAllocatorKind(S, Stack, AC->getAllocator());
4878     // OpenMP, 2.11.4 allocate Clause, Restrictions.
4879     // For task, taskloop or target directives, allocation requests to memory
4880     // allocators with the trait access set to thread result in unspecified
4881     // behavior.
4882     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4883         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4884          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4885       S.Diag(AC->getAllocator()->getExprLoc(),
4886              diag::warn_omp_allocate_thread_on_task_target_directive)
4887           << getOpenMPDirectiveName(Stack->getCurrentDirective());
4888     }
4889     for (Expr *E : AC->varlists()) {
4890       SourceLocation ELoc;
4891       SourceRange ERange;
4892       Expr *SimpleRefExpr = E;
4893       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4894       ValueDecl *VD = Res.first;
4895       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4896       if (!isOpenMPPrivate(Data.CKind)) {
4897         S.Diag(E->getExprLoc(),
4898                diag::err_omp_expected_private_copy_for_allocate);
4899         continue;
4900       }
4901       VarDecl *PrivateVD = DeclToCopy[VD];
4902       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4903                                             AllocatorKind, AC->getAllocator()))
4904         continue;
4905       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4906                                 E->getSourceRange());
4907     }
4908   }
4909 }
4910 
4911 StmtResult Sema::ActOnOpenMPExecutableDirective(
4912     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4913     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4914     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4915   StmtResult Res = StmtError();
4916   // First check CancelRegion which is then used in checkNestingOfRegions.
4917   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4918       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
4919                             StartLoc))
4920     return StmtError();
4921 
4922   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
4923   VarsWithInheritedDSAType VarsWithInheritedDSA;
4924   bool ErrorFound = false;
4925   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
4926   if (AStmt && !CurContext->isDependentContext()) {
4927     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4928 
4929     // Check default data sharing attributes for referenced variables.
4930     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
4931     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4932     Stmt *S = AStmt;
4933     while (--ThisCaptureLevel >= 0)
4934       S = cast<CapturedStmt>(S)->getCapturedStmt();
4935     DSAChecker.Visit(S);
4936     if (!isOpenMPTargetDataManagementDirective(Kind) &&
4937         !isOpenMPTaskingDirective(Kind)) {
4938       // Visit subcaptures to generate implicit clauses for captured vars.
4939       auto *CS = cast<CapturedStmt>(AStmt);
4940       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4941       getOpenMPCaptureRegions(CaptureRegions, Kind);
4942       // Ignore outer tasking regions for target directives.
4943       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4944         CS = cast<CapturedStmt>(CS->getCapturedStmt());
4945       DSAChecker.visitSubCaptures(CS);
4946     }
4947     if (DSAChecker.isErrorFound())
4948       return StmtError();
4949     // Generate list of implicitly defined firstprivate variables.
4950     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
4951 
4952     SmallVector<Expr *, 4> ImplicitFirstprivates(
4953         DSAChecker.getImplicitFirstprivate().begin(),
4954         DSAChecker.getImplicitFirstprivate().end());
4955     SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4956     for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4957       ArrayRef<Expr *> ImplicitMap =
4958           DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4959       ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4960     }
4961     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
4962     for (OMPClause *C : Clauses) {
4963       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
4964         for (Expr *E : IRC->taskgroup_descriptors())
4965           if (E)
4966             ImplicitFirstprivates.emplace_back(E);
4967       }
4968       // OpenMP 5.0, 2.10.1 task Construct
4969       // [detach clause]... The event-handle will be considered as if it was
4970       // specified on a firstprivate clause.
4971       if (auto *DC = dyn_cast<OMPDetachClause>(C))
4972         ImplicitFirstprivates.push_back(DC->getEventHandler());
4973     }
4974     if (!ImplicitFirstprivates.empty()) {
4975       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
4976               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4977               SourceLocation())) {
4978         ClausesWithImplicit.push_back(Implicit);
4979         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
4980                      ImplicitFirstprivates.size();
4981       } else {
4982         ErrorFound = true;
4983       }
4984     }
4985     int ClauseKindCnt = -1;
4986     for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4987       ++ClauseKindCnt;
4988       if (ImplicitMap.empty())
4989         continue;
4990       CXXScopeSpec MapperIdScopeSpec;
4991       DeclarationNameInfo MapperId;
4992       auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
4993       if (OMPClause *Implicit = ActOnOpenMPMapClause(
4994               llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4995               /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4996               ImplicitMap, OMPVarListLocTy())) {
4997         ClausesWithImplicit.emplace_back(Implicit);
4998         ErrorFound |=
4999             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
5000       } else {
5001         ErrorFound = true;
5002       }
5003     }
5004   }
5005 
5006   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5007   switch (Kind) {
5008   case OMPD_parallel:
5009     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5010                                        EndLoc);
5011     AllowedNameModifiers.push_back(OMPD_parallel);
5012     break;
5013   case OMPD_simd:
5014     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5015                                    VarsWithInheritedDSA);
5016     if (LangOpts.OpenMP >= 50)
5017       AllowedNameModifiers.push_back(OMPD_simd);
5018     break;
5019   case OMPD_for:
5020     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5021                                   VarsWithInheritedDSA);
5022     break;
5023   case OMPD_for_simd:
5024     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5025                                       EndLoc, VarsWithInheritedDSA);
5026     if (LangOpts.OpenMP >= 50)
5027       AllowedNameModifiers.push_back(OMPD_simd);
5028     break;
5029   case OMPD_sections:
5030     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5031                                        EndLoc);
5032     break;
5033   case OMPD_section:
5034     assert(ClausesWithImplicit.empty() &&
5035            "No clauses are allowed for 'omp section' directive");
5036     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5037     break;
5038   case OMPD_single:
5039     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5040                                      EndLoc);
5041     break;
5042   case OMPD_master:
5043     assert(ClausesWithImplicit.empty() &&
5044            "No clauses are allowed for 'omp master' directive");
5045     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5046     break;
5047   case OMPD_critical:
5048     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5049                                        StartLoc, EndLoc);
5050     break;
5051   case OMPD_parallel_for:
5052     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5053                                           EndLoc, VarsWithInheritedDSA);
5054     AllowedNameModifiers.push_back(OMPD_parallel);
5055     break;
5056   case OMPD_parallel_for_simd:
5057     Res = ActOnOpenMPParallelForSimdDirective(
5058         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5059     AllowedNameModifiers.push_back(OMPD_parallel);
5060     if (LangOpts.OpenMP >= 50)
5061       AllowedNameModifiers.push_back(OMPD_simd);
5062     break;
5063   case OMPD_parallel_master:
5064     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5065                                                StartLoc, EndLoc);
5066     AllowedNameModifiers.push_back(OMPD_parallel);
5067     break;
5068   case OMPD_parallel_sections:
5069     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5070                                                StartLoc, EndLoc);
5071     AllowedNameModifiers.push_back(OMPD_parallel);
5072     break;
5073   case OMPD_task:
5074     Res =
5075         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5076     AllowedNameModifiers.push_back(OMPD_task);
5077     break;
5078   case OMPD_taskyield:
5079     assert(ClausesWithImplicit.empty() &&
5080            "No clauses are allowed for 'omp taskyield' directive");
5081     assert(AStmt == nullptr &&
5082            "No associated statement allowed for 'omp taskyield' directive");
5083     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5084     break;
5085   case OMPD_barrier:
5086     assert(ClausesWithImplicit.empty() &&
5087            "No clauses are allowed for 'omp barrier' directive");
5088     assert(AStmt == nullptr &&
5089            "No associated statement allowed for 'omp barrier' directive");
5090     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5091     break;
5092   case OMPD_taskwait:
5093     assert(ClausesWithImplicit.empty() &&
5094            "No clauses are allowed for 'omp taskwait' directive");
5095     assert(AStmt == nullptr &&
5096            "No associated statement allowed for 'omp taskwait' directive");
5097     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5098     break;
5099   case OMPD_taskgroup:
5100     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5101                                         EndLoc);
5102     break;
5103   case OMPD_flush:
5104     assert(AStmt == nullptr &&
5105            "No associated statement allowed for 'omp flush' directive");
5106     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5107     break;
5108   case OMPD_depobj:
5109     assert(AStmt == nullptr &&
5110            "No associated statement allowed for 'omp depobj' directive");
5111     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5112     break;
5113   case OMPD_scan:
5114     assert(AStmt == nullptr &&
5115            "No associated statement allowed for 'omp scan' directive");
5116     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5117     break;
5118   case OMPD_ordered:
5119     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5120                                       EndLoc);
5121     break;
5122   case OMPD_atomic:
5123     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5124                                      EndLoc);
5125     break;
5126   case OMPD_teams:
5127     Res =
5128         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5129     break;
5130   case OMPD_target:
5131     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5132                                      EndLoc);
5133     AllowedNameModifiers.push_back(OMPD_target);
5134     break;
5135   case OMPD_target_parallel:
5136     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5137                                              StartLoc, EndLoc);
5138     AllowedNameModifiers.push_back(OMPD_target);
5139     AllowedNameModifiers.push_back(OMPD_parallel);
5140     break;
5141   case OMPD_target_parallel_for:
5142     Res = ActOnOpenMPTargetParallelForDirective(
5143         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5144     AllowedNameModifiers.push_back(OMPD_target);
5145     AllowedNameModifiers.push_back(OMPD_parallel);
5146     break;
5147   case OMPD_cancellation_point:
5148     assert(ClausesWithImplicit.empty() &&
5149            "No clauses are allowed for 'omp cancellation point' directive");
5150     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5151                                "cancellation point' directive");
5152     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5153     break;
5154   case OMPD_cancel:
5155     assert(AStmt == nullptr &&
5156            "No associated statement allowed for 'omp cancel' directive");
5157     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5158                                      CancelRegion);
5159     AllowedNameModifiers.push_back(OMPD_cancel);
5160     break;
5161   case OMPD_target_data:
5162     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5163                                          EndLoc);
5164     AllowedNameModifiers.push_back(OMPD_target_data);
5165     break;
5166   case OMPD_target_enter_data:
5167     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
5168                                               EndLoc, AStmt);
5169     AllowedNameModifiers.push_back(OMPD_target_enter_data);
5170     break;
5171   case OMPD_target_exit_data:
5172     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
5173                                              EndLoc, AStmt);
5174     AllowedNameModifiers.push_back(OMPD_target_exit_data);
5175     break;
5176   case OMPD_taskloop:
5177     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
5178                                        EndLoc, VarsWithInheritedDSA);
5179     AllowedNameModifiers.push_back(OMPD_taskloop);
5180     break;
5181   case OMPD_taskloop_simd:
5182     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5183                                            EndLoc, VarsWithInheritedDSA);
5184     AllowedNameModifiers.push_back(OMPD_taskloop);
5185     if (LangOpts.OpenMP >= 50)
5186       AllowedNameModifiers.push_back(OMPD_simd);
5187     break;
5188   case OMPD_master_taskloop:
5189     Res = ActOnOpenMPMasterTaskLoopDirective(
5190         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5191     AllowedNameModifiers.push_back(OMPD_taskloop);
5192     break;
5193   case OMPD_master_taskloop_simd:
5194     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
5195         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5196     AllowedNameModifiers.push_back(OMPD_taskloop);
5197     if (LangOpts.OpenMP >= 50)
5198       AllowedNameModifiers.push_back(OMPD_simd);
5199     break;
5200   case OMPD_parallel_master_taskloop:
5201     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
5202         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5203     AllowedNameModifiers.push_back(OMPD_taskloop);
5204     AllowedNameModifiers.push_back(OMPD_parallel);
5205     break;
5206   case OMPD_parallel_master_taskloop_simd:
5207     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
5208         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5209     AllowedNameModifiers.push_back(OMPD_taskloop);
5210     AllowedNameModifiers.push_back(OMPD_parallel);
5211     if (LangOpts.OpenMP >= 50)
5212       AllowedNameModifiers.push_back(OMPD_simd);
5213     break;
5214   case OMPD_distribute:
5215     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
5216                                          EndLoc, VarsWithInheritedDSA);
5217     break;
5218   case OMPD_target_update:
5219     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
5220                                            EndLoc, AStmt);
5221     AllowedNameModifiers.push_back(OMPD_target_update);
5222     break;
5223   case OMPD_distribute_parallel_for:
5224     Res = ActOnOpenMPDistributeParallelForDirective(
5225         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5226     AllowedNameModifiers.push_back(OMPD_parallel);
5227     break;
5228   case OMPD_distribute_parallel_for_simd:
5229     Res = ActOnOpenMPDistributeParallelForSimdDirective(
5230         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5231     AllowedNameModifiers.push_back(OMPD_parallel);
5232     if (LangOpts.OpenMP >= 50)
5233       AllowedNameModifiers.push_back(OMPD_simd);
5234     break;
5235   case OMPD_distribute_simd:
5236     Res = ActOnOpenMPDistributeSimdDirective(
5237         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5238     if (LangOpts.OpenMP >= 50)
5239       AllowedNameModifiers.push_back(OMPD_simd);
5240     break;
5241   case OMPD_target_parallel_for_simd:
5242     Res = ActOnOpenMPTargetParallelForSimdDirective(
5243         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5244     AllowedNameModifiers.push_back(OMPD_target);
5245     AllowedNameModifiers.push_back(OMPD_parallel);
5246     if (LangOpts.OpenMP >= 50)
5247       AllowedNameModifiers.push_back(OMPD_simd);
5248     break;
5249   case OMPD_target_simd:
5250     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5251                                          EndLoc, VarsWithInheritedDSA);
5252     AllowedNameModifiers.push_back(OMPD_target);
5253     if (LangOpts.OpenMP >= 50)
5254       AllowedNameModifiers.push_back(OMPD_simd);
5255     break;
5256   case OMPD_teams_distribute:
5257     Res = ActOnOpenMPTeamsDistributeDirective(
5258         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5259     break;
5260   case OMPD_teams_distribute_simd:
5261     Res = ActOnOpenMPTeamsDistributeSimdDirective(
5262         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5263     if (LangOpts.OpenMP >= 50)
5264       AllowedNameModifiers.push_back(OMPD_simd);
5265     break;
5266   case OMPD_teams_distribute_parallel_for_simd:
5267     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
5268         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5269     AllowedNameModifiers.push_back(OMPD_parallel);
5270     if (LangOpts.OpenMP >= 50)
5271       AllowedNameModifiers.push_back(OMPD_simd);
5272     break;
5273   case OMPD_teams_distribute_parallel_for:
5274     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
5275         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5276     AllowedNameModifiers.push_back(OMPD_parallel);
5277     break;
5278   case OMPD_target_teams:
5279     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
5280                                           EndLoc);
5281     AllowedNameModifiers.push_back(OMPD_target);
5282     break;
5283   case OMPD_target_teams_distribute:
5284     Res = ActOnOpenMPTargetTeamsDistributeDirective(
5285         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5286     AllowedNameModifiers.push_back(OMPD_target);
5287     break;
5288   case OMPD_target_teams_distribute_parallel_for:
5289     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
5290         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5291     AllowedNameModifiers.push_back(OMPD_target);
5292     AllowedNameModifiers.push_back(OMPD_parallel);
5293     break;
5294   case OMPD_target_teams_distribute_parallel_for_simd:
5295     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
5296         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5297     AllowedNameModifiers.push_back(OMPD_target);
5298     AllowedNameModifiers.push_back(OMPD_parallel);
5299     if (LangOpts.OpenMP >= 50)
5300       AllowedNameModifiers.push_back(OMPD_simd);
5301     break;
5302   case OMPD_target_teams_distribute_simd:
5303     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
5304         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5305     AllowedNameModifiers.push_back(OMPD_target);
5306     if (LangOpts.OpenMP >= 50)
5307       AllowedNameModifiers.push_back(OMPD_simd);
5308     break;
5309   case OMPD_declare_target:
5310   case OMPD_end_declare_target:
5311   case OMPD_threadprivate:
5312   case OMPD_allocate:
5313   case OMPD_declare_reduction:
5314   case OMPD_declare_mapper:
5315   case OMPD_declare_simd:
5316   case OMPD_requires:
5317   case OMPD_declare_variant:
5318   case OMPD_begin_declare_variant:
5319   case OMPD_end_declare_variant:
5320     llvm_unreachable("OpenMP Directive is not allowed");
5321   case OMPD_unknown:
5322     llvm_unreachable("Unknown OpenMP directive");
5323   }
5324 
5325   ErrorFound = Res.isInvalid() || ErrorFound;
5326 
5327   // Check variables in the clauses if default(none) was specified.
5328   if (DSAStack->getDefaultDSA() == DSA_none) {
5329     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
5330     for (OMPClause *C : Clauses) {
5331       switch (C->getClauseKind()) {
5332       case OMPC_num_threads:
5333       case OMPC_dist_schedule:
5334         // Do not analyse if no parent teams directive.
5335         if (isOpenMPTeamsDirective(Kind))
5336           break;
5337         continue;
5338       case OMPC_if:
5339         if (isOpenMPTeamsDirective(Kind) &&
5340             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
5341           break;
5342         if (isOpenMPParallelDirective(Kind) &&
5343             isOpenMPTaskLoopDirective(Kind) &&
5344             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
5345           break;
5346         continue;
5347       case OMPC_schedule:
5348       case OMPC_detach:
5349         break;
5350       case OMPC_grainsize:
5351       case OMPC_num_tasks:
5352       case OMPC_final:
5353       case OMPC_priority:
5354         // Do not analyze if no parent parallel directive.
5355         if (isOpenMPParallelDirective(Kind))
5356           break;
5357         continue;
5358       case OMPC_ordered:
5359       case OMPC_device:
5360       case OMPC_num_teams:
5361       case OMPC_thread_limit:
5362       case OMPC_hint:
5363       case OMPC_collapse:
5364       case OMPC_safelen:
5365       case OMPC_simdlen:
5366       case OMPC_default:
5367       case OMPC_proc_bind:
5368       case OMPC_private:
5369       case OMPC_firstprivate:
5370       case OMPC_lastprivate:
5371       case OMPC_shared:
5372       case OMPC_reduction:
5373       case OMPC_task_reduction:
5374       case OMPC_in_reduction:
5375       case OMPC_linear:
5376       case OMPC_aligned:
5377       case OMPC_copyin:
5378       case OMPC_copyprivate:
5379       case OMPC_nowait:
5380       case OMPC_untied:
5381       case OMPC_mergeable:
5382       case OMPC_allocate:
5383       case OMPC_read:
5384       case OMPC_write:
5385       case OMPC_update:
5386       case OMPC_capture:
5387       case OMPC_seq_cst:
5388       case OMPC_acq_rel:
5389       case OMPC_acquire:
5390       case OMPC_release:
5391       case OMPC_relaxed:
5392       case OMPC_depend:
5393       case OMPC_threads:
5394       case OMPC_simd:
5395       case OMPC_map:
5396       case OMPC_nogroup:
5397       case OMPC_defaultmap:
5398       case OMPC_to:
5399       case OMPC_from:
5400       case OMPC_use_device_ptr:
5401       case OMPC_use_device_addr:
5402       case OMPC_is_device_ptr:
5403       case OMPC_nontemporal:
5404       case OMPC_order:
5405       case OMPC_destroy:
5406       case OMPC_inclusive:
5407       case OMPC_exclusive:
5408       case OMPC_uses_allocators:
5409       case OMPC_affinity:
5410         continue;
5411       case OMPC_allocator:
5412       case OMPC_flush:
5413       case OMPC_depobj:
5414       case OMPC_threadprivate:
5415       case OMPC_uniform:
5416       case OMPC_unknown:
5417       case OMPC_unified_address:
5418       case OMPC_unified_shared_memory:
5419       case OMPC_reverse_offload:
5420       case OMPC_dynamic_allocators:
5421       case OMPC_atomic_default_mem_order:
5422       case OMPC_device_type:
5423       case OMPC_match:
5424         llvm_unreachable("Unexpected clause");
5425       }
5426       for (Stmt *CC : C->children()) {
5427         if (CC)
5428           DSAChecker.Visit(CC);
5429       }
5430     }
5431     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
5432       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5433   }
5434   for (const auto &P : VarsWithInheritedDSA) {
5435     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5436       continue;
5437     ErrorFound = true;
5438     if (DSAStack->getDefaultDSA() == DSA_none) {
5439       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5440           << P.first << P.second->getSourceRange();
5441       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5442     } else if (getLangOpts().OpenMP >= 50) {
5443       Diag(P.second->getExprLoc(),
5444            diag::err_omp_defaultmap_no_attr_for_variable)
5445           << P.first << P.second->getSourceRange();
5446       Diag(DSAStack->getDefaultDSALocation(),
5447            diag::note_omp_defaultmap_attr_none);
5448     }
5449   }
5450 
5451   if (!AllowedNameModifiers.empty())
5452     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5453                  ErrorFound;
5454 
5455   if (ErrorFound)
5456     return StmtError();
5457 
5458   if (!CurContext->isDependentContext() &&
5459       isOpenMPTargetExecutionDirective(Kind) &&
5460       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5461         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5462         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5463         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5464     // Register target to DSA Stack.
5465     DSAStack->addTargetDirLocation(StartLoc);
5466   }
5467 
5468   return Res;
5469 }
5470 
5471 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5472     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
5473     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
5474     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5475     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
5476   assert(Aligneds.size() == Alignments.size());
5477   assert(Linears.size() == LinModifiers.size());
5478   assert(Linears.size() == Steps.size());
5479   if (!DG || DG.get().isNull())
5480     return DeclGroupPtrTy();
5481 
5482   const int SimdId = 0;
5483   if (!DG.get().isSingleDecl()) {
5484     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5485         << SimdId;
5486     return DG;
5487   }
5488   Decl *ADecl = DG.get().getSingleDecl();
5489   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5490     ADecl = FTD->getTemplatedDecl();
5491 
5492   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5493   if (!FD) {
5494     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
5495     return DeclGroupPtrTy();
5496   }
5497 
5498   // OpenMP [2.8.2, declare simd construct, Description]
5499   // The parameter of the simdlen clause must be a constant positive integer
5500   // expression.
5501   ExprResult SL;
5502   if (Simdlen)
5503     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
5504   // OpenMP [2.8.2, declare simd construct, Description]
5505   // The special this pointer can be used as if was one of the arguments to the
5506   // function in any of the linear, aligned, or uniform clauses.
5507   // The uniform clause declares one or more arguments to have an invariant
5508   // value for all concurrent invocations of the function in the execution of a
5509   // single SIMD loop.
5510   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5511   const Expr *UniformedLinearThis = nullptr;
5512   for (const Expr *E : Uniforms) {
5513     E = E->IgnoreParenImpCasts();
5514     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5515       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5516         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5517             FD->getParamDecl(PVD->getFunctionScopeIndex())
5518                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
5519           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
5520           continue;
5521         }
5522     if (isa<CXXThisExpr>(E)) {
5523       UniformedLinearThis = E;
5524       continue;
5525     }
5526     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5527         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5528   }
5529   // OpenMP [2.8.2, declare simd construct, Description]
5530   // The aligned clause declares that the object to which each list item points
5531   // is aligned to the number of bytes expressed in the optional parameter of
5532   // the aligned clause.
5533   // The special this pointer can be used as if was one of the arguments to the
5534   // function in any of the linear, aligned, or uniform clauses.
5535   // The type of list items appearing in the aligned clause must be array,
5536   // pointer, reference to array, or reference to pointer.
5537   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5538   const Expr *AlignedThis = nullptr;
5539   for (const Expr *E : Aligneds) {
5540     E = E->IgnoreParenImpCasts();
5541     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5542       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5543         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5544         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5545             FD->getParamDecl(PVD->getFunctionScopeIndex())
5546                     ->getCanonicalDecl() == CanonPVD) {
5547           // OpenMP  [2.8.1, simd construct, Restrictions]
5548           // A list-item cannot appear in more than one aligned clause.
5549           if (AlignedArgs.count(CanonPVD) > 0) {
5550             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5551                 << 1 << getOpenMPClauseName(OMPC_aligned)
5552                 << E->getSourceRange();
5553             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5554                  diag::note_omp_explicit_dsa)
5555                 << getOpenMPClauseName(OMPC_aligned);
5556             continue;
5557           }
5558           AlignedArgs[CanonPVD] = E;
5559           QualType QTy = PVD->getType()
5560                              .getNonReferenceType()
5561                              .getUnqualifiedType()
5562                              .getCanonicalType();
5563           const Type *Ty = QTy.getTypePtrOrNull();
5564           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5565             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5566                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5567             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5568           }
5569           continue;
5570         }
5571       }
5572     if (isa<CXXThisExpr>(E)) {
5573       if (AlignedThis) {
5574         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5575             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
5576         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5577             << getOpenMPClauseName(OMPC_aligned);
5578       }
5579       AlignedThis = E;
5580       continue;
5581     }
5582     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5583         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5584   }
5585   // The optional parameter of the aligned clause, alignment, must be a constant
5586   // positive integer expression. If no optional parameter is specified,
5587   // implementation-defined default alignments for SIMD instructions on the
5588   // target platforms are assumed.
5589   SmallVector<const Expr *, 4> NewAligns;
5590   for (Expr *E : Alignments) {
5591     ExprResult Align;
5592     if (E)
5593       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5594     NewAligns.push_back(Align.get());
5595   }
5596   // OpenMP [2.8.2, declare simd construct, Description]
5597   // The linear clause declares one or more list items to be private to a SIMD
5598   // lane and to have a linear relationship with respect to the iteration space
5599   // of a loop.
5600   // The special this pointer can be used as if was one of the arguments to the
5601   // function in any of the linear, aligned, or uniform clauses.
5602   // When a linear-step expression is specified in a linear clause it must be
5603   // either a constant integer expression or an integer-typed parameter that is
5604   // specified in a uniform clause on the directive.
5605   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
5606   const bool IsUniformedThis = UniformedLinearThis != nullptr;
5607   auto MI = LinModifiers.begin();
5608   for (const Expr *E : Linears) {
5609     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5610     ++MI;
5611     E = E->IgnoreParenImpCasts();
5612     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5613       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5614         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5615         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5616             FD->getParamDecl(PVD->getFunctionScopeIndex())
5617                     ->getCanonicalDecl() == CanonPVD) {
5618           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
5619           // A list-item cannot appear in more than one linear clause.
5620           if (LinearArgs.count(CanonPVD) > 0) {
5621             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5622                 << getOpenMPClauseName(OMPC_linear)
5623                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5624             Diag(LinearArgs[CanonPVD]->getExprLoc(),
5625                  diag::note_omp_explicit_dsa)
5626                 << getOpenMPClauseName(OMPC_linear);
5627             continue;
5628           }
5629           // Each argument can appear in at most one uniform or linear clause.
5630           if (UniformedArgs.count(CanonPVD) > 0) {
5631             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5632                 << getOpenMPClauseName(OMPC_linear)
5633                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5634             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5635                  diag::note_omp_explicit_dsa)
5636                 << getOpenMPClauseName(OMPC_uniform);
5637             continue;
5638           }
5639           LinearArgs[CanonPVD] = E;
5640           if (E->isValueDependent() || E->isTypeDependent() ||
5641               E->isInstantiationDependent() ||
5642               E->containsUnexpandedParameterPack())
5643             continue;
5644           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5645                                       PVD->getOriginalType(),
5646                                       /*IsDeclareSimd=*/true);
5647           continue;
5648         }
5649       }
5650     if (isa<CXXThisExpr>(E)) {
5651       if (UniformedLinearThis) {
5652         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5653             << getOpenMPClauseName(OMPC_linear)
5654             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5655             << E->getSourceRange();
5656         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5657             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5658                                                    : OMPC_linear);
5659         continue;
5660       }
5661       UniformedLinearThis = E;
5662       if (E->isValueDependent() || E->isTypeDependent() ||
5663           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5664         continue;
5665       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5666                                   E->getType(), /*IsDeclareSimd=*/true);
5667       continue;
5668     }
5669     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5670         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5671   }
5672   Expr *Step = nullptr;
5673   Expr *NewStep = nullptr;
5674   SmallVector<Expr *, 4> NewSteps;
5675   for (Expr *E : Steps) {
5676     // Skip the same step expression, it was checked already.
5677     if (Step == E || !E) {
5678       NewSteps.push_back(E ? NewStep : nullptr);
5679       continue;
5680     }
5681     Step = E;
5682     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5683       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5684         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5685         if (UniformedArgs.count(CanonPVD) == 0) {
5686           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5687               << Step->getSourceRange();
5688         } else if (E->isValueDependent() || E->isTypeDependent() ||
5689                    E->isInstantiationDependent() ||
5690                    E->containsUnexpandedParameterPack() ||
5691                    CanonPVD->getType()->hasIntegerRepresentation()) {
5692           NewSteps.push_back(Step);
5693         } else {
5694           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5695               << Step->getSourceRange();
5696         }
5697         continue;
5698       }
5699     NewStep = Step;
5700     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5701         !Step->isInstantiationDependent() &&
5702         !Step->containsUnexpandedParameterPack()) {
5703       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5704                     .get();
5705       if (NewStep)
5706         NewStep = VerifyIntegerConstantExpression(NewStep).get();
5707     }
5708     NewSteps.push_back(NewStep);
5709   }
5710   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5711       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
5712       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
5713       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5714       const_cast<Expr **>(Linears.data()), Linears.size(),
5715       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5716       NewSteps.data(), NewSteps.size(), SR);
5717   ADecl->addAttr(NewAttr);
5718   return DG;
5719 }
5720 
5721 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5722                          QualType NewType) {
5723   assert(NewType->isFunctionProtoType() &&
5724          "Expected function type with prototype.");
5725   assert(FD->getType()->isFunctionNoProtoType() &&
5726          "Expected function with type with no prototype.");
5727   assert(FDWithProto->getType()->isFunctionProtoType() &&
5728          "Expected function with prototype.");
5729   // Synthesize parameters with the same types.
5730   FD->setType(NewType);
5731   SmallVector<ParmVarDecl *, 16> Params;
5732   for (const ParmVarDecl *P : FDWithProto->parameters()) {
5733     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5734                                       SourceLocation(), nullptr, P->getType(),
5735                                       /*TInfo=*/nullptr, SC_None, nullptr);
5736     Param->setScopeInfo(0, Params.size());
5737     Param->setImplicit();
5738     Params.push_back(Param);
5739   }
5740 
5741   FD->setParams(Params);
5742 }
5743 
5744 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
5745     : TI(&TI), NameSuffix(TI.getMangledName()) {}
5746 
5747 FunctionDecl *
5748 Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
5749                                                                 Declarator &D) {
5750   IdentifierInfo *BaseII = D.getIdentifier();
5751   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
5752                       LookupOrdinaryName);
5753   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
5754 
5755   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5756   QualType FType = TInfo->getType();
5757 
5758   bool IsConstexpr = D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr;
5759   bool IsConsteval = D.getDeclSpec().getConstexprSpecifier() == CSK_consteval;
5760 
5761   FunctionDecl *BaseFD = nullptr;
5762   for (auto *Candidate : Lookup) {
5763     auto *UDecl = dyn_cast<FunctionDecl>(Candidate->getUnderlyingDecl());
5764     if (!UDecl)
5765       continue;
5766 
5767     // Don't specialize constexpr/consteval functions with
5768     // non-constexpr/consteval functions.
5769     if (UDecl->isConstexpr() && !IsConstexpr)
5770       continue;
5771     if (UDecl->isConsteval() && !IsConsteval)
5772       continue;
5773 
5774     QualType NewType = Context.mergeFunctionTypes(
5775         FType, UDecl->getType(), /* OfBlockPointer */ false,
5776         /* Unqualified */ false, /* AllowCXX */ true);
5777     if (NewType.isNull())
5778       continue;
5779 
5780     // Found a base!
5781     BaseFD = UDecl;
5782     break;
5783   }
5784   if (!BaseFD) {
5785     BaseFD = cast<FunctionDecl>(ActOnDeclarator(S, D));
5786     BaseFD->setImplicit(true);
5787   }
5788 
5789   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
5790   std::string MangledName;
5791   MangledName += D.getIdentifier()->getName();
5792   MangledName += getOpenMPVariantManglingSeparatorStr();
5793   MangledName += DVScope.NameSuffix;
5794   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
5795 
5796   VariantII.setMangledOpenMPVariantName(true);
5797   D.SetIdentifier(&VariantII, D.getBeginLoc());
5798   return BaseFD;
5799 }
5800 
5801 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
5802     FunctionDecl *FD, FunctionDecl *BaseFD) {
5803   // Do not mark function as is used to prevent its emission if this is the
5804   // only place where it is used.
5805   EnterExpressionEvaluationContext Unevaluated(
5806       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5807 
5808   Expr *VariantFuncRef = DeclRefExpr::Create(
5809       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
5810       /* RefersToEnclosingVariableOrCapture */ false,
5811       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
5812 
5813   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
5814   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
5815       Context, VariantFuncRef, DVScope.TI);
5816   BaseFD->addAttr(OMPDeclareVariantA);
5817 }
5818 
5819 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
5820                                  SourceLocation LParenLoc,
5821                                  MultiExprArg ArgExprs,
5822                                  SourceLocation RParenLoc, Expr *ExecConfig) {
5823   // The common case is a regular call we do not want to specialize at all. Try
5824   // to make that case fast by bailing early.
5825   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
5826   if (!CE)
5827     return Call;
5828 
5829   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
5830   if (!CalleeFnDecl)
5831     return Call;
5832 
5833   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
5834     return Call;
5835 
5836   ASTContext &Context = getASTContext();
5837   OMPContext OMPCtx(getLangOpts().OpenMPIsDevice,
5838                     Context.getTargetInfo().getTriple());
5839 
5840   SmallVector<Expr *, 4> Exprs;
5841   SmallVector<VariantMatchInfo, 4> VMIs;
5842   while (CalleeFnDecl) {
5843     for (OMPDeclareVariantAttr *A :
5844          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
5845       Expr *VariantRef = A->getVariantFuncRef();
5846 
5847       VariantMatchInfo VMI;
5848       OMPTraitInfo &TI = A->getTraitInfo();
5849       TI.getAsVariantMatchInfo(Context, VMI);
5850       if (!isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ false))
5851         continue;
5852 
5853       VMIs.push_back(VMI);
5854       Exprs.push_back(VariantRef);
5855     }
5856 
5857     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
5858   }
5859 
5860   ExprResult NewCall;
5861   do {
5862     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
5863     if (BestIdx < 0)
5864       return Call;
5865     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
5866     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
5867 
5868     {
5869       // Try to build a (member) call expression for the current best applicable
5870       // variant expression. We allow this to fail in which case we continue
5871       // with the next best variant expression. The fail case is part of the
5872       // implementation defined behavior in the OpenMP standard when it talks
5873       // about what differences in the function prototypes: "Any differences
5874       // that the specific OpenMP context requires in the prototype of the
5875       // variant from the base function prototype are implementation defined."
5876       // This wording is there to allow the specialized variant to have a
5877       // different type than the base function. This is intended and OK but if
5878       // we cannot create a call the difference is not in the "implementation
5879       // defined range" we allow.
5880       Sema::TentativeAnalysisScope Trap(*this);
5881 
5882       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
5883         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
5884         BestExpr = MemberExpr::CreateImplicit(
5885             Context, MemberCall->getImplicitObjectArgument(),
5886             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
5887             MemberCall->getValueKind(), MemberCall->getObjectKind());
5888       }
5889       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
5890                               ExecConfig);
5891       if (NewCall.isUsable())
5892         break;
5893     }
5894 
5895     VMIs.erase(VMIs.begin() + BestIdx);
5896     Exprs.erase(Exprs.begin() + BestIdx);
5897   } while (!VMIs.empty());
5898 
5899   if (!NewCall.isUsable())
5900     return Call;
5901   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
5902 }
5903 
5904 Optional<std::pair<FunctionDecl *, Expr *>>
5905 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5906                                         Expr *VariantRef, OMPTraitInfo &TI,
5907                                         SourceRange SR) {
5908   if (!DG || DG.get().isNull())
5909     return None;
5910 
5911   const int VariantId = 1;
5912   // Must be applied only to single decl.
5913   if (!DG.get().isSingleDecl()) {
5914     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5915         << VariantId << SR;
5916     return None;
5917   }
5918   Decl *ADecl = DG.get().getSingleDecl();
5919   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5920     ADecl = FTD->getTemplatedDecl();
5921 
5922   // Decl must be a function.
5923   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5924   if (!FD) {
5925     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5926         << VariantId << SR;
5927     return None;
5928   }
5929 
5930   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5931     return FD->hasAttrs() &&
5932            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5933             FD->hasAttr<TargetAttr>());
5934   };
5935   // OpenMP is not compatible with CPU-specific attributes.
5936   if (HasMultiVersionAttributes(FD)) {
5937     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5938         << SR;
5939     return None;
5940   }
5941 
5942   // Allow #pragma omp declare variant only if the function is not used.
5943   if (FD->isUsed(false))
5944     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
5945         << FD->getLocation();
5946 
5947   // Check if the function was emitted already.
5948   const FunctionDecl *Definition;
5949   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5950       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
5951     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5952         << FD->getLocation();
5953 
5954   // The VariantRef must point to function.
5955   if (!VariantRef) {
5956     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
5957     return None;
5958   }
5959 
5960   auto ShouldDelayChecks = [](Expr *&E, bool) {
5961     return E && (E->isTypeDependent() || E->isValueDependent() ||
5962                  E->containsUnexpandedParameterPack() ||
5963                  E->isInstantiationDependent());
5964   };
5965   // Do not check templates, wait until instantiation.
5966   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
5967       TI.anyScoreOrCondition(ShouldDelayChecks))
5968     return std::make_pair(FD, VariantRef);
5969 
5970   // Deal with non-constant score and user condition expressions.
5971   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
5972                                                      bool IsScore) -> bool {
5973     llvm::APSInt Result;
5974     if (!E || E->isIntegerConstantExpr(Result, Context))
5975       return false;
5976 
5977     if (IsScore) {
5978       // We warn on non-constant scores and pretend they were not present.
5979       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
5980           << E;
5981       E = nullptr;
5982     } else {
5983       // We could replace a non-constant user condition with "false" but we
5984       // will soon need to handle these anyway for the dynamic version of
5985       // OpenMP context selectors.
5986       Diag(E->getExprLoc(),
5987            diag::err_omp_declare_variant_user_condition_not_constant)
5988           << E;
5989     }
5990     return true;
5991   };
5992   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
5993     return None;
5994 
5995   // Convert VariantRef expression to the type of the original function to
5996   // resolve possible conflicts.
5997   ExprResult VariantRefCast;
5998   if (LangOpts.CPlusPlus) {
5999     QualType FnPtrType;
6000     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6001     if (Method && !Method->isStatic()) {
6002       const Type *ClassType =
6003           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6004       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6005       ExprResult ER;
6006       {
6007         // Build adrr_of unary op to correctly handle type checks for member
6008         // functions.
6009         Sema::TentativeAnalysisScope Trap(*this);
6010         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6011                                   VariantRef);
6012       }
6013       if (!ER.isUsable()) {
6014         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6015             << VariantId << VariantRef->getSourceRange();
6016         return None;
6017       }
6018       VariantRef = ER.get();
6019     } else {
6020       FnPtrType = Context.getPointerType(FD->getType());
6021     }
6022     ImplicitConversionSequence ICS =
6023         TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
6024                               /*SuppressUserConversions=*/false,
6025                               AllowedExplicit::None,
6026                               /*InOverloadResolution=*/false,
6027                               /*CStyle=*/false,
6028                               /*AllowObjCWritebackConversion=*/false);
6029     if (ICS.isFailure()) {
6030       Diag(VariantRef->getExprLoc(),
6031            diag::err_omp_declare_variant_incompat_types)
6032           << VariantRef->getType()
6033           << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6034           << VariantRef->getSourceRange();
6035       return None;
6036     }
6037     VariantRefCast = PerformImplicitConversion(
6038         VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6039     if (!VariantRefCast.isUsable())
6040       return None;
6041     // Drop previously built artificial addr_of unary op for member functions.
6042     if (Method && !Method->isStatic()) {
6043       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6044       if (auto *UO = dyn_cast<UnaryOperator>(
6045               PossibleAddrOfVariantRef->IgnoreImplicit()))
6046         VariantRefCast = UO->getSubExpr();
6047     }
6048   } else {
6049     VariantRefCast = VariantRef;
6050   }
6051 
6052   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6053   if (!ER.isUsable() ||
6054       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6055     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6056         << VariantId << VariantRef->getSourceRange();
6057     return None;
6058   }
6059 
6060   // The VariantRef must point to function.
6061   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6062   if (!DRE) {
6063     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6064         << VariantId << VariantRef->getSourceRange();
6065     return None;
6066   }
6067   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6068   if (!NewFD) {
6069     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6070         << VariantId << VariantRef->getSourceRange();
6071     return None;
6072   }
6073 
6074   // Check if function types are compatible in C.
6075   if (!LangOpts.CPlusPlus) {
6076     QualType NewType =
6077         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
6078     if (NewType.isNull()) {
6079       Diag(VariantRef->getExprLoc(),
6080            diag::err_omp_declare_variant_incompat_types)
6081           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
6082       return None;
6083     }
6084     if (NewType->isFunctionProtoType()) {
6085       if (FD->getType()->isFunctionNoProtoType())
6086         setPrototype(*this, FD, NewFD, NewType);
6087       else if (NewFD->getType()->isFunctionNoProtoType())
6088         setPrototype(*this, NewFD, FD, NewType);
6089     }
6090   }
6091 
6092   // Check if variant function is not marked with declare variant directive.
6093   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
6094     Diag(VariantRef->getExprLoc(),
6095          diag::warn_omp_declare_variant_marked_as_declare_variant)
6096         << VariantRef->getSourceRange();
6097     SourceRange SR =
6098         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
6099     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
6100     return None;
6101   }
6102 
6103   enum DoesntSupport {
6104     VirtFuncs = 1,
6105     Constructors = 3,
6106     Destructors = 4,
6107     DeletedFuncs = 5,
6108     DefaultedFuncs = 6,
6109     ConstexprFuncs = 7,
6110     ConstevalFuncs = 8,
6111   };
6112   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
6113     if (CXXFD->isVirtual()) {
6114       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6115           << VirtFuncs;
6116       return None;
6117     }
6118 
6119     if (isa<CXXConstructorDecl>(FD)) {
6120       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6121           << Constructors;
6122       return None;
6123     }
6124 
6125     if (isa<CXXDestructorDecl>(FD)) {
6126       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6127           << Destructors;
6128       return None;
6129     }
6130   }
6131 
6132   if (FD->isDeleted()) {
6133     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6134         << DeletedFuncs;
6135     return None;
6136   }
6137 
6138   if (FD->isDefaulted()) {
6139     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6140         << DefaultedFuncs;
6141     return None;
6142   }
6143 
6144   if (FD->isConstexpr()) {
6145     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6146         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
6147     return None;
6148   }
6149 
6150   // Check general compatibility.
6151   if (areMultiversionVariantFunctionsCompatible(
6152           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
6153           PartialDiagnosticAt(SourceLocation(),
6154                               PartialDiagnostic::NullDiagnostic()),
6155           PartialDiagnosticAt(
6156               VariantRef->getExprLoc(),
6157               PDiag(diag::err_omp_declare_variant_doesnt_support)),
6158           PartialDiagnosticAt(VariantRef->getExprLoc(),
6159                               PDiag(diag::err_omp_declare_variant_diff)
6160                                   << FD->getLocation()),
6161           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
6162           /*CLinkageMayDiffer=*/true))
6163     return None;
6164   return std::make_pair(FD, cast<Expr>(DRE));
6165 }
6166 
6167 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
6168                                               Expr *VariantRef,
6169                                               OMPTraitInfo &TI,
6170                                               SourceRange SR) {
6171   auto *NewAttr =
6172       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
6173   FD->addAttr(NewAttr);
6174 }
6175 
6176 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
6177                                               Stmt *AStmt,
6178                                               SourceLocation StartLoc,
6179                                               SourceLocation EndLoc) {
6180   if (!AStmt)
6181     return StmtError();
6182 
6183   auto *CS = cast<CapturedStmt>(AStmt);
6184   // 1.2.2 OpenMP Language Terminology
6185   // Structured block - An executable statement with a single entry at the
6186   // top and a single exit at the bottom.
6187   // The point of exit cannot be a branch out of the structured block.
6188   // longjmp() and throw() must not violate the entry/exit criteria.
6189   CS->getCapturedDecl()->setNothrow();
6190 
6191   setFunctionHasBranchProtectedScope();
6192 
6193   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6194                                       DSAStack->getTaskgroupReductionRef(),
6195                                       DSAStack->isCancelRegion());
6196 }
6197 
6198 namespace {
6199 /// Iteration space of a single for loop.
6200 struct LoopIterationSpace final {
6201   /// True if the condition operator is the strict compare operator (<, > or
6202   /// !=).
6203   bool IsStrictCompare = false;
6204   /// Condition of the loop.
6205   Expr *PreCond = nullptr;
6206   /// This expression calculates the number of iterations in the loop.
6207   /// It is always possible to calculate it before starting the loop.
6208   Expr *NumIterations = nullptr;
6209   /// The loop counter variable.
6210   Expr *CounterVar = nullptr;
6211   /// Private loop counter variable.
6212   Expr *PrivateCounterVar = nullptr;
6213   /// This is initializer for the initial value of #CounterVar.
6214   Expr *CounterInit = nullptr;
6215   /// This is step for the #CounterVar used to generate its update:
6216   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
6217   Expr *CounterStep = nullptr;
6218   /// Should step be subtracted?
6219   bool Subtract = false;
6220   /// Source range of the loop init.
6221   SourceRange InitSrcRange;
6222   /// Source range of the loop condition.
6223   SourceRange CondSrcRange;
6224   /// Source range of the loop increment.
6225   SourceRange IncSrcRange;
6226   /// Minimum value that can have the loop control variable. Used to support
6227   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
6228   /// since only such variables can be used in non-loop invariant expressions.
6229   Expr *MinValue = nullptr;
6230   /// Maximum value that can have the loop control variable. Used to support
6231   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
6232   /// since only such variables can be used in non-loop invariant expressions.
6233   Expr *MaxValue = nullptr;
6234   /// true, if the lower bound depends on the outer loop control var.
6235   bool IsNonRectangularLB = false;
6236   /// true, if the upper bound depends on the outer loop control var.
6237   bool IsNonRectangularUB = false;
6238   /// Index of the loop this loop depends on and forms non-rectangular loop
6239   /// nest.
6240   unsigned LoopDependentIdx = 0;
6241   /// Final condition for the non-rectangular loop nest support. It is used to
6242   /// check that the number of iterations for this particular counter must be
6243   /// finished.
6244   Expr *FinalCondition = nullptr;
6245 };
6246 
6247 /// Helper class for checking canonical form of the OpenMP loops and
6248 /// extracting iteration space of each loop in the loop nest, that will be used
6249 /// for IR generation.
6250 class OpenMPIterationSpaceChecker {
6251   /// Reference to Sema.
6252   Sema &SemaRef;
6253   /// Data-sharing stack.
6254   DSAStackTy &Stack;
6255   /// A location for diagnostics (when there is no some better location).
6256   SourceLocation DefaultLoc;
6257   /// A location for diagnostics (when increment is not compatible).
6258   SourceLocation ConditionLoc;
6259   /// A source location for referring to loop init later.
6260   SourceRange InitSrcRange;
6261   /// A source location for referring to condition later.
6262   SourceRange ConditionSrcRange;
6263   /// A source location for referring to increment later.
6264   SourceRange IncrementSrcRange;
6265   /// Loop variable.
6266   ValueDecl *LCDecl = nullptr;
6267   /// Reference to loop variable.
6268   Expr *LCRef = nullptr;
6269   /// Lower bound (initializer for the var).
6270   Expr *LB = nullptr;
6271   /// Upper bound.
6272   Expr *UB = nullptr;
6273   /// Loop step (increment).
6274   Expr *Step = nullptr;
6275   /// This flag is true when condition is one of:
6276   ///   Var <  UB
6277   ///   Var <= UB
6278   ///   UB  >  Var
6279   ///   UB  >= Var
6280   /// This will have no value when the condition is !=
6281   llvm::Optional<bool> TestIsLessOp;
6282   /// This flag is true when condition is strict ( < or > ).
6283   bool TestIsStrictOp = false;
6284   /// This flag is true when step is subtracted on each iteration.
6285   bool SubtractStep = false;
6286   /// The outer loop counter this loop depends on (if any).
6287   const ValueDecl *DepDecl = nullptr;
6288   /// Contains number of loop (starts from 1) on which loop counter init
6289   /// expression of this loop depends on.
6290   Optional<unsigned> InitDependOnLC;
6291   /// Contains number of loop (starts from 1) on which loop counter condition
6292   /// expression of this loop depends on.
6293   Optional<unsigned> CondDependOnLC;
6294   /// Checks if the provide statement depends on the loop counter.
6295   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
6296   /// Original condition required for checking of the exit condition for
6297   /// non-rectangular loop.
6298   Expr *Condition = nullptr;
6299 
6300 public:
6301   OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
6302                               SourceLocation DefaultLoc)
6303       : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
6304         ConditionLoc(DefaultLoc) {}
6305   /// Check init-expr for canonical loop form and save loop counter
6306   /// variable - #Var and its initialization value - #LB.
6307   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
6308   /// Check test-expr for canonical form, save upper-bound (#UB), flags
6309   /// for less/greater and for strict/non-strict comparison.
6310   bool checkAndSetCond(Expr *S);
6311   /// Check incr-expr for canonical loop form and return true if it
6312   /// does not conform, otherwise save loop step (#Step).
6313   bool checkAndSetInc(Expr *S);
6314   /// Return the loop counter variable.
6315   ValueDecl *getLoopDecl() const { return LCDecl; }
6316   /// Return the reference expression to loop counter variable.
6317   Expr *getLoopDeclRefExpr() const { return LCRef; }
6318   /// Source range of the loop init.
6319   SourceRange getInitSrcRange() const { return InitSrcRange; }
6320   /// Source range of the loop condition.
6321   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
6322   /// Source range of the loop increment.
6323   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
6324   /// True if the step should be subtracted.
6325   bool shouldSubtractStep() const { return SubtractStep; }
6326   /// True, if the compare operator is strict (<, > or !=).
6327   bool isStrictTestOp() const { return TestIsStrictOp; }
6328   /// Build the expression to calculate the number of iterations.
6329   Expr *buildNumIterations(
6330       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
6331       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6332   /// Build the precondition expression for the loops.
6333   Expr *
6334   buildPreCond(Scope *S, Expr *Cond,
6335                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6336   /// Build reference expression to the counter be used for codegen.
6337   DeclRefExpr *
6338   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6339                   DSAStackTy &DSA) const;
6340   /// Build reference expression to the private counter be used for
6341   /// codegen.
6342   Expr *buildPrivateCounterVar() const;
6343   /// Build initialization of the counter be used for codegen.
6344   Expr *buildCounterInit() const;
6345   /// Build step of the counter be used for codegen.
6346   Expr *buildCounterStep() const;
6347   /// Build loop data with counter value for depend clauses in ordered
6348   /// directives.
6349   Expr *
6350   buildOrderedLoopData(Scope *S, Expr *Counter,
6351                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6352                        SourceLocation Loc, Expr *Inc = nullptr,
6353                        OverloadedOperatorKind OOK = OO_Amp);
6354   /// Builds the minimum value for the loop counter.
6355   std::pair<Expr *, Expr *> buildMinMaxValues(
6356       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6357   /// Builds final condition for the non-rectangular loops.
6358   Expr *buildFinalCondition(Scope *S) const;
6359   /// Return true if any expression is dependent.
6360   bool dependent() const;
6361   /// Returns true if the initializer forms non-rectangular loop.
6362   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
6363   /// Returns true if the condition forms non-rectangular loop.
6364   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
6365   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
6366   unsigned getLoopDependentIdx() const {
6367     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
6368   }
6369 
6370 private:
6371   /// Check the right-hand side of an assignment in the increment
6372   /// expression.
6373   bool checkAndSetIncRHS(Expr *RHS);
6374   /// Helper to set loop counter variable and its initializer.
6375   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
6376                       bool EmitDiags);
6377   /// Helper to set upper bound.
6378   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
6379              SourceRange SR, SourceLocation SL);
6380   /// Helper to set loop increment.
6381   bool setStep(Expr *NewStep, bool Subtract);
6382 };
6383 
6384 bool OpenMPIterationSpaceChecker::dependent() const {
6385   if (!LCDecl) {
6386     assert(!LB && !UB && !Step);
6387     return false;
6388   }
6389   return LCDecl->getType()->isDependentType() ||
6390          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
6391          (Step && Step->isValueDependent());
6392 }
6393 
6394 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
6395                                                  Expr *NewLCRefExpr,
6396                                                  Expr *NewLB, bool EmitDiags) {
6397   // State consistency checking to ensure correct usage.
6398   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
6399          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6400   if (!NewLCDecl || !NewLB)
6401     return true;
6402   LCDecl = getCanonicalDecl(NewLCDecl);
6403   LCRef = NewLCRefExpr;
6404   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
6405     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6406       if ((Ctor->isCopyOrMoveConstructor() ||
6407            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6408           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6409         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
6410   LB = NewLB;
6411   if (EmitDiags)
6412     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
6413   return false;
6414 }
6415 
6416 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
6417                                         llvm::Optional<bool> LessOp,
6418                                         bool StrictOp, SourceRange SR,
6419                                         SourceLocation SL) {
6420   // State consistency checking to ensure correct usage.
6421   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
6422          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6423   if (!NewUB)
6424     return true;
6425   UB = NewUB;
6426   if (LessOp)
6427     TestIsLessOp = LessOp;
6428   TestIsStrictOp = StrictOp;
6429   ConditionSrcRange = SR;
6430   ConditionLoc = SL;
6431   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
6432   return false;
6433 }
6434 
6435 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
6436   // State consistency checking to ensure correct usage.
6437   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
6438   if (!NewStep)
6439     return true;
6440   if (!NewStep->isValueDependent()) {
6441     // Check that the step is integer expression.
6442     SourceLocation StepLoc = NewStep->getBeginLoc();
6443     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
6444         StepLoc, getExprAsWritten(NewStep));
6445     if (Val.isInvalid())
6446       return true;
6447     NewStep = Val.get();
6448 
6449     // OpenMP [2.6, Canonical Loop Form, Restrictions]
6450     //  If test-expr is of form var relational-op b and relational-op is < or
6451     //  <= then incr-expr must cause var to increase on each iteration of the
6452     //  loop. If test-expr is of form var relational-op b and relational-op is
6453     //  > or >= then incr-expr must cause var to decrease on each iteration of
6454     //  the loop.
6455     //  If test-expr is of form b relational-op var and relational-op is < or
6456     //  <= then incr-expr must cause var to decrease on each iteration of the
6457     //  loop. If test-expr is of form b relational-op var and relational-op is
6458     //  > or >= then incr-expr must cause var to increase on each iteration of
6459     //  the loop.
6460     llvm::APSInt Result;
6461     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
6462     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
6463     bool IsConstNeg =
6464         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
6465     bool IsConstPos =
6466         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
6467     bool IsConstZero = IsConstant && !Result.getBoolValue();
6468 
6469     // != with increment is treated as <; != with decrement is treated as >
6470     if (!TestIsLessOp.hasValue())
6471       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
6472     if (UB && (IsConstZero ||
6473                (TestIsLessOp.getValue() ?
6474                   (IsConstNeg || (IsUnsigned && Subtract)) :
6475                   (IsConstPos || (IsUnsigned && !Subtract))))) {
6476       SemaRef.Diag(NewStep->getExprLoc(),
6477                    diag::err_omp_loop_incr_not_compatible)
6478           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
6479       SemaRef.Diag(ConditionLoc,
6480                    diag::note_omp_loop_cond_requres_compatible_incr)
6481           << TestIsLessOp.getValue() << ConditionSrcRange;
6482       return true;
6483     }
6484     if (TestIsLessOp.getValue() == Subtract) {
6485       NewStep =
6486           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
6487               .get();
6488       Subtract = !Subtract;
6489     }
6490   }
6491 
6492   Step = NewStep;
6493   SubtractStep = Subtract;
6494   return false;
6495 }
6496 
6497 namespace {
6498 /// Checker for the non-rectangular loops. Checks if the initializer or
6499 /// condition expression references loop counter variable.
6500 class LoopCounterRefChecker final
6501     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
6502   Sema &SemaRef;
6503   DSAStackTy &Stack;
6504   const ValueDecl *CurLCDecl = nullptr;
6505   const ValueDecl *DepDecl = nullptr;
6506   const ValueDecl *PrevDepDecl = nullptr;
6507   bool IsInitializer = true;
6508   unsigned BaseLoopId = 0;
6509   bool checkDecl(const Expr *E, const ValueDecl *VD) {
6510     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
6511       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
6512           << (IsInitializer ? 0 : 1);
6513       return false;
6514     }
6515     const auto &&Data = Stack.isLoopControlVariable(VD);
6516     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6517     // The type of the loop iterator on which we depend may not have a random
6518     // access iterator type.
6519     if (Data.first && VD->getType()->isRecordType()) {
6520       SmallString<128> Name;
6521       llvm::raw_svector_ostream OS(Name);
6522       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6523                                /*Qualified=*/true);
6524       SemaRef.Diag(E->getExprLoc(),
6525                    diag::err_omp_wrong_dependency_iterator_type)
6526           << OS.str();
6527       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6528       return false;
6529     }
6530     if (Data.first &&
6531         (DepDecl || (PrevDepDecl &&
6532                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6533       if (!DepDecl && PrevDepDecl)
6534         DepDecl = PrevDepDecl;
6535       SmallString<128> Name;
6536       llvm::raw_svector_ostream OS(Name);
6537       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6538                                     /*Qualified=*/true);
6539       SemaRef.Diag(E->getExprLoc(),
6540                    diag::err_omp_invariant_or_linear_dependency)
6541           << OS.str();
6542       return false;
6543     }
6544     if (Data.first) {
6545       DepDecl = VD;
6546       BaseLoopId = Data.first;
6547     }
6548     return Data.first;
6549   }
6550 
6551 public:
6552   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6553     const ValueDecl *VD = E->getDecl();
6554     if (isa<VarDecl>(VD))
6555       return checkDecl(E, VD);
6556     return false;
6557   }
6558   bool VisitMemberExpr(const MemberExpr *E) {
6559     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6560       const ValueDecl *VD = E->getMemberDecl();
6561       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6562         return checkDecl(E, VD);
6563     }
6564     return false;
6565   }
6566   bool VisitStmt(const Stmt *S) {
6567     bool Res = false;
6568     for (const Stmt *Child : S->children())
6569       Res = (Child && Visit(Child)) || Res;
6570     return Res;
6571   }
6572   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
6573                                  const ValueDecl *CurLCDecl, bool IsInitializer,
6574                                  const ValueDecl *PrevDepDecl = nullptr)
6575       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
6576         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6577   unsigned getBaseLoopId() const {
6578     assert(CurLCDecl && "Expected loop dependency.");
6579     return BaseLoopId;
6580   }
6581   const ValueDecl *getDepDecl() const {
6582     assert(CurLCDecl && "Expected loop dependency.");
6583     return DepDecl;
6584   }
6585 };
6586 } // namespace
6587 
6588 Optional<unsigned>
6589 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6590                                                      bool IsInitializer) {
6591   // Check for the non-rectangular loops.
6592   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6593                                         DepDecl);
6594   if (LoopStmtChecker.Visit(S)) {
6595     DepDecl = LoopStmtChecker.getDepDecl();
6596     return LoopStmtChecker.getBaseLoopId();
6597   }
6598   return llvm::None;
6599 }
6600 
6601 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
6602   // Check init-expr for canonical loop form and save loop counter
6603   // variable - #Var and its initialization value - #LB.
6604   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6605   //   var = lb
6606   //   integer-type var = lb
6607   //   random-access-iterator-type var = lb
6608   //   pointer-type var = lb
6609   //
6610   if (!S) {
6611     if (EmitDiags) {
6612       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6613     }
6614     return true;
6615   }
6616   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6617     if (!ExprTemp->cleanupsHaveSideEffects())
6618       S = ExprTemp->getSubExpr();
6619 
6620   InitSrcRange = S->getSourceRange();
6621   if (Expr *E = dyn_cast<Expr>(S))
6622     S = E->IgnoreParens();
6623   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6624     if (BO->getOpcode() == BO_Assign) {
6625       Expr *LHS = BO->getLHS()->IgnoreParens();
6626       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6627         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6628           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6629             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6630                                   EmitDiags);
6631         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
6632       }
6633       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6634         if (ME->isArrow() &&
6635             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6636           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6637                                 EmitDiags);
6638       }
6639     }
6640   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
6641     if (DS->isSingleDecl()) {
6642       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
6643         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
6644           // Accept non-canonical init form here but emit ext. warning.
6645           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
6646             SemaRef.Diag(S->getBeginLoc(),
6647                          diag::ext_omp_loop_not_canonical_init)
6648                 << S->getSourceRange();
6649           return setLCDeclAndLB(
6650               Var,
6651               buildDeclRefExpr(SemaRef, Var,
6652                                Var->getType().getNonReferenceType(),
6653                                DS->getBeginLoc()),
6654               Var->getInit(), EmitDiags);
6655         }
6656       }
6657     }
6658   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6659     if (CE->getOperator() == OO_Equal) {
6660       Expr *LHS = CE->getArg(0);
6661       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6662         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6663           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6664             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6665                                   EmitDiags);
6666         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
6667       }
6668       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6669         if (ME->isArrow() &&
6670             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6671           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6672                                 EmitDiags);
6673       }
6674     }
6675   }
6676 
6677   if (dependent() || SemaRef.CurContext->isDependentContext())
6678     return false;
6679   if (EmitDiags) {
6680     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
6681         << S->getSourceRange();
6682   }
6683   return true;
6684 }
6685 
6686 /// Ignore parenthesizes, implicit casts, copy constructor and return the
6687 /// variable (which may be the loop variable) if possible.
6688 static const ValueDecl *getInitLCDecl(const Expr *E) {
6689   if (!E)
6690     return nullptr;
6691   E = getExprAsWritten(E);
6692   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
6693     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6694       if ((Ctor->isCopyOrMoveConstructor() ||
6695            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6696           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6697         E = CE->getArg(0)->IgnoreParenImpCasts();
6698   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6699     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
6700       return getCanonicalDecl(VD);
6701   }
6702   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
6703     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6704       return getCanonicalDecl(ME->getMemberDecl());
6705   return nullptr;
6706 }
6707 
6708 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
6709   // Check test-expr for canonical form, save upper-bound UB, flags for
6710   // less/greater and for strict/non-strict comparison.
6711   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
6712   //   var relational-op b
6713   //   b relational-op var
6714   //
6715   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
6716   if (!S) {
6717     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6718         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
6719     return true;
6720   }
6721   Condition = S;
6722   S = getExprAsWritten(S);
6723   SourceLocation CondLoc = S->getBeginLoc();
6724   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6725     if (BO->isRelationalOp()) {
6726       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6727         return setUB(BO->getRHS(),
6728                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6729                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6730                      BO->getSourceRange(), BO->getOperatorLoc());
6731       if (getInitLCDecl(BO->getRHS()) == LCDecl)
6732         return setUB(BO->getLHS(),
6733                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6734                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6735                      BO->getSourceRange(), BO->getOperatorLoc());
6736     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6737       return setUB(
6738           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6739           /*LessOp=*/llvm::None,
6740           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
6741   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6742     if (CE->getNumArgs() == 2) {
6743       auto Op = CE->getOperator();
6744       switch (Op) {
6745       case OO_Greater:
6746       case OO_GreaterEqual:
6747       case OO_Less:
6748       case OO_LessEqual:
6749         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6750           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
6751                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6752                        CE->getOperatorLoc());
6753         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6754           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
6755                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6756                        CE->getOperatorLoc());
6757         break;
6758       case OO_ExclaimEqual:
6759         if (IneqCondIsCanonical)
6760           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6761                                                               : CE->getArg(0),
6762                        /*LessOp=*/llvm::None,
6763                        /*StrictOp=*/true, CE->getSourceRange(),
6764                        CE->getOperatorLoc());
6765         break;
6766       default:
6767         break;
6768       }
6769     }
6770   }
6771   if (dependent() || SemaRef.CurContext->isDependentContext())
6772     return false;
6773   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
6774       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
6775   return true;
6776 }
6777 
6778 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
6779   // RHS of canonical loop form increment can be:
6780   //   var + incr
6781   //   incr + var
6782   //   var - incr
6783   //
6784   RHS = RHS->IgnoreParenImpCasts();
6785   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
6786     if (BO->isAdditiveOp()) {
6787       bool IsAdd = BO->getOpcode() == BO_Add;
6788       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6789         return setStep(BO->getRHS(), !IsAdd);
6790       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6791         return setStep(BO->getLHS(), /*Subtract=*/false);
6792     }
6793   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
6794     bool IsAdd = CE->getOperator() == OO_Plus;
6795     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
6796       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6797         return setStep(CE->getArg(1), !IsAdd);
6798       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6799         return setStep(CE->getArg(0), /*Subtract=*/false);
6800     }
6801   }
6802   if (dependent() || SemaRef.CurContext->isDependentContext())
6803     return false;
6804   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
6805       << RHS->getSourceRange() << LCDecl;
6806   return true;
6807 }
6808 
6809 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
6810   // Check incr-expr for canonical loop form and return true if it
6811   // does not conform.
6812   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6813   //   ++var
6814   //   var++
6815   //   --var
6816   //   var--
6817   //   var += incr
6818   //   var -= incr
6819   //   var = var + incr
6820   //   var = incr + var
6821   //   var = var - incr
6822   //
6823   if (!S) {
6824     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
6825     return true;
6826   }
6827   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6828     if (!ExprTemp->cleanupsHaveSideEffects())
6829       S = ExprTemp->getSubExpr();
6830 
6831   IncrementSrcRange = S->getSourceRange();
6832   S = S->IgnoreParens();
6833   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
6834     if (UO->isIncrementDecrementOp() &&
6835         getInitLCDecl(UO->getSubExpr()) == LCDecl)
6836       return setStep(SemaRef
6837                          .ActOnIntegerConstant(UO->getBeginLoc(),
6838                                                (UO->isDecrementOp() ? -1 : 1))
6839                          .get(),
6840                      /*Subtract=*/false);
6841   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6842     switch (BO->getOpcode()) {
6843     case BO_AddAssign:
6844     case BO_SubAssign:
6845       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6846         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
6847       break;
6848     case BO_Assign:
6849       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6850         return checkAndSetIncRHS(BO->getRHS());
6851       break;
6852     default:
6853       break;
6854     }
6855   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6856     switch (CE->getOperator()) {
6857     case OO_PlusPlus:
6858     case OO_MinusMinus:
6859       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6860         return setStep(SemaRef
6861                            .ActOnIntegerConstant(
6862                                CE->getBeginLoc(),
6863                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6864                            .get(),
6865                        /*Subtract=*/false);
6866       break;
6867     case OO_PlusEqual:
6868     case OO_MinusEqual:
6869       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6870         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
6871       break;
6872     case OO_Equal:
6873       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6874         return checkAndSetIncRHS(CE->getArg(1));
6875       break;
6876     default:
6877       break;
6878     }
6879   }
6880   if (dependent() || SemaRef.CurContext->isDependentContext())
6881     return false;
6882   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
6883       << S->getSourceRange() << LCDecl;
6884   return true;
6885 }
6886 
6887 static ExprResult
6888 tryBuildCapture(Sema &SemaRef, Expr *Capture,
6889                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6890   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
6891     return Capture;
6892   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6893     return SemaRef.PerformImplicitConversion(
6894         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6895         /*AllowExplicit=*/true);
6896   auto I = Captures.find(Capture);
6897   if (I != Captures.end())
6898     return buildCapture(SemaRef, Capture, I->second);
6899   DeclRefExpr *Ref = nullptr;
6900   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6901   Captures[Capture] = Ref;
6902   return Res;
6903 }
6904 
6905 /// Build the expression to calculate the number of iterations.
6906 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
6907     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
6908     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6909   ExprResult Diff;
6910   QualType VarType = LCDecl->getType().getNonReferenceType();
6911   if (VarType->isIntegerType() || VarType->isPointerType() ||
6912       SemaRef.getLangOpts().CPlusPlus) {
6913     Expr *LBVal = LB;
6914     Expr *UBVal = UB;
6915     // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6916     // max(LB(MinVal), LB(MaxVal))
6917     if (InitDependOnLC) {
6918       const LoopIterationSpace &IS =
6919           ResultIterSpaces[ResultIterSpaces.size() - 1 -
6920                            InitDependOnLC.getValueOr(
6921                                CondDependOnLC.getValueOr(0))];
6922       if (!IS.MinValue || !IS.MaxValue)
6923         return nullptr;
6924       // OuterVar = Min
6925       ExprResult MinValue =
6926           SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6927       if (!MinValue.isUsable())
6928         return nullptr;
6929 
6930       ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6931                                                IS.CounterVar, MinValue.get());
6932       if (!LBMinVal.isUsable())
6933         return nullptr;
6934       // OuterVar = Min, LBVal
6935       LBMinVal =
6936           SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6937       if (!LBMinVal.isUsable())
6938         return nullptr;
6939       // (OuterVar = Min, LBVal)
6940       LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6941       if (!LBMinVal.isUsable())
6942         return nullptr;
6943 
6944       // OuterVar = Max
6945       ExprResult MaxValue =
6946           SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6947       if (!MaxValue.isUsable())
6948         return nullptr;
6949 
6950       ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6951                                                IS.CounterVar, MaxValue.get());
6952       if (!LBMaxVal.isUsable())
6953         return nullptr;
6954       // OuterVar = Max, LBVal
6955       LBMaxVal =
6956           SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6957       if (!LBMaxVal.isUsable())
6958         return nullptr;
6959       // (OuterVar = Max, LBVal)
6960       LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6961       if (!LBMaxVal.isUsable())
6962         return nullptr;
6963 
6964       Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6965       Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6966       if (!LBMin || !LBMax)
6967         return nullptr;
6968       // LB(MinVal) < LB(MaxVal)
6969       ExprResult MinLessMaxRes =
6970           SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6971       if (!MinLessMaxRes.isUsable())
6972         return nullptr;
6973       Expr *MinLessMax =
6974           tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6975       if (!MinLessMax)
6976         return nullptr;
6977       if (TestIsLessOp.getValue()) {
6978         // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6979         // LB(MaxVal))
6980         ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6981                                                       MinLessMax, LBMin, LBMax);
6982         if (!MinLB.isUsable())
6983           return nullptr;
6984         LBVal = MinLB.get();
6985       } else {
6986         // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6987         // LB(MaxVal))
6988         ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6989                                                       MinLessMax, LBMax, LBMin);
6990         if (!MaxLB.isUsable())
6991           return nullptr;
6992         LBVal = MaxLB.get();
6993       }
6994     }
6995     // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6996     // min(UB(MinVal), UB(MaxVal))
6997     if (CondDependOnLC) {
6998       const LoopIterationSpace &IS =
6999           ResultIterSpaces[ResultIterSpaces.size() - 1 -
7000                            InitDependOnLC.getValueOr(
7001                                CondDependOnLC.getValueOr(0))];
7002       if (!IS.MinValue || !IS.MaxValue)
7003         return nullptr;
7004       // OuterVar = Min
7005       ExprResult MinValue =
7006           SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7007       if (!MinValue.isUsable())
7008         return nullptr;
7009 
7010       ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7011                                                IS.CounterVar, MinValue.get());
7012       if (!UBMinVal.isUsable())
7013         return nullptr;
7014       // OuterVar = Min, UBVal
7015       UBMinVal =
7016           SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
7017       if (!UBMinVal.isUsable())
7018         return nullptr;
7019       // (OuterVar = Min, UBVal)
7020       UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
7021       if (!UBMinVal.isUsable())
7022         return nullptr;
7023 
7024       // OuterVar = Max
7025       ExprResult MaxValue =
7026           SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7027       if (!MaxValue.isUsable())
7028         return nullptr;
7029 
7030       ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7031                                                IS.CounterVar, MaxValue.get());
7032       if (!UBMaxVal.isUsable())
7033         return nullptr;
7034       // OuterVar = Max, UBVal
7035       UBMaxVal =
7036           SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
7037       if (!UBMaxVal.isUsable())
7038         return nullptr;
7039       // (OuterVar = Max, UBVal)
7040       UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
7041       if (!UBMaxVal.isUsable())
7042         return nullptr;
7043 
7044       Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
7045       Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
7046       if (!UBMin || !UBMax)
7047         return nullptr;
7048       // UB(MinVal) > UB(MaxVal)
7049       ExprResult MinGreaterMaxRes =
7050           SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
7051       if (!MinGreaterMaxRes.isUsable())
7052         return nullptr;
7053       Expr *MinGreaterMax =
7054           tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
7055       if (!MinGreaterMax)
7056         return nullptr;
7057       if (TestIsLessOp.getValue()) {
7058         // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
7059         // UB(MaxVal))
7060         ExprResult MaxUB = SemaRef.ActOnConditionalOp(
7061             DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
7062         if (!MaxUB.isUsable())
7063           return nullptr;
7064         UBVal = MaxUB.get();
7065       } else {
7066         // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
7067         // UB(MaxVal))
7068         ExprResult MinUB = SemaRef.ActOnConditionalOp(
7069             DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
7070         if (!MinUB.isUsable())
7071           return nullptr;
7072         UBVal = MinUB.get();
7073       }
7074     }
7075     // Upper - Lower
7076     Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
7077     Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
7078     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
7079     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
7080     if (!Upper || !Lower)
7081       return nullptr;
7082 
7083     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7084 
7085     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
7086       // BuildBinOp already emitted error, this one is to point user to upper
7087       // and lower bound, and to tell what is passed to 'operator-'.
7088       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7089           << Upper->getSourceRange() << Lower->getSourceRange();
7090       return nullptr;
7091     }
7092   }
7093 
7094   if (!Diff.isUsable())
7095     return nullptr;
7096 
7097   // Upper - Lower [- 1]
7098   if (TestIsStrictOp)
7099     Diff = SemaRef.BuildBinOp(
7100         S, DefaultLoc, BO_Sub, Diff.get(),
7101         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7102   if (!Diff.isUsable())
7103     return nullptr;
7104 
7105   // Upper - Lower [- 1] + Step
7106   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7107   if (!NewStep.isUsable())
7108     return nullptr;
7109   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7110   if (!Diff.isUsable())
7111     return nullptr;
7112 
7113   // Parentheses (for dumping/debugging purposes only).
7114   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7115   if (!Diff.isUsable())
7116     return nullptr;
7117 
7118   // (Upper - Lower [- 1] + Step) / Step
7119   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7120   if (!Diff.isUsable())
7121     return nullptr;
7122 
7123   // OpenMP runtime requires 32-bit or 64-bit loop variables.
7124   QualType Type = Diff.get()->getType();
7125   ASTContext &C = SemaRef.Context;
7126   bool UseVarType = VarType->hasIntegerRepresentation() &&
7127                     C.getTypeSize(Type) > C.getTypeSize(VarType);
7128   if (!Type->isIntegerType() || UseVarType) {
7129     unsigned NewSize =
7130         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
7131     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
7132                                : Type->hasSignedIntegerRepresentation();
7133     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
7134     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
7135       Diff = SemaRef.PerformImplicitConversion(
7136           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
7137       if (!Diff.isUsable())
7138         return nullptr;
7139     }
7140   }
7141   if (LimitedType) {
7142     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
7143     if (NewSize != C.getTypeSize(Type)) {
7144       if (NewSize < C.getTypeSize(Type)) {
7145         assert(NewSize == 64 && "incorrect loop var size");
7146         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
7147             << InitSrcRange << ConditionSrcRange;
7148       }
7149       QualType NewType = C.getIntTypeForBitwidth(
7150           NewSize, Type->hasSignedIntegerRepresentation() ||
7151                        C.getTypeSize(Type) < NewSize);
7152       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
7153         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
7154                                                  Sema::AA_Converting, true);
7155         if (!Diff.isUsable())
7156           return nullptr;
7157       }
7158     }
7159   }
7160 
7161   return Diff.get();
7162 }
7163 
7164 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
7165     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7166   // Do not build for iterators, they cannot be used in non-rectangular loop
7167   // nests.
7168   if (LCDecl->getType()->isRecordType())
7169     return std::make_pair(nullptr, nullptr);
7170   // If we subtract, the min is in the condition, otherwise the min is in the
7171   // init value.
7172   Expr *MinExpr = nullptr;
7173   Expr *MaxExpr = nullptr;
7174   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
7175   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
7176   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
7177                                            : CondDependOnLC.hasValue();
7178   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
7179                                            : InitDependOnLC.hasValue();
7180   Expr *Lower =
7181       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
7182   Expr *Upper =
7183       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
7184   if (!Upper || !Lower)
7185     return std::make_pair(nullptr, nullptr);
7186 
7187   if (TestIsLessOp.getValue())
7188     MinExpr = Lower;
7189   else
7190     MaxExpr = Upper;
7191 
7192   // Build minimum/maximum value based on number of iterations.
7193   ExprResult Diff;
7194   QualType VarType = LCDecl->getType().getNonReferenceType();
7195 
7196   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7197   if (!Diff.isUsable())
7198     return std::make_pair(nullptr, nullptr);
7199 
7200   // Upper - Lower [- 1]
7201   if (TestIsStrictOp)
7202     Diff = SemaRef.BuildBinOp(
7203         S, DefaultLoc, BO_Sub, Diff.get(),
7204         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7205   if (!Diff.isUsable())
7206     return std::make_pair(nullptr, nullptr);
7207 
7208   // Upper - Lower [- 1] + Step
7209   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7210   if (!NewStep.isUsable())
7211     return std::make_pair(nullptr, nullptr);
7212 
7213   // Parentheses (for dumping/debugging purposes only).
7214   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7215   if (!Diff.isUsable())
7216     return std::make_pair(nullptr, nullptr);
7217 
7218   // (Upper - Lower [- 1]) / Step
7219   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7220   if (!Diff.isUsable())
7221     return std::make_pair(nullptr, nullptr);
7222 
7223   // ((Upper - Lower [- 1]) / Step) * Step
7224   // Parentheses (for dumping/debugging purposes only).
7225   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7226   if (!Diff.isUsable())
7227     return std::make_pair(nullptr, nullptr);
7228 
7229   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
7230   if (!Diff.isUsable())
7231     return std::make_pair(nullptr, nullptr);
7232 
7233   // Convert to the original type or ptrdiff_t, if original type is pointer.
7234   if (!VarType->isAnyPointerType() &&
7235       !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
7236     Diff = SemaRef.PerformImplicitConversion(
7237         Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
7238   } else if (VarType->isAnyPointerType() &&
7239              !SemaRef.Context.hasSameType(
7240                  Diff.get()->getType(),
7241                  SemaRef.Context.getUnsignedPointerDiffType())) {
7242     Diff = SemaRef.PerformImplicitConversion(
7243         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
7244         Sema::AA_Converting, /*AllowExplicit=*/true);
7245   }
7246   if (!Diff.isUsable())
7247     return std::make_pair(nullptr, nullptr);
7248 
7249   // Parentheses (for dumping/debugging purposes only).
7250   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7251   if (!Diff.isUsable())
7252     return std::make_pair(nullptr, nullptr);
7253 
7254   if (TestIsLessOp.getValue()) {
7255     // MinExpr = Lower;
7256     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
7257     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
7258     if (!Diff.isUsable())
7259       return std::make_pair(nullptr, nullptr);
7260     Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
7261     if (!Diff.isUsable())
7262       return std::make_pair(nullptr, nullptr);
7263     MaxExpr = Diff.get();
7264   } else {
7265     // MaxExpr = Upper;
7266     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
7267     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7268     if (!Diff.isUsable())
7269       return std::make_pair(nullptr, nullptr);
7270     Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
7271     if (!Diff.isUsable())
7272       return std::make_pair(nullptr, nullptr);
7273     MinExpr = Diff.get();
7274   }
7275 
7276   return std::make_pair(MinExpr, MaxExpr);
7277 }
7278 
7279 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
7280   if (InitDependOnLC || CondDependOnLC)
7281     return Condition;
7282   return nullptr;
7283 }
7284 
7285 Expr *OpenMPIterationSpaceChecker::buildPreCond(
7286     Scope *S, Expr *Cond,
7287     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7288   // Do not build a precondition when the condition/initialization is dependent
7289   // to prevent pessimistic early loop exit.
7290   // TODO: this can be improved by calculating min/max values but not sure that
7291   // it will be very effective.
7292   if (CondDependOnLC || InitDependOnLC)
7293     return SemaRef.PerformImplicitConversion(
7294         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
7295         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7296         /*AllowExplicit=*/true).get();
7297 
7298   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
7299   Sema::TentativeAnalysisScope Trap(SemaRef);
7300 
7301   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
7302   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
7303   if (!NewLB.isUsable() || !NewUB.isUsable())
7304     return nullptr;
7305 
7306   ExprResult CondExpr =
7307       SemaRef.BuildBinOp(S, DefaultLoc,
7308                          TestIsLessOp.getValue() ?
7309                            (TestIsStrictOp ? BO_LT : BO_LE) :
7310                            (TestIsStrictOp ? BO_GT : BO_GE),
7311                          NewLB.get(), NewUB.get());
7312   if (CondExpr.isUsable()) {
7313     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
7314                                                 SemaRef.Context.BoolTy))
7315       CondExpr = SemaRef.PerformImplicitConversion(
7316           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7317           /*AllowExplicit=*/true);
7318   }
7319 
7320   // Otherwise use original loop condition and evaluate it in runtime.
7321   return CondExpr.isUsable() ? CondExpr.get() : Cond;
7322 }
7323 
7324 /// Build reference expression to the counter be used for codegen.
7325 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
7326     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7327     DSAStackTy &DSA) const {
7328   auto *VD = dyn_cast<VarDecl>(LCDecl);
7329   if (!VD) {
7330     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
7331     DeclRefExpr *Ref = buildDeclRefExpr(
7332         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
7333     const DSAStackTy::DSAVarData Data =
7334         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
7335     // If the loop control decl is explicitly marked as private, do not mark it
7336     // as captured again.
7337     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
7338       Captures.insert(std::make_pair(LCRef, Ref));
7339     return Ref;
7340   }
7341   return cast<DeclRefExpr>(LCRef);
7342 }
7343 
7344 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
7345   if (LCDecl && !LCDecl->isInvalidDecl()) {
7346     QualType Type = LCDecl->getType().getNonReferenceType();
7347     VarDecl *PrivateVar = buildVarDecl(
7348         SemaRef, DefaultLoc, Type, LCDecl->getName(),
7349         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
7350         isa<VarDecl>(LCDecl)
7351             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
7352             : nullptr);
7353     if (PrivateVar->isInvalidDecl())
7354       return nullptr;
7355     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
7356   }
7357   return nullptr;
7358 }
7359 
7360 /// Build initialization of the counter to be used for codegen.
7361 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
7362 
7363 /// Build step of the counter be used for codegen.
7364 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
7365 
7366 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
7367     Scope *S, Expr *Counter,
7368     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
7369     Expr *Inc, OverloadedOperatorKind OOK) {
7370   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
7371   if (!Cnt)
7372     return nullptr;
7373   if (Inc) {
7374     assert((OOK == OO_Plus || OOK == OO_Minus) &&
7375            "Expected only + or - operations for depend clauses.");
7376     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
7377     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
7378     if (!Cnt)
7379       return nullptr;
7380   }
7381   ExprResult Diff;
7382   QualType VarType = LCDecl->getType().getNonReferenceType();
7383   if (VarType->isIntegerType() || VarType->isPointerType() ||
7384       SemaRef.getLangOpts().CPlusPlus) {
7385     // Upper - Lower
7386     Expr *Upper = TestIsLessOp.getValue()
7387                       ? Cnt
7388                       : tryBuildCapture(SemaRef, LB, Captures).get();
7389     Expr *Lower = TestIsLessOp.getValue()
7390                       ? tryBuildCapture(SemaRef, LB, Captures).get()
7391                       : Cnt;
7392     if (!Upper || !Lower)
7393       return nullptr;
7394 
7395     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7396 
7397     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
7398       // BuildBinOp already emitted error, this one is to point user to upper
7399       // and lower bound, and to tell what is passed to 'operator-'.
7400       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7401           << Upper->getSourceRange() << Lower->getSourceRange();
7402       return nullptr;
7403     }
7404   }
7405 
7406   if (!Diff.isUsable())
7407     return nullptr;
7408 
7409   // Parentheses (for dumping/debugging purposes only).
7410   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7411   if (!Diff.isUsable())
7412     return nullptr;
7413 
7414   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7415   if (!NewStep.isUsable())
7416     return nullptr;
7417   // (Upper - Lower) / Step
7418   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7419   if (!Diff.isUsable())
7420     return nullptr;
7421 
7422   return Diff.get();
7423 }
7424 } // namespace
7425 
7426 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
7427   assert(getLangOpts().OpenMP && "OpenMP is not active.");
7428   assert(Init && "Expected loop in canonical form.");
7429   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
7430   if (AssociatedLoops > 0 &&
7431       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
7432     DSAStack->loopStart();
7433     OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
7434     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
7435       if (ValueDecl *D = ISC.getLoopDecl()) {
7436         auto *VD = dyn_cast<VarDecl>(D);
7437         DeclRefExpr *PrivateRef = nullptr;
7438         if (!VD) {
7439           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
7440             VD = Private;
7441           } else {
7442             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
7443                                       /*WithInit=*/false);
7444             VD = cast<VarDecl>(PrivateRef->getDecl());
7445           }
7446         }
7447         DSAStack->addLoopControlVariable(D, VD);
7448         const Decl *LD = DSAStack->getPossiblyLoopCunter();
7449         if (LD != D->getCanonicalDecl()) {
7450           DSAStack->resetPossibleLoopCounter();
7451           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
7452             MarkDeclarationsReferencedInExpr(
7453                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
7454                                  Var->getType().getNonLValueExprType(Context),
7455                                  ForLoc, /*RefersToCapture=*/true));
7456         }
7457         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7458         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
7459         // Referenced in a Construct, C/C++]. The loop iteration variable in the
7460         // associated for-loop of a simd construct with just one associated
7461         // for-loop may be listed in a linear clause with a constant-linear-step
7462         // that is the increment of the associated for-loop. The loop iteration
7463         // variable(s) in the associated for-loop(s) of a for or parallel for
7464         // construct may be listed in a private or lastprivate clause.
7465         DSAStackTy::DSAVarData DVar =
7466             DSAStack->getTopDSA(D, /*FromParent=*/false);
7467         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
7468         // is declared in the loop and it is predetermined as a private.
7469         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
7470         OpenMPClauseKind PredeterminedCKind =
7471             isOpenMPSimdDirective(DKind)
7472                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
7473                 : OMPC_private;
7474         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7475               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
7476               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
7477                                          DVar.CKind != OMPC_private))) ||
7478              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
7479                DKind == OMPD_master_taskloop ||
7480                DKind == OMPD_parallel_master_taskloop ||
7481                isOpenMPDistributeDirective(DKind)) &&
7482               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7483               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
7484             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
7485           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
7486               << getOpenMPClauseName(DVar.CKind)
7487               << getOpenMPDirectiveName(DKind)
7488               << getOpenMPClauseName(PredeterminedCKind);
7489           if (DVar.RefExpr == nullptr)
7490             DVar.CKind = PredeterminedCKind;
7491           reportOriginalDsa(*this, DSAStack, D, DVar,
7492                             /*IsLoopIterVar=*/true);
7493         } else if (LoopDeclRefExpr) {
7494           // Make the loop iteration variable private (for worksharing
7495           // constructs), linear (for simd directives with the only one
7496           // associated loop) or lastprivate (for simd directives with several
7497           // collapsed or ordered loops).
7498           if (DVar.CKind == OMPC_unknown)
7499             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
7500                              PrivateRef);
7501         }
7502       }
7503     }
7504     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
7505   }
7506 }
7507 
7508 /// Called on a for stmt to check and extract its iteration space
7509 /// for further processing (such as collapsing).
7510 static bool checkOpenMPIterationSpace(
7511     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
7512     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
7513     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
7514     Expr *OrderedLoopCountExpr,
7515     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7516     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
7517     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7518   // OpenMP [2.9.1, Canonical Loop Form]
7519   //   for (init-expr; test-expr; incr-expr) structured-block
7520   //   for (range-decl: range-expr) structured-block
7521   auto *For = dyn_cast_or_null<ForStmt>(S);
7522   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7523   // Ranged for is supported only in OpenMP 5.0.
7524   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
7525     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
7526         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
7527         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
7528         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
7529     if (TotalNestedLoopCount > 1) {
7530       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7531         SemaRef.Diag(DSA.getConstructLoc(),
7532                      diag::note_omp_collapse_ordered_expr)
7533             << 2 << CollapseLoopCountExpr->getSourceRange()
7534             << OrderedLoopCountExpr->getSourceRange();
7535       else if (CollapseLoopCountExpr)
7536         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7537                      diag::note_omp_collapse_ordered_expr)
7538             << 0 << CollapseLoopCountExpr->getSourceRange();
7539       else
7540         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7541                      diag::note_omp_collapse_ordered_expr)
7542             << 1 << OrderedLoopCountExpr->getSourceRange();
7543     }
7544     return true;
7545   }
7546   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7547          "No loop body.");
7548 
7549   OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7550                                   For ? For->getForLoc() : CXXFor->getForLoc());
7551 
7552   // Check init.
7553   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
7554   if (ISC.checkAndSetInit(Init))
7555     return true;
7556 
7557   bool HasErrors = false;
7558 
7559   // Check loop variable's type.
7560   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
7561     // OpenMP [2.6, Canonical Loop Form]
7562     // Var is one of the following:
7563     //   A variable of signed or unsigned integer type.
7564     //   For C++, a variable of a random access iterator type.
7565     //   For C, a variable of a pointer type.
7566     QualType VarType = LCDecl->getType().getNonReferenceType();
7567     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7568         !VarType->isPointerType() &&
7569         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
7570       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
7571           << SemaRef.getLangOpts().CPlusPlus;
7572       HasErrors = true;
7573     }
7574 
7575     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7576     // a Construct
7577     // The loop iteration variable(s) in the associated for-loop(s) of a for or
7578     // parallel for construct is (are) private.
7579     // The loop iteration variable in the associated for-loop of a simd
7580     // construct with just one associated for-loop is linear with a
7581     // constant-linear-step that is the increment of the associated for-loop.
7582     // Exclude loop var from the list of variables with implicitly defined data
7583     // sharing attributes.
7584     VarsWithImplicitDSA.erase(LCDecl);
7585 
7586     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7587 
7588     // Check test-expr.
7589     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
7590 
7591     // Check incr-expr.
7592     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
7593   }
7594 
7595   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
7596     return HasErrors;
7597 
7598   // Build the loop's iteration space representation.
7599   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7600       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
7601   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7602       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7603                              (isOpenMPWorksharingDirective(DKind) ||
7604                               isOpenMPTaskLoopDirective(DKind) ||
7605                               isOpenMPDistributeDirective(DKind)),
7606                              Captures);
7607   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7608       ISC.buildCounterVar(Captures, DSA);
7609   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7610       ISC.buildPrivateCounterVar();
7611   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7612   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7613   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7614   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7615       ISC.getConditionSrcRange();
7616   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7617       ISC.getIncrementSrcRange();
7618   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7619   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7620       ISC.isStrictTestOp();
7621   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7622            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7623       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7624   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7625       ISC.buildFinalCondition(DSA.getCurScope());
7626   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7627       ISC.doesInitDependOnLC();
7628   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7629       ISC.doesCondDependOnLC();
7630   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7631       ISC.getLoopDependentIdx();
7632 
7633   HasErrors |=
7634       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7635        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7636        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7637        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7638        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7639        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
7640   if (!HasErrors && DSA.isOrderedRegion()) {
7641     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7642       if (CurrentNestedLoopCount <
7643           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7644         DSA.getOrderedRegionParam().second->setLoopNumIterations(
7645             CurrentNestedLoopCount,
7646             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
7647         DSA.getOrderedRegionParam().second->setLoopCounter(
7648             CurrentNestedLoopCount,
7649             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
7650       }
7651     }
7652     for (auto &Pair : DSA.getDoacrossDependClauses()) {
7653       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7654         // Erroneous case - clause has some problems.
7655         continue;
7656       }
7657       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7658           Pair.second.size() <= CurrentNestedLoopCount) {
7659         // Erroneous case - clause has some problems.
7660         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7661         continue;
7662       }
7663       Expr *CntValue;
7664       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7665         CntValue = ISC.buildOrderedLoopData(
7666             DSA.getCurScope(),
7667             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
7668             Pair.first->getDependencyLoc());
7669       else
7670         CntValue = ISC.buildOrderedLoopData(
7671             DSA.getCurScope(),
7672             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
7673             Pair.first->getDependencyLoc(),
7674             Pair.second[CurrentNestedLoopCount].first,
7675             Pair.second[CurrentNestedLoopCount].second);
7676       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7677     }
7678   }
7679 
7680   return HasErrors;
7681 }
7682 
7683 /// Build 'VarRef = Start.
7684 static ExprResult
7685 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7686                  ExprResult Start, bool IsNonRectangularLB,
7687                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7688   // Build 'VarRef = Start.
7689   ExprResult NewStart = IsNonRectangularLB
7690                             ? Start.get()
7691                             : tryBuildCapture(SemaRef, Start.get(), Captures);
7692   if (!NewStart.isUsable())
7693     return ExprError();
7694   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
7695                                    VarRef.get()->getType())) {
7696     NewStart = SemaRef.PerformImplicitConversion(
7697         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7698         /*AllowExplicit=*/true);
7699     if (!NewStart.isUsable())
7700       return ExprError();
7701   }
7702 
7703   ExprResult Init =
7704       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7705   return Init;
7706 }
7707 
7708 /// Build 'VarRef = Start + Iter * Step'.
7709 static ExprResult buildCounterUpdate(
7710     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7711     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
7712     bool IsNonRectangularLB,
7713     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
7714   // Add parentheses (for debugging purposes only).
7715   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7716   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7717       !Step.isUsable())
7718     return ExprError();
7719 
7720   ExprResult NewStep = Step;
7721   if (Captures)
7722     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
7723   if (NewStep.isInvalid())
7724     return ExprError();
7725   ExprResult Update =
7726       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
7727   if (!Update.isUsable())
7728     return ExprError();
7729 
7730   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7731   // 'VarRef = Start (+|-) Iter * Step'.
7732   if (!Start.isUsable())
7733     return ExprError();
7734   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7735   if (!NewStart.isUsable())
7736     return ExprError();
7737   if (Captures && !IsNonRectangularLB)
7738     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
7739   if (NewStart.isInvalid())
7740     return ExprError();
7741 
7742   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7743   ExprResult SavedUpdate = Update;
7744   ExprResult UpdateVal;
7745   if (VarRef.get()->getType()->isOverloadableType() ||
7746       NewStart.get()->getType()->isOverloadableType() ||
7747       Update.get()->getType()->isOverloadableType()) {
7748     Sema::TentativeAnalysisScope Trap(SemaRef);
7749 
7750     Update =
7751         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7752     if (Update.isUsable()) {
7753       UpdateVal =
7754           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7755                              VarRef.get(), SavedUpdate.get());
7756       if (UpdateVal.isUsable()) {
7757         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7758                                             UpdateVal.get());
7759       }
7760     }
7761   }
7762 
7763   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7764   if (!Update.isUsable() || !UpdateVal.isUsable()) {
7765     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7766                                 NewStart.get(), SavedUpdate.get());
7767     if (!Update.isUsable())
7768       return ExprError();
7769 
7770     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7771                                      VarRef.get()->getType())) {
7772       Update = SemaRef.PerformImplicitConversion(
7773           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7774       if (!Update.isUsable())
7775         return ExprError();
7776     }
7777 
7778     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7779   }
7780   return Update;
7781 }
7782 
7783 /// Convert integer expression \a E to make it have at least \a Bits
7784 /// bits.
7785 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
7786   if (E == nullptr)
7787     return ExprError();
7788   ASTContext &C = SemaRef.Context;
7789   QualType OldType = E->getType();
7790   unsigned HasBits = C.getTypeSize(OldType);
7791   if (HasBits >= Bits)
7792     return ExprResult(E);
7793   // OK to convert to signed, because new type has more bits than old.
7794   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7795   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7796                                            true);
7797 }
7798 
7799 /// Check if the given expression \a E is a constant integer that fits
7800 /// into \a Bits bits.
7801 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
7802   if (E == nullptr)
7803     return false;
7804   llvm::APSInt Result;
7805   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7806     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7807   return false;
7808 }
7809 
7810 /// Build preinits statement for the given declarations.
7811 static Stmt *buildPreInits(ASTContext &Context,
7812                            MutableArrayRef<Decl *> PreInits) {
7813   if (!PreInits.empty()) {
7814     return new (Context) DeclStmt(
7815         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7816         SourceLocation(), SourceLocation());
7817   }
7818   return nullptr;
7819 }
7820 
7821 /// Build preinits statement for the given declarations.
7822 static Stmt *
7823 buildPreInits(ASTContext &Context,
7824               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7825   if (!Captures.empty()) {
7826     SmallVector<Decl *, 16> PreInits;
7827     for (const auto &Pair : Captures)
7828       PreInits.push_back(Pair.second->getDecl());
7829     return buildPreInits(Context, PreInits);
7830   }
7831   return nullptr;
7832 }
7833 
7834 /// Build postupdate expression for the given list of postupdates expressions.
7835 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7836   Expr *PostUpdate = nullptr;
7837   if (!PostUpdates.empty()) {
7838     for (Expr *E : PostUpdates) {
7839       Expr *ConvE = S.BuildCStyleCastExpr(
7840                          E->getExprLoc(),
7841                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7842                          E->getExprLoc(), E)
7843                         .get();
7844       PostUpdate = PostUpdate
7845                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7846                                               PostUpdate, ConvE)
7847                              .get()
7848                        : ConvE;
7849     }
7850   }
7851   return PostUpdate;
7852 }
7853 
7854 /// Called on a for stmt to check itself and nested loops (if any).
7855 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7856 /// number of collapsed loops otherwise.
7857 static unsigned
7858 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
7859                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7860                 DSAStackTy &DSA,
7861                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7862                 OMPLoopDirective::HelperExprs &Built) {
7863   unsigned NestedLoopCount = 1;
7864   if (CollapseLoopCountExpr) {
7865     // Found 'collapse' clause - calculate collapse number.
7866     Expr::EvalResult Result;
7867     if (!CollapseLoopCountExpr->isValueDependent() &&
7868         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
7869       NestedLoopCount = Result.Val.getInt().getLimitedValue();
7870     } else {
7871       Built.clear(/*Size=*/1);
7872       return 1;
7873     }
7874   }
7875   unsigned OrderedLoopCount = 1;
7876   if (OrderedLoopCountExpr) {
7877     // Found 'ordered' clause - calculate collapse number.
7878     Expr::EvalResult EVResult;
7879     if (!OrderedLoopCountExpr->isValueDependent() &&
7880         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7881                                             SemaRef.getASTContext())) {
7882       llvm::APSInt Result = EVResult.Val.getInt();
7883       if (Result.getLimitedValue() < NestedLoopCount) {
7884         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7885                      diag::err_omp_wrong_ordered_loop_count)
7886             << OrderedLoopCountExpr->getSourceRange();
7887         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7888                      diag::note_collapse_loop_count)
7889             << CollapseLoopCountExpr->getSourceRange();
7890       }
7891       OrderedLoopCount = Result.getLimitedValue();
7892     } else {
7893       Built.clear(/*Size=*/1);
7894       return 1;
7895     }
7896   }
7897   // This is helper routine for loop directives (e.g., 'for', 'simd',
7898   // 'for simd', etc.).
7899   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
7900   SmallVector<LoopIterationSpace, 4> IterSpaces(
7901       std::max(OrderedLoopCount, NestedLoopCount));
7902   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
7903   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
7904     if (checkOpenMPIterationSpace(
7905             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7906             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
7907             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
7908       return 0;
7909     // Move on to the next nested for loop, or to the loop body.
7910     // OpenMP [2.8.1, simd construct, Restrictions]
7911     // All loops associated with the construct must be perfectly nested; that
7912     // is, there must be no intervening code nor any OpenMP directive between
7913     // any two loops.
7914     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7915       CurStmt = For->getBody();
7916     } else {
7917       assert(isa<CXXForRangeStmt>(CurStmt) &&
7918              "Expected canonical for or range-based for loops.");
7919       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7920     }
7921     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7922         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
7923   }
7924   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7925     if (checkOpenMPIterationSpace(
7926             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7927             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
7928             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
7929       return 0;
7930     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7931       // Handle initialization of captured loop iterator variables.
7932       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7933       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7934         Captures[DRE] = DRE;
7935       }
7936     }
7937     // Move on to the next nested for loop, or to the loop body.
7938     // OpenMP [2.8.1, simd construct, Restrictions]
7939     // All loops associated with the construct must be perfectly nested; that
7940     // is, there must be no intervening code nor any OpenMP directive between
7941     // any two loops.
7942     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7943       CurStmt = For->getBody();
7944     } else {
7945       assert(isa<CXXForRangeStmt>(CurStmt) &&
7946              "Expected canonical for or range-based for loops.");
7947       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7948     }
7949     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7950         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
7951   }
7952 
7953   Built.clear(/* size */ NestedLoopCount);
7954 
7955   if (SemaRef.CurContext->isDependentContext())
7956     return NestedLoopCount;
7957 
7958   // An example of what is generated for the following code:
7959   //
7960   //   #pragma omp simd collapse(2) ordered(2)
7961   //   for (i = 0; i < NI; ++i)
7962   //     for (k = 0; k < NK; ++k)
7963   //       for (j = J0; j < NJ; j+=2) {
7964   //         <loop body>
7965   //       }
7966   //
7967   // We generate the code below.
7968   // Note: the loop body may be outlined in CodeGen.
7969   // Note: some counters may be C++ classes, operator- is used to find number of
7970   // iterations and operator+= to calculate counter value.
7971   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7972   // or i64 is currently supported).
7973   //
7974   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7975   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7976   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7977   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7978   //     // similar updates for vars in clauses (e.g. 'linear')
7979   //     <loop body (using local i and j)>
7980   //   }
7981   //   i = NI; // assign final values of counters
7982   //   j = NJ;
7983   //
7984 
7985   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7986   // the iteration counts of the collapsed for loops.
7987   // Precondition tests if there is at least one iteration (all conditions are
7988   // true).
7989   auto PreCond = ExprResult(IterSpaces[0].PreCond);
7990   Expr *N0 = IterSpaces[0].NumIterations;
7991   ExprResult LastIteration32 =
7992       widenIterationCount(/*Bits=*/32,
7993                           SemaRef
7994                               .PerformImplicitConversion(
7995                                   N0->IgnoreImpCasts(), N0->getType(),
7996                                   Sema::AA_Converting, /*AllowExplicit=*/true)
7997                               .get(),
7998                           SemaRef);
7999   ExprResult LastIteration64 = widenIterationCount(
8000       /*Bits=*/64,
8001       SemaRef
8002           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
8003                                      Sema::AA_Converting,
8004                                      /*AllowExplicit=*/true)
8005           .get(),
8006       SemaRef);
8007 
8008   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
8009     return NestedLoopCount;
8010 
8011   ASTContext &C = SemaRef.Context;
8012   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
8013 
8014   Scope *CurScope = DSA.getCurScope();
8015   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
8016     if (PreCond.isUsable()) {
8017       PreCond =
8018           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
8019                              PreCond.get(), IterSpaces[Cnt].PreCond);
8020     }
8021     Expr *N = IterSpaces[Cnt].NumIterations;
8022     SourceLocation Loc = N->getExprLoc();
8023     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
8024     if (LastIteration32.isUsable())
8025       LastIteration32 = SemaRef.BuildBinOp(
8026           CurScope, Loc, BO_Mul, LastIteration32.get(),
8027           SemaRef
8028               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8029                                          Sema::AA_Converting,
8030                                          /*AllowExplicit=*/true)
8031               .get());
8032     if (LastIteration64.isUsable())
8033       LastIteration64 = SemaRef.BuildBinOp(
8034           CurScope, Loc, BO_Mul, LastIteration64.get(),
8035           SemaRef
8036               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8037                                          Sema::AA_Converting,
8038                                          /*AllowExplicit=*/true)
8039               .get());
8040   }
8041 
8042   // Choose either the 32-bit or 64-bit version.
8043   ExprResult LastIteration = LastIteration64;
8044   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
8045       (LastIteration32.isUsable() &&
8046        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
8047        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
8048         fitsInto(
8049             /*Bits=*/32,
8050             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
8051             LastIteration64.get(), SemaRef))))
8052     LastIteration = LastIteration32;
8053   QualType VType = LastIteration.get()->getType();
8054   QualType RealVType = VType;
8055   QualType StrideVType = VType;
8056   if (isOpenMPTaskLoopDirective(DKind)) {
8057     VType =
8058         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
8059     StrideVType =
8060         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8061   }
8062 
8063   if (!LastIteration.isUsable())
8064     return 0;
8065 
8066   // Save the number of iterations.
8067   ExprResult NumIterations = LastIteration;
8068   {
8069     LastIteration = SemaRef.BuildBinOp(
8070         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
8071         LastIteration.get(),
8072         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8073     if (!LastIteration.isUsable())
8074       return 0;
8075   }
8076 
8077   // Calculate the last iteration number beforehand instead of doing this on
8078   // each iteration. Do not do this if the number of iterations may be kfold-ed.
8079   llvm::APSInt Result;
8080   bool IsConstant =
8081       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
8082   ExprResult CalcLastIteration;
8083   if (!IsConstant) {
8084     ExprResult SaveRef =
8085         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
8086     LastIteration = SaveRef;
8087 
8088     // Prepare SaveRef + 1.
8089     NumIterations = SemaRef.BuildBinOp(
8090         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
8091         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8092     if (!NumIterations.isUsable())
8093       return 0;
8094   }
8095 
8096   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
8097 
8098   // Build variables passed into runtime, necessary for worksharing directives.
8099   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
8100   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8101       isOpenMPDistributeDirective(DKind)) {
8102     // Lower bound variable, initialized with zero.
8103     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
8104     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
8105     SemaRef.AddInitializerToDecl(LBDecl,
8106                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8107                                  /*DirectInit*/ false);
8108 
8109     // Upper bound variable, initialized with last iteration number.
8110     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
8111     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
8112     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
8113                                  /*DirectInit*/ false);
8114 
8115     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
8116     // This will be used to implement clause 'lastprivate'.
8117     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
8118     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
8119     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
8120     SemaRef.AddInitializerToDecl(ILDecl,
8121                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8122                                  /*DirectInit*/ false);
8123 
8124     // Stride variable returned by runtime (we initialize it to 1 by default).
8125     VarDecl *STDecl =
8126         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
8127     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
8128     SemaRef.AddInitializerToDecl(STDecl,
8129                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
8130                                  /*DirectInit*/ false);
8131 
8132     // Build expression: UB = min(UB, LastIteration)
8133     // It is necessary for CodeGen of directives with static scheduling.
8134     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
8135                                                 UB.get(), LastIteration.get());
8136     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8137         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
8138         LastIteration.get(), UB.get());
8139     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
8140                              CondOp.get());
8141     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
8142 
8143     // If we have a combined directive that combines 'distribute', 'for' or
8144     // 'simd' we need to be able to access the bounds of the schedule of the
8145     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
8146     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
8147     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8148       // Lower bound variable, initialized with zero.
8149       VarDecl *CombLBDecl =
8150           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
8151       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
8152       SemaRef.AddInitializerToDecl(
8153           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8154           /*DirectInit*/ false);
8155 
8156       // Upper bound variable, initialized with last iteration number.
8157       VarDecl *CombUBDecl =
8158           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
8159       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
8160       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
8161                                    /*DirectInit*/ false);
8162 
8163       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
8164           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
8165       ExprResult CombCondOp =
8166           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
8167                                      LastIteration.get(), CombUB.get());
8168       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
8169                                    CombCondOp.get());
8170       CombEUB =
8171           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
8172 
8173       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
8174       // We expect to have at least 2 more parameters than the 'parallel'
8175       // directive does - the lower and upper bounds of the previous schedule.
8176       assert(CD->getNumParams() >= 4 &&
8177              "Unexpected number of parameters in loop combined directive");
8178 
8179       // Set the proper type for the bounds given what we learned from the
8180       // enclosed loops.
8181       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
8182       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
8183 
8184       // Previous lower and upper bounds are obtained from the region
8185       // parameters.
8186       PrevLB =
8187           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
8188       PrevUB =
8189           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
8190     }
8191   }
8192 
8193   // Build the iteration variable and its initialization before loop.
8194   ExprResult IV;
8195   ExprResult Init, CombInit;
8196   {
8197     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
8198     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
8199     Expr *RHS =
8200         (isOpenMPWorksharingDirective(DKind) ||
8201          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8202             ? LB.get()
8203             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8204     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
8205     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
8206 
8207     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8208       Expr *CombRHS =
8209           (isOpenMPWorksharingDirective(DKind) ||
8210            isOpenMPTaskLoopDirective(DKind) ||
8211            isOpenMPDistributeDirective(DKind))
8212               ? CombLB.get()
8213               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8214       CombInit =
8215           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
8216       CombInit =
8217           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
8218     }
8219   }
8220 
8221   bool UseStrictCompare =
8222       RealVType->hasUnsignedIntegerRepresentation() &&
8223       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
8224         return LIS.IsStrictCompare;
8225       });
8226   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
8227   // unsigned IV)) for worksharing loops.
8228   SourceLocation CondLoc = AStmt->getBeginLoc();
8229   Expr *BoundUB = UB.get();
8230   if (UseStrictCompare) {
8231     BoundUB =
8232         SemaRef
8233             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
8234                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8235             .get();
8236     BoundUB =
8237         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
8238   }
8239   ExprResult Cond =
8240       (isOpenMPWorksharingDirective(DKind) ||
8241        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8242           ? SemaRef.BuildBinOp(CurScope, CondLoc,
8243                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
8244                                BoundUB)
8245           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8246                                NumIterations.get());
8247   ExprResult CombDistCond;
8248   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8249     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8250                                       NumIterations.get());
8251   }
8252 
8253   ExprResult CombCond;
8254   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8255     Expr *BoundCombUB = CombUB.get();
8256     if (UseStrictCompare) {
8257       BoundCombUB =
8258           SemaRef
8259               .BuildBinOp(
8260                   CurScope, CondLoc, BO_Add, BoundCombUB,
8261                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8262               .get();
8263       BoundCombUB =
8264           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
8265               .get();
8266     }
8267     CombCond =
8268         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8269                            IV.get(), BoundCombUB);
8270   }
8271   // Loop increment (IV = IV + 1)
8272   SourceLocation IncLoc = AStmt->getBeginLoc();
8273   ExprResult Inc =
8274       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
8275                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
8276   if (!Inc.isUsable())
8277     return 0;
8278   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
8279   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
8280   if (!Inc.isUsable())
8281     return 0;
8282 
8283   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
8284   // Used for directives with static scheduling.
8285   // In combined construct, add combined version that use CombLB and CombUB
8286   // base variables for the update
8287   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
8288   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8289       isOpenMPDistributeDirective(DKind)) {
8290     // LB + ST
8291     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
8292     if (!NextLB.isUsable())
8293       return 0;
8294     // LB = LB + ST
8295     NextLB =
8296         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
8297     NextLB =
8298         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
8299     if (!NextLB.isUsable())
8300       return 0;
8301     // UB + ST
8302     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
8303     if (!NextUB.isUsable())
8304       return 0;
8305     // UB = UB + ST
8306     NextUB =
8307         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
8308     NextUB =
8309         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
8310     if (!NextUB.isUsable())
8311       return 0;
8312     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8313       CombNextLB =
8314           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
8315       if (!NextLB.isUsable())
8316         return 0;
8317       // LB = LB + ST
8318       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
8319                                       CombNextLB.get());
8320       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
8321                                                /*DiscardedValue*/ false);
8322       if (!CombNextLB.isUsable())
8323         return 0;
8324       // UB + ST
8325       CombNextUB =
8326           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
8327       if (!CombNextUB.isUsable())
8328         return 0;
8329       // UB = UB + ST
8330       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
8331                                       CombNextUB.get());
8332       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
8333                                                /*DiscardedValue*/ false);
8334       if (!CombNextUB.isUsable())
8335         return 0;
8336     }
8337   }
8338 
8339   // Create increment expression for distribute loop when combined in a same
8340   // directive with for as IV = IV + ST; ensure upper bound expression based
8341   // on PrevUB instead of NumIterations - used to implement 'for' when found
8342   // in combination with 'distribute', like in 'distribute parallel for'
8343   SourceLocation DistIncLoc = AStmt->getBeginLoc();
8344   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
8345   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8346     DistCond = SemaRef.BuildBinOp(
8347         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
8348     assert(DistCond.isUsable() && "distribute cond expr was not built");
8349 
8350     DistInc =
8351         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
8352     assert(DistInc.isUsable() && "distribute inc expr was not built");
8353     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
8354                                  DistInc.get());
8355     DistInc =
8356         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
8357     assert(DistInc.isUsable() && "distribute inc expr was not built");
8358 
8359     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
8360     // construct
8361     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
8362     ExprResult IsUBGreater =
8363         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
8364     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8365         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
8366     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
8367                                  CondOp.get());
8368     PrevEUB =
8369         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
8370 
8371     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
8372     // parallel for is in combination with a distribute directive with
8373     // schedule(static, 1)
8374     Expr *BoundPrevUB = PrevUB.get();
8375     if (UseStrictCompare) {
8376       BoundPrevUB =
8377           SemaRef
8378               .BuildBinOp(
8379                   CurScope, CondLoc, BO_Add, BoundPrevUB,
8380                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8381               .get();
8382       BoundPrevUB =
8383           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
8384               .get();
8385     }
8386     ParForInDistCond =
8387         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8388                            IV.get(), BoundPrevUB);
8389   }
8390 
8391   // Build updates and final values of the loop counters.
8392   bool HasErrors = false;
8393   Built.Counters.resize(NestedLoopCount);
8394   Built.Inits.resize(NestedLoopCount);
8395   Built.Updates.resize(NestedLoopCount);
8396   Built.Finals.resize(NestedLoopCount);
8397   Built.DependentCounters.resize(NestedLoopCount);
8398   Built.DependentInits.resize(NestedLoopCount);
8399   Built.FinalsConditions.resize(NestedLoopCount);
8400   {
8401     // We implement the following algorithm for obtaining the
8402     // original loop iteration variable values based on the
8403     // value of the collapsed loop iteration variable IV.
8404     //
8405     // Let n+1 be the number of collapsed loops in the nest.
8406     // Iteration variables (I0, I1, .... In)
8407     // Iteration counts (N0, N1, ... Nn)
8408     //
8409     // Acc = IV;
8410     //
8411     // To compute Ik for loop k, 0 <= k <= n, generate:
8412     //    Prod = N(k+1) * N(k+2) * ... * Nn;
8413     //    Ik = Acc / Prod;
8414     //    Acc -= Ik * Prod;
8415     //
8416     ExprResult Acc = IV;
8417     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8418       LoopIterationSpace &IS = IterSpaces[Cnt];
8419       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
8420       ExprResult Iter;
8421 
8422       // Compute prod
8423       ExprResult Prod =
8424           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8425       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
8426         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
8427                                   IterSpaces[K].NumIterations);
8428 
8429       // Iter = Acc / Prod
8430       // If there is at least one more inner loop to avoid
8431       // multiplication by 1.
8432       if (Cnt + 1 < NestedLoopCount)
8433         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
8434                                   Acc.get(), Prod.get());
8435       else
8436         Iter = Acc;
8437       if (!Iter.isUsable()) {
8438         HasErrors = true;
8439         break;
8440       }
8441 
8442       // Update Acc:
8443       // Acc -= Iter * Prod
8444       // Check if there is at least one more inner loop to avoid
8445       // multiplication by 1.
8446       if (Cnt + 1 < NestedLoopCount)
8447         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
8448                                   Iter.get(), Prod.get());
8449       else
8450         Prod = Iter;
8451       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
8452                                Acc.get(), Prod.get());
8453 
8454       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
8455       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
8456       DeclRefExpr *CounterVar = buildDeclRefExpr(
8457           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
8458           /*RefersToCapture=*/true);
8459       ExprResult Init =
8460           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
8461                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
8462       if (!Init.isUsable()) {
8463         HasErrors = true;
8464         break;
8465       }
8466       ExprResult Update = buildCounterUpdate(
8467           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
8468           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
8469       if (!Update.isUsable()) {
8470         HasErrors = true;
8471         break;
8472       }
8473 
8474       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
8475       ExprResult Final =
8476           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
8477                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
8478                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
8479       if (!Final.isUsable()) {
8480         HasErrors = true;
8481         break;
8482       }
8483 
8484       if (!Update.isUsable() || !Final.isUsable()) {
8485         HasErrors = true;
8486         break;
8487       }
8488       // Save results
8489       Built.Counters[Cnt] = IS.CounterVar;
8490       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
8491       Built.Inits[Cnt] = Init.get();
8492       Built.Updates[Cnt] = Update.get();
8493       Built.Finals[Cnt] = Final.get();
8494       Built.DependentCounters[Cnt] = nullptr;
8495       Built.DependentInits[Cnt] = nullptr;
8496       Built.FinalsConditions[Cnt] = nullptr;
8497       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
8498         Built.DependentCounters[Cnt] =
8499             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
8500         Built.DependentInits[Cnt] =
8501             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
8502         Built.FinalsConditions[Cnt] = IS.FinalCondition;
8503       }
8504     }
8505   }
8506 
8507   if (HasErrors)
8508     return 0;
8509 
8510   // Save results
8511   Built.IterationVarRef = IV.get();
8512   Built.LastIteration = LastIteration.get();
8513   Built.NumIterations = NumIterations.get();
8514   Built.CalcLastIteration = SemaRef
8515                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
8516                                                      /*DiscardedValue=*/false)
8517                                 .get();
8518   Built.PreCond = PreCond.get();
8519   Built.PreInits = buildPreInits(C, Captures);
8520   Built.Cond = Cond.get();
8521   Built.Init = Init.get();
8522   Built.Inc = Inc.get();
8523   Built.LB = LB.get();
8524   Built.UB = UB.get();
8525   Built.IL = IL.get();
8526   Built.ST = ST.get();
8527   Built.EUB = EUB.get();
8528   Built.NLB = NextLB.get();
8529   Built.NUB = NextUB.get();
8530   Built.PrevLB = PrevLB.get();
8531   Built.PrevUB = PrevUB.get();
8532   Built.DistInc = DistInc.get();
8533   Built.PrevEUB = PrevEUB.get();
8534   Built.DistCombinedFields.LB = CombLB.get();
8535   Built.DistCombinedFields.UB = CombUB.get();
8536   Built.DistCombinedFields.EUB = CombEUB.get();
8537   Built.DistCombinedFields.Init = CombInit.get();
8538   Built.DistCombinedFields.Cond = CombCond.get();
8539   Built.DistCombinedFields.NLB = CombNextLB.get();
8540   Built.DistCombinedFields.NUB = CombNextUB.get();
8541   Built.DistCombinedFields.DistCond = CombDistCond.get();
8542   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
8543 
8544   return NestedLoopCount;
8545 }
8546 
8547 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
8548   auto CollapseClauses =
8549       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8550   if (CollapseClauses.begin() != CollapseClauses.end())
8551     return (*CollapseClauses.begin())->getNumForLoops();
8552   return nullptr;
8553 }
8554 
8555 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
8556   auto OrderedClauses =
8557       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8558   if (OrderedClauses.begin() != OrderedClauses.end())
8559     return (*OrderedClauses.begin())->getNumForLoops();
8560   return nullptr;
8561 }
8562 
8563 static bool checkSimdlenSafelenSpecified(Sema &S,
8564                                          const ArrayRef<OMPClause *> Clauses) {
8565   const OMPSafelenClause *Safelen = nullptr;
8566   const OMPSimdlenClause *Simdlen = nullptr;
8567 
8568   for (const OMPClause *Clause : Clauses) {
8569     if (Clause->getClauseKind() == OMPC_safelen)
8570       Safelen = cast<OMPSafelenClause>(Clause);
8571     else if (Clause->getClauseKind() == OMPC_simdlen)
8572       Simdlen = cast<OMPSimdlenClause>(Clause);
8573     if (Safelen && Simdlen)
8574       break;
8575   }
8576 
8577   if (Simdlen && Safelen) {
8578     const Expr *SimdlenLength = Simdlen->getSimdlen();
8579     const Expr *SafelenLength = Safelen->getSafelen();
8580     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8581         SimdlenLength->isInstantiationDependent() ||
8582         SimdlenLength->containsUnexpandedParameterPack())
8583       return false;
8584     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8585         SafelenLength->isInstantiationDependent() ||
8586         SafelenLength->containsUnexpandedParameterPack())
8587       return false;
8588     Expr::EvalResult SimdlenResult, SafelenResult;
8589     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8590     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8591     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8592     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
8593     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8594     // If both simdlen and safelen clauses are specified, the value of the
8595     // simdlen parameter must be less than or equal to the value of the safelen
8596     // parameter.
8597     if (SimdlenRes > SafelenRes) {
8598       S.Diag(SimdlenLength->getExprLoc(),
8599              diag::err_omp_wrong_simdlen_safelen_values)
8600           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8601       return true;
8602     }
8603   }
8604   return false;
8605 }
8606 
8607 StmtResult
8608 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8609                                SourceLocation StartLoc, SourceLocation EndLoc,
8610                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8611   if (!AStmt)
8612     return StmtError();
8613 
8614   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8615   OMPLoopDirective::HelperExprs B;
8616   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8617   // define the nested loops number.
8618   unsigned NestedLoopCount = checkOpenMPLoop(
8619       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8620       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
8621   if (NestedLoopCount == 0)
8622     return StmtError();
8623 
8624   assert((CurContext->isDependentContext() || B.builtAll()) &&
8625          "omp simd loop exprs were not built");
8626 
8627   if (!CurContext->isDependentContext()) {
8628     // Finalize the clauses that need pre-built expressions for CodeGen.
8629     for (OMPClause *C : Clauses) {
8630       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8631         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8632                                      B.NumIterations, *this, CurScope,
8633                                      DSAStack))
8634           return StmtError();
8635     }
8636   }
8637 
8638   if (checkSimdlenSafelenSpecified(*this, Clauses))
8639     return StmtError();
8640 
8641   setFunctionHasBranchProtectedScope();
8642   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8643                                   Clauses, AStmt, B);
8644 }
8645 
8646 StmtResult
8647 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8648                               SourceLocation StartLoc, SourceLocation EndLoc,
8649                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8650   if (!AStmt)
8651     return StmtError();
8652 
8653   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8654   OMPLoopDirective::HelperExprs B;
8655   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8656   // define the nested loops number.
8657   unsigned NestedLoopCount = checkOpenMPLoop(
8658       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8659       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
8660   if (NestedLoopCount == 0)
8661     return StmtError();
8662 
8663   assert((CurContext->isDependentContext() || B.builtAll()) &&
8664          "omp for loop exprs were not built");
8665 
8666   if (!CurContext->isDependentContext()) {
8667     // Finalize the clauses that need pre-built expressions for CodeGen.
8668     for (OMPClause *C : Clauses) {
8669       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8670         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8671                                      B.NumIterations, *this, CurScope,
8672                                      DSAStack))
8673           return StmtError();
8674     }
8675   }
8676 
8677   setFunctionHasBranchProtectedScope();
8678   return OMPForDirective::Create(
8679       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8680       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
8681 }
8682 
8683 StmtResult Sema::ActOnOpenMPForSimdDirective(
8684     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8685     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8686   if (!AStmt)
8687     return StmtError();
8688 
8689   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8690   OMPLoopDirective::HelperExprs B;
8691   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8692   // define the nested loops number.
8693   unsigned NestedLoopCount =
8694       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
8695                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8696                       VarsWithImplicitDSA, B);
8697   if (NestedLoopCount == 0)
8698     return StmtError();
8699 
8700   assert((CurContext->isDependentContext() || B.builtAll()) &&
8701          "omp for simd loop exprs were not built");
8702 
8703   if (!CurContext->isDependentContext()) {
8704     // Finalize the clauses that need pre-built expressions for CodeGen.
8705     for (OMPClause *C : Clauses) {
8706       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8707         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8708                                      B.NumIterations, *this, CurScope,
8709                                      DSAStack))
8710           return StmtError();
8711     }
8712   }
8713 
8714   if (checkSimdlenSafelenSpecified(*this, Clauses))
8715     return StmtError();
8716 
8717   setFunctionHasBranchProtectedScope();
8718   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8719                                      Clauses, AStmt, B);
8720 }
8721 
8722 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8723                                               Stmt *AStmt,
8724                                               SourceLocation StartLoc,
8725                                               SourceLocation EndLoc) {
8726   if (!AStmt)
8727     return StmtError();
8728 
8729   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8730   auto BaseStmt = AStmt;
8731   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
8732     BaseStmt = CS->getCapturedStmt();
8733   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
8734     auto S = C->children();
8735     if (S.begin() == S.end())
8736       return StmtError();
8737     // All associated statements must be '#pragma omp section' except for
8738     // the first one.
8739     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
8740       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8741         if (SectionStmt)
8742           Diag(SectionStmt->getBeginLoc(),
8743                diag::err_omp_sections_substmt_not_section);
8744         return StmtError();
8745       }
8746       cast<OMPSectionDirective>(SectionStmt)
8747           ->setHasCancel(DSAStack->isCancelRegion());
8748     }
8749   } else {
8750     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
8751     return StmtError();
8752   }
8753 
8754   setFunctionHasBranchProtectedScope();
8755 
8756   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8757                                       DSAStack->getTaskgroupReductionRef(),
8758                                       DSAStack->isCancelRegion());
8759 }
8760 
8761 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8762                                              SourceLocation StartLoc,
8763                                              SourceLocation EndLoc) {
8764   if (!AStmt)
8765     return StmtError();
8766 
8767   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8768 
8769   setFunctionHasBranchProtectedScope();
8770   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
8771 
8772   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8773                                      DSAStack->isCancelRegion());
8774 }
8775 
8776 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8777                                             Stmt *AStmt,
8778                                             SourceLocation StartLoc,
8779                                             SourceLocation EndLoc) {
8780   if (!AStmt)
8781     return StmtError();
8782 
8783   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8784 
8785   setFunctionHasBranchProtectedScope();
8786 
8787   // OpenMP [2.7.3, single Construct, Restrictions]
8788   // The copyprivate clause must not be used with the nowait clause.
8789   const OMPClause *Nowait = nullptr;
8790   const OMPClause *Copyprivate = nullptr;
8791   for (const OMPClause *Clause : Clauses) {
8792     if (Clause->getClauseKind() == OMPC_nowait)
8793       Nowait = Clause;
8794     else if (Clause->getClauseKind() == OMPC_copyprivate)
8795       Copyprivate = Clause;
8796     if (Copyprivate && Nowait) {
8797       Diag(Copyprivate->getBeginLoc(),
8798            diag::err_omp_single_copyprivate_with_nowait);
8799       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
8800       return StmtError();
8801     }
8802   }
8803 
8804   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8805 }
8806 
8807 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8808                                             SourceLocation StartLoc,
8809                                             SourceLocation EndLoc) {
8810   if (!AStmt)
8811     return StmtError();
8812 
8813   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8814 
8815   setFunctionHasBranchProtectedScope();
8816 
8817   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8818 }
8819 
8820 StmtResult Sema::ActOnOpenMPCriticalDirective(
8821     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8822     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
8823   if (!AStmt)
8824     return StmtError();
8825 
8826   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8827 
8828   bool ErrorFound = false;
8829   llvm::APSInt Hint;
8830   SourceLocation HintLoc;
8831   bool DependentHint = false;
8832   for (const OMPClause *C : Clauses) {
8833     if (C->getClauseKind() == OMPC_hint) {
8834       if (!DirName.getName()) {
8835         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
8836         ErrorFound = true;
8837       }
8838       Expr *E = cast<OMPHintClause>(C)->getHint();
8839       if (E->isTypeDependent() || E->isValueDependent() ||
8840           E->isInstantiationDependent()) {
8841         DependentHint = true;
8842       } else {
8843         Hint = E->EvaluateKnownConstInt(Context);
8844         HintLoc = C->getBeginLoc();
8845       }
8846     }
8847   }
8848   if (ErrorFound)
8849     return StmtError();
8850   const auto Pair = DSAStack->getCriticalWithHint(DirName);
8851   if (Pair.first && DirName.getName() && !DependentHint) {
8852     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8853       Diag(StartLoc, diag::err_omp_critical_with_hint);
8854       if (HintLoc.isValid())
8855         Diag(HintLoc, diag::note_omp_critical_hint_here)
8856             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
8857       else
8858         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
8859       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
8860         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
8861             << 1
8862             << C->getHint()->EvaluateKnownConstInt(Context).toString(
8863                    /*Radix=*/10, /*Signed=*/false);
8864       } else {
8865         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
8866       }
8867     }
8868   }
8869 
8870   setFunctionHasBranchProtectedScope();
8871 
8872   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8873                                            Clauses, AStmt);
8874   if (!Pair.first && DirName.getName() && !DependentHint)
8875     DSAStack->addCriticalWithHint(Dir, Hint);
8876   return Dir;
8877 }
8878 
8879 StmtResult Sema::ActOnOpenMPParallelForDirective(
8880     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8881     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8882   if (!AStmt)
8883     return StmtError();
8884 
8885   auto *CS = cast<CapturedStmt>(AStmt);
8886   // 1.2.2 OpenMP Language Terminology
8887   // Structured block - An executable statement with a single entry at the
8888   // top and a single exit at the bottom.
8889   // The point of exit cannot be a branch out of the structured block.
8890   // longjmp() and throw() must not violate the entry/exit criteria.
8891   CS->getCapturedDecl()->setNothrow();
8892 
8893   OMPLoopDirective::HelperExprs B;
8894   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8895   // define the nested loops number.
8896   unsigned NestedLoopCount =
8897       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
8898                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8899                       VarsWithImplicitDSA, B);
8900   if (NestedLoopCount == 0)
8901     return StmtError();
8902 
8903   assert((CurContext->isDependentContext() || B.builtAll()) &&
8904          "omp parallel for loop exprs were not built");
8905 
8906   if (!CurContext->isDependentContext()) {
8907     // Finalize the clauses that need pre-built expressions for CodeGen.
8908     for (OMPClause *C : Clauses) {
8909       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8910         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8911                                      B.NumIterations, *this, CurScope,
8912                                      DSAStack))
8913           return StmtError();
8914     }
8915   }
8916 
8917   setFunctionHasBranchProtectedScope();
8918   return OMPParallelForDirective::Create(
8919       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8920       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
8921 }
8922 
8923 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8924     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8925     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8926   if (!AStmt)
8927     return StmtError();
8928 
8929   auto *CS = cast<CapturedStmt>(AStmt);
8930   // 1.2.2 OpenMP Language Terminology
8931   // Structured block - An executable statement with a single entry at the
8932   // top and a single exit at the bottom.
8933   // The point of exit cannot be a branch out of the structured block.
8934   // longjmp() and throw() must not violate the entry/exit criteria.
8935   CS->getCapturedDecl()->setNothrow();
8936 
8937   OMPLoopDirective::HelperExprs B;
8938   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8939   // define the nested loops number.
8940   unsigned NestedLoopCount =
8941       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
8942                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8943                       VarsWithImplicitDSA, B);
8944   if (NestedLoopCount == 0)
8945     return StmtError();
8946 
8947   if (!CurContext->isDependentContext()) {
8948     // Finalize the clauses that need pre-built expressions for CodeGen.
8949     for (OMPClause *C : Clauses) {
8950       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8951         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8952                                      B.NumIterations, *this, CurScope,
8953                                      DSAStack))
8954           return StmtError();
8955     }
8956   }
8957 
8958   if (checkSimdlenSafelenSpecified(*this, Clauses))
8959     return StmtError();
8960 
8961   setFunctionHasBranchProtectedScope();
8962   return OMPParallelForSimdDirective::Create(
8963       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8964 }
8965 
8966 StmtResult
8967 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8968                                          Stmt *AStmt, SourceLocation StartLoc,
8969                                          SourceLocation EndLoc) {
8970   if (!AStmt)
8971     return StmtError();
8972 
8973   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8974   auto *CS = cast<CapturedStmt>(AStmt);
8975   // 1.2.2 OpenMP Language Terminology
8976   // Structured block - An executable statement with a single entry at the
8977   // top and a single exit at the bottom.
8978   // The point of exit cannot be a branch out of the structured block.
8979   // longjmp() and throw() must not violate the entry/exit criteria.
8980   CS->getCapturedDecl()->setNothrow();
8981 
8982   setFunctionHasBranchProtectedScope();
8983 
8984   return OMPParallelMasterDirective::Create(
8985       Context, StartLoc, EndLoc, Clauses, AStmt,
8986       DSAStack->getTaskgroupReductionRef());
8987 }
8988 
8989 StmtResult
8990 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8991                                            Stmt *AStmt, SourceLocation StartLoc,
8992                                            SourceLocation EndLoc) {
8993   if (!AStmt)
8994     return StmtError();
8995 
8996   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8997   auto BaseStmt = AStmt;
8998   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
8999     BaseStmt = CS->getCapturedStmt();
9000   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9001     auto S = C->children();
9002     if (S.begin() == S.end())
9003       return StmtError();
9004     // All associated statements must be '#pragma omp section' except for
9005     // the first one.
9006     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9007       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9008         if (SectionStmt)
9009           Diag(SectionStmt->getBeginLoc(),
9010                diag::err_omp_parallel_sections_substmt_not_section);
9011         return StmtError();
9012       }
9013       cast<OMPSectionDirective>(SectionStmt)
9014           ->setHasCancel(DSAStack->isCancelRegion());
9015     }
9016   } else {
9017     Diag(AStmt->getBeginLoc(),
9018          diag::err_omp_parallel_sections_not_compound_stmt);
9019     return StmtError();
9020   }
9021 
9022   setFunctionHasBranchProtectedScope();
9023 
9024   return OMPParallelSectionsDirective::Create(
9025       Context, StartLoc, EndLoc, Clauses, AStmt,
9026       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9027 }
9028 
9029 /// detach and mergeable clauses are mutially exclusive, check for it.
9030 static bool checkDetachMergeableClauses(Sema &S,
9031                                         ArrayRef<OMPClause *> Clauses) {
9032   const OMPClause *PrevClause = nullptr;
9033   bool ErrorFound = false;
9034   for (const OMPClause *C : Clauses) {
9035     if (C->getClauseKind() == OMPC_detach ||
9036         C->getClauseKind() == OMPC_mergeable) {
9037       if (!PrevClause) {
9038         PrevClause = C;
9039       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
9040         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
9041             << getOpenMPClauseName(C->getClauseKind())
9042             << getOpenMPClauseName(PrevClause->getClauseKind());
9043         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
9044             << getOpenMPClauseName(PrevClause->getClauseKind());
9045         ErrorFound = true;
9046       }
9047     }
9048   }
9049   return ErrorFound;
9050 }
9051 
9052 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9053                                           Stmt *AStmt, SourceLocation StartLoc,
9054                                           SourceLocation EndLoc) {
9055   if (!AStmt)
9056     return StmtError();
9057 
9058   // OpenMP 5.0, 2.10.1 task Construct
9059   // If a detach clause appears on the directive, then a mergeable clause cannot
9060   // appear on the same directive.
9061   if (checkDetachMergeableClauses(*this, Clauses))
9062     return StmtError();
9063 
9064   auto *CS = cast<CapturedStmt>(AStmt);
9065   // 1.2.2 OpenMP Language Terminology
9066   // Structured block - An executable statement with a single entry at the
9067   // top and a single exit at the bottom.
9068   // The point of exit cannot be a branch out of the structured block.
9069   // longjmp() and throw() must not violate the entry/exit criteria.
9070   CS->getCapturedDecl()->setNothrow();
9071 
9072   setFunctionHasBranchProtectedScope();
9073 
9074   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9075                                   DSAStack->isCancelRegion());
9076 }
9077 
9078 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9079                                                SourceLocation EndLoc) {
9080   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
9081 }
9082 
9083 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9084                                              SourceLocation EndLoc) {
9085   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
9086 }
9087 
9088 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9089                                               SourceLocation EndLoc) {
9090   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
9091 }
9092 
9093 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9094                                                Stmt *AStmt,
9095                                                SourceLocation StartLoc,
9096                                                SourceLocation EndLoc) {
9097   if (!AStmt)
9098     return StmtError();
9099 
9100   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9101 
9102   setFunctionHasBranchProtectedScope();
9103 
9104   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
9105                                        AStmt,
9106                                        DSAStack->getTaskgroupReductionRef());
9107 }
9108 
9109 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9110                                            SourceLocation StartLoc,
9111                                            SourceLocation EndLoc) {
9112   OMPFlushClause *FC = nullptr;
9113   OMPClause *OrderClause = nullptr;
9114   for (OMPClause *C : Clauses) {
9115     if (C->getClauseKind() == OMPC_flush)
9116       FC = cast<OMPFlushClause>(C);
9117     else
9118       OrderClause = C;
9119   }
9120   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9121   SourceLocation MemOrderLoc;
9122   for (const OMPClause *C : Clauses) {
9123     if (C->getClauseKind() == OMPC_acq_rel ||
9124         C->getClauseKind() == OMPC_acquire ||
9125         C->getClauseKind() == OMPC_release) {
9126       if (MemOrderKind != OMPC_unknown) {
9127         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9128             << getOpenMPDirectiveName(OMPD_flush) << 1
9129             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9130         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9131             << getOpenMPClauseName(MemOrderKind);
9132       } else {
9133         MemOrderKind = C->getClauseKind();
9134         MemOrderLoc = C->getBeginLoc();
9135       }
9136     }
9137   }
9138   if (FC && OrderClause) {
9139     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
9140         << getOpenMPClauseName(OrderClause->getClauseKind());
9141     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
9142         << getOpenMPClauseName(OrderClause->getClauseKind());
9143     return StmtError();
9144   }
9145   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
9146 }
9147 
9148 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
9149                                             SourceLocation StartLoc,
9150                                             SourceLocation EndLoc) {
9151   if (Clauses.empty()) {
9152     Diag(StartLoc, diag::err_omp_depobj_expected);
9153     return StmtError();
9154   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
9155     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
9156     return StmtError();
9157   }
9158   // Only depobj expression and another single clause is allowed.
9159   if (Clauses.size() > 2) {
9160     Diag(Clauses[2]->getBeginLoc(),
9161          diag::err_omp_depobj_single_clause_expected);
9162     return StmtError();
9163   } else if (Clauses.size() < 1) {
9164     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
9165     return StmtError();
9166   }
9167   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
9168 }
9169 
9170 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
9171                                           SourceLocation StartLoc,
9172                                           SourceLocation EndLoc) {
9173   // Check that exactly one clause is specified.
9174   if (Clauses.size() != 1) {
9175     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
9176          diag::err_omp_scan_single_clause_expected);
9177     return StmtError();
9178   }
9179   // Check that only one instance of scan directives is used in the same outer
9180   // region.
9181   if (DSAStack->doesParentHasScanDirective()) {
9182     Diag(StartLoc, diag::err_omp_several_scan_directives_in_region);
9183     Diag(DSAStack->getParentScanDirectiveLoc(),
9184          diag::note_omp_previous_scan_directive);
9185     return StmtError();
9186   }
9187   DSAStack->setParentHasScanDirective(StartLoc);
9188   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
9189 }
9190 
9191 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9192                                              Stmt *AStmt,
9193                                              SourceLocation StartLoc,
9194                                              SourceLocation EndLoc) {
9195   const OMPClause *DependFound = nullptr;
9196   const OMPClause *DependSourceClause = nullptr;
9197   const OMPClause *DependSinkClause = nullptr;
9198   bool ErrorFound = false;
9199   const OMPThreadsClause *TC = nullptr;
9200   const OMPSIMDClause *SC = nullptr;
9201   for (const OMPClause *C : Clauses) {
9202     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
9203       DependFound = C;
9204       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
9205         if (DependSourceClause) {
9206           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
9207               << getOpenMPDirectiveName(OMPD_ordered)
9208               << getOpenMPClauseName(OMPC_depend) << 2;
9209           ErrorFound = true;
9210         } else {
9211           DependSourceClause = C;
9212         }
9213         if (DependSinkClause) {
9214           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9215               << 0;
9216           ErrorFound = true;
9217         }
9218       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
9219         if (DependSourceClause) {
9220           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9221               << 1;
9222           ErrorFound = true;
9223         }
9224         DependSinkClause = C;
9225       }
9226     } else if (C->getClauseKind() == OMPC_threads) {
9227       TC = cast<OMPThreadsClause>(C);
9228     } else if (C->getClauseKind() == OMPC_simd) {
9229       SC = cast<OMPSIMDClause>(C);
9230     }
9231   }
9232   if (!ErrorFound && !SC &&
9233       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
9234     // OpenMP [2.8.1,simd Construct, Restrictions]
9235     // An ordered construct with the simd clause is the only OpenMP construct
9236     // that can appear in the simd region.
9237     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
9238         << (LangOpts.OpenMP >= 50 ? 1 : 0);
9239     ErrorFound = true;
9240   } else if (DependFound && (TC || SC)) {
9241     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
9242         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
9243     ErrorFound = true;
9244   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
9245     Diag(DependFound->getBeginLoc(),
9246          diag::err_omp_ordered_directive_without_param);
9247     ErrorFound = true;
9248   } else if (TC || Clauses.empty()) {
9249     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
9250       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
9251       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
9252           << (TC != nullptr);
9253       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
9254       ErrorFound = true;
9255     }
9256   }
9257   if ((!AStmt && !DependFound) || ErrorFound)
9258     return StmtError();
9259 
9260   if (AStmt) {
9261     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9262 
9263     setFunctionHasBranchProtectedScope();
9264   }
9265 
9266   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9267 }
9268 
9269 namespace {
9270 /// Helper class for checking expression in 'omp atomic [update]'
9271 /// construct.
9272 class OpenMPAtomicUpdateChecker {
9273   /// Error results for atomic update expressions.
9274   enum ExprAnalysisErrorCode {
9275     /// A statement is not an expression statement.
9276     NotAnExpression,
9277     /// Expression is not builtin binary or unary operation.
9278     NotABinaryOrUnaryExpression,
9279     /// Unary operation is not post-/pre- increment/decrement operation.
9280     NotAnUnaryIncDecExpression,
9281     /// An expression is not of scalar type.
9282     NotAScalarType,
9283     /// A binary operation is not an assignment operation.
9284     NotAnAssignmentOp,
9285     /// RHS part of the binary operation is not a binary expression.
9286     NotABinaryExpression,
9287     /// RHS part is not additive/multiplicative/shift/biwise binary
9288     /// expression.
9289     NotABinaryOperator,
9290     /// RHS binary operation does not have reference to the updated LHS
9291     /// part.
9292     NotAnUpdateExpression,
9293     /// No errors is found.
9294     NoError
9295   };
9296   /// Reference to Sema.
9297   Sema &SemaRef;
9298   /// A location for note diagnostics (when error is found).
9299   SourceLocation NoteLoc;
9300   /// 'x' lvalue part of the source atomic expression.
9301   Expr *X;
9302   /// 'expr' rvalue part of the source atomic expression.
9303   Expr *E;
9304   /// Helper expression of the form
9305   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9306   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9307   Expr *UpdateExpr;
9308   /// Is 'x' a LHS in a RHS part of full update expression. It is
9309   /// important for non-associative operations.
9310   bool IsXLHSInRHSPart;
9311   BinaryOperatorKind Op;
9312   SourceLocation OpLoc;
9313   /// true if the source expression is a postfix unary operation, false
9314   /// if it is a prefix unary operation.
9315   bool IsPostfixUpdate;
9316 
9317 public:
9318   OpenMPAtomicUpdateChecker(Sema &SemaRef)
9319       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
9320         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
9321   /// Check specified statement that it is suitable for 'atomic update'
9322   /// constructs and extract 'x', 'expr' and Operation from the original
9323   /// expression. If DiagId and NoteId == 0, then only check is performed
9324   /// without error notification.
9325   /// \param DiagId Diagnostic which should be emitted if error is found.
9326   /// \param NoteId Diagnostic note for the main error message.
9327   /// \return true if statement is not an update expression, false otherwise.
9328   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
9329   /// Return the 'x' lvalue part of the source atomic expression.
9330   Expr *getX() const { return X; }
9331   /// Return the 'expr' rvalue part of the source atomic expression.
9332   Expr *getExpr() const { return E; }
9333   /// Return the update expression used in calculation of the updated
9334   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9335   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9336   Expr *getUpdateExpr() const { return UpdateExpr; }
9337   /// Return true if 'x' is LHS in RHS part of full update expression,
9338   /// false otherwise.
9339   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
9340 
9341   /// true if the source expression is a postfix unary operation, false
9342   /// if it is a prefix unary operation.
9343   bool isPostfixUpdate() const { return IsPostfixUpdate; }
9344 
9345 private:
9346   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
9347                             unsigned NoteId = 0);
9348 };
9349 } // namespace
9350 
9351 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
9352     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
9353   ExprAnalysisErrorCode ErrorFound = NoError;
9354   SourceLocation ErrorLoc, NoteLoc;
9355   SourceRange ErrorRange, NoteRange;
9356   // Allowed constructs are:
9357   //  x = x binop expr;
9358   //  x = expr binop x;
9359   if (AtomicBinOp->getOpcode() == BO_Assign) {
9360     X = AtomicBinOp->getLHS();
9361     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
9362             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
9363       if (AtomicInnerBinOp->isMultiplicativeOp() ||
9364           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
9365           AtomicInnerBinOp->isBitwiseOp()) {
9366         Op = AtomicInnerBinOp->getOpcode();
9367         OpLoc = AtomicInnerBinOp->getOperatorLoc();
9368         Expr *LHS = AtomicInnerBinOp->getLHS();
9369         Expr *RHS = AtomicInnerBinOp->getRHS();
9370         llvm::FoldingSetNodeID XId, LHSId, RHSId;
9371         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
9372                                           /*Canonical=*/true);
9373         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
9374                                             /*Canonical=*/true);
9375         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
9376                                             /*Canonical=*/true);
9377         if (XId == LHSId) {
9378           E = RHS;
9379           IsXLHSInRHSPart = true;
9380         } else if (XId == RHSId) {
9381           E = LHS;
9382           IsXLHSInRHSPart = false;
9383         } else {
9384           ErrorLoc = AtomicInnerBinOp->getExprLoc();
9385           ErrorRange = AtomicInnerBinOp->getSourceRange();
9386           NoteLoc = X->getExprLoc();
9387           NoteRange = X->getSourceRange();
9388           ErrorFound = NotAnUpdateExpression;
9389         }
9390       } else {
9391         ErrorLoc = AtomicInnerBinOp->getExprLoc();
9392         ErrorRange = AtomicInnerBinOp->getSourceRange();
9393         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
9394         NoteRange = SourceRange(NoteLoc, NoteLoc);
9395         ErrorFound = NotABinaryOperator;
9396       }
9397     } else {
9398       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
9399       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
9400       ErrorFound = NotABinaryExpression;
9401     }
9402   } else {
9403     ErrorLoc = AtomicBinOp->getExprLoc();
9404     ErrorRange = AtomicBinOp->getSourceRange();
9405     NoteLoc = AtomicBinOp->getOperatorLoc();
9406     NoteRange = SourceRange(NoteLoc, NoteLoc);
9407     ErrorFound = NotAnAssignmentOp;
9408   }
9409   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9410     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9411     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9412     return true;
9413   }
9414   if (SemaRef.CurContext->isDependentContext())
9415     E = X = UpdateExpr = nullptr;
9416   return ErrorFound != NoError;
9417 }
9418 
9419 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
9420                                                unsigned NoteId) {
9421   ExprAnalysisErrorCode ErrorFound = NoError;
9422   SourceLocation ErrorLoc, NoteLoc;
9423   SourceRange ErrorRange, NoteRange;
9424   // Allowed constructs are:
9425   //  x++;
9426   //  x--;
9427   //  ++x;
9428   //  --x;
9429   //  x binop= expr;
9430   //  x = x binop expr;
9431   //  x = expr binop x;
9432   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
9433     AtomicBody = AtomicBody->IgnoreParenImpCasts();
9434     if (AtomicBody->getType()->isScalarType() ||
9435         AtomicBody->isInstantiationDependent()) {
9436       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
9437               AtomicBody->IgnoreParenImpCasts())) {
9438         // Check for Compound Assignment Operation
9439         Op = BinaryOperator::getOpForCompoundAssignment(
9440             AtomicCompAssignOp->getOpcode());
9441         OpLoc = AtomicCompAssignOp->getOperatorLoc();
9442         E = AtomicCompAssignOp->getRHS();
9443         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
9444         IsXLHSInRHSPart = true;
9445       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
9446                      AtomicBody->IgnoreParenImpCasts())) {
9447         // Check for Binary Operation
9448         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
9449           return true;
9450       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
9451                      AtomicBody->IgnoreParenImpCasts())) {
9452         // Check for Unary Operation
9453         if (AtomicUnaryOp->isIncrementDecrementOp()) {
9454           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
9455           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
9456           OpLoc = AtomicUnaryOp->getOperatorLoc();
9457           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
9458           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
9459           IsXLHSInRHSPart = true;
9460         } else {
9461           ErrorFound = NotAnUnaryIncDecExpression;
9462           ErrorLoc = AtomicUnaryOp->getExprLoc();
9463           ErrorRange = AtomicUnaryOp->getSourceRange();
9464           NoteLoc = AtomicUnaryOp->getOperatorLoc();
9465           NoteRange = SourceRange(NoteLoc, NoteLoc);
9466         }
9467       } else if (!AtomicBody->isInstantiationDependent()) {
9468         ErrorFound = NotABinaryOrUnaryExpression;
9469         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
9470         NoteRange = ErrorRange = AtomicBody->getSourceRange();
9471       }
9472     } else {
9473       ErrorFound = NotAScalarType;
9474       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
9475       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9476     }
9477   } else {
9478     ErrorFound = NotAnExpression;
9479     NoteLoc = ErrorLoc = S->getBeginLoc();
9480     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9481   }
9482   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9483     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9484     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9485     return true;
9486   }
9487   if (SemaRef.CurContext->isDependentContext())
9488     E = X = UpdateExpr = nullptr;
9489   if (ErrorFound == NoError && E && X) {
9490     // Build an update expression of form 'OpaqueValueExpr(x) binop
9491     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
9492     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
9493     auto *OVEX = new (SemaRef.getASTContext())
9494         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
9495     auto *OVEExpr = new (SemaRef.getASTContext())
9496         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
9497     ExprResult Update =
9498         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
9499                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
9500     if (Update.isInvalid())
9501       return true;
9502     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
9503                                                Sema::AA_Casting);
9504     if (Update.isInvalid())
9505       return true;
9506     UpdateExpr = Update.get();
9507   }
9508   return ErrorFound != NoError;
9509 }
9510 
9511 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9512                                             Stmt *AStmt,
9513                                             SourceLocation StartLoc,
9514                                             SourceLocation EndLoc) {
9515   // Register location of the first atomic directive.
9516   DSAStack->addAtomicDirectiveLoc(StartLoc);
9517   if (!AStmt)
9518     return StmtError();
9519 
9520   auto *CS = cast<CapturedStmt>(AStmt);
9521   // 1.2.2 OpenMP Language Terminology
9522   // Structured block - An executable statement with a single entry at the
9523   // top and a single exit at the bottom.
9524   // The point of exit cannot be a branch out of the structured block.
9525   // longjmp() and throw() must not violate the entry/exit criteria.
9526   OpenMPClauseKind AtomicKind = OMPC_unknown;
9527   SourceLocation AtomicKindLoc;
9528   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9529   SourceLocation MemOrderLoc;
9530   for (const OMPClause *C : Clauses) {
9531     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
9532         C->getClauseKind() == OMPC_update ||
9533         C->getClauseKind() == OMPC_capture) {
9534       if (AtomicKind != OMPC_unknown) {
9535         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
9536             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9537         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
9538             << getOpenMPClauseName(AtomicKind);
9539       } else {
9540         AtomicKind = C->getClauseKind();
9541         AtomicKindLoc = C->getBeginLoc();
9542       }
9543     }
9544     if (C->getClauseKind() == OMPC_seq_cst ||
9545         C->getClauseKind() == OMPC_acq_rel ||
9546         C->getClauseKind() == OMPC_acquire ||
9547         C->getClauseKind() == OMPC_release ||
9548         C->getClauseKind() == OMPC_relaxed) {
9549       if (MemOrderKind != OMPC_unknown) {
9550         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9551             << getOpenMPDirectiveName(OMPD_atomic) << 0
9552             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9553         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9554             << getOpenMPClauseName(MemOrderKind);
9555       } else {
9556         MemOrderKind = C->getClauseKind();
9557         MemOrderLoc = C->getBeginLoc();
9558       }
9559     }
9560   }
9561   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
9562   // If atomic-clause is read then memory-order-clause must not be acq_rel or
9563   // release.
9564   // If atomic-clause is write then memory-order-clause must not be acq_rel or
9565   // acquire.
9566   // If atomic-clause is update or not present then memory-order-clause must not
9567   // be acq_rel or acquire.
9568   if ((AtomicKind == OMPC_read &&
9569        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
9570       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
9571         AtomicKind == OMPC_unknown) &&
9572        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
9573     SourceLocation Loc = AtomicKindLoc;
9574     if (AtomicKind == OMPC_unknown)
9575       Loc = StartLoc;
9576     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
9577         << getOpenMPClauseName(AtomicKind)
9578         << (AtomicKind == OMPC_unknown ? 1 : 0)
9579         << getOpenMPClauseName(MemOrderKind);
9580     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9581         << getOpenMPClauseName(MemOrderKind);
9582   }
9583 
9584   Stmt *Body = CS->getCapturedStmt();
9585   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
9586     Body = EWC->getSubExpr();
9587 
9588   Expr *X = nullptr;
9589   Expr *V = nullptr;
9590   Expr *E = nullptr;
9591   Expr *UE = nullptr;
9592   bool IsXLHSInRHSPart = false;
9593   bool IsPostfixUpdate = false;
9594   // OpenMP [2.12.6, atomic Construct]
9595   // In the next expressions:
9596   // * x and v (as applicable) are both l-value expressions with scalar type.
9597   // * During the execution of an atomic region, multiple syntactic
9598   // occurrences of x must designate the same storage location.
9599   // * Neither of v and expr (as applicable) may access the storage location
9600   // designated by x.
9601   // * Neither of x and expr (as applicable) may access the storage location
9602   // designated by v.
9603   // * expr is an expression with scalar type.
9604   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
9605   // * binop, binop=, ++, and -- are not overloaded operators.
9606   // * The expression x binop expr must be numerically equivalent to x binop
9607   // (expr). This requirement is satisfied if the operators in expr have
9608   // precedence greater than binop, or by using parentheses around expr or
9609   // subexpressions of expr.
9610   // * The expression expr binop x must be numerically equivalent to (expr)
9611   // binop x. This requirement is satisfied if the operators in expr have
9612   // precedence equal to or greater than binop, or by using parentheses around
9613   // expr or subexpressions of expr.
9614   // * For forms that allow multiple occurrences of x, the number of times
9615   // that x is evaluated is unspecified.
9616   if (AtomicKind == OMPC_read) {
9617     enum {
9618       NotAnExpression,
9619       NotAnAssignmentOp,
9620       NotAScalarType,
9621       NotAnLValue,
9622       NoError
9623     } ErrorFound = NoError;
9624     SourceLocation ErrorLoc, NoteLoc;
9625     SourceRange ErrorRange, NoteRange;
9626     // If clause is read:
9627     //  v = x;
9628     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9629       const auto *AtomicBinOp =
9630           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9631       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9632         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9633         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
9634         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9635             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
9636           if (!X->isLValue() || !V->isLValue()) {
9637             const Expr *NotLValueExpr = X->isLValue() ? V : X;
9638             ErrorFound = NotAnLValue;
9639             ErrorLoc = AtomicBinOp->getExprLoc();
9640             ErrorRange = AtomicBinOp->getSourceRange();
9641             NoteLoc = NotLValueExpr->getExprLoc();
9642             NoteRange = NotLValueExpr->getSourceRange();
9643           }
9644         } else if (!X->isInstantiationDependent() ||
9645                    !V->isInstantiationDependent()) {
9646           const Expr *NotScalarExpr =
9647               (X->isInstantiationDependent() || X->getType()->isScalarType())
9648                   ? V
9649                   : X;
9650           ErrorFound = NotAScalarType;
9651           ErrorLoc = AtomicBinOp->getExprLoc();
9652           ErrorRange = AtomicBinOp->getSourceRange();
9653           NoteLoc = NotScalarExpr->getExprLoc();
9654           NoteRange = NotScalarExpr->getSourceRange();
9655         }
9656       } else if (!AtomicBody->isInstantiationDependent()) {
9657         ErrorFound = NotAnAssignmentOp;
9658         ErrorLoc = AtomicBody->getExprLoc();
9659         ErrorRange = AtomicBody->getSourceRange();
9660         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9661                               : AtomicBody->getExprLoc();
9662         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9663                                 : AtomicBody->getSourceRange();
9664       }
9665     } else {
9666       ErrorFound = NotAnExpression;
9667       NoteLoc = ErrorLoc = Body->getBeginLoc();
9668       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9669     }
9670     if (ErrorFound != NoError) {
9671       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
9672           << ErrorRange;
9673       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9674                                                       << NoteRange;
9675       return StmtError();
9676     }
9677     if (CurContext->isDependentContext())
9678       V = X = nullptr;
9679   } else if (AtomicKind == OMPC_write) {
9680     enum {
9681       NotAnExpression,
9682       NotAnAssignmentOp,
9683       NotAScalarType,
9684       NotAnLValue,
9685       NoError
9686     } ErrorFound = NoError;
9687     SourceLocation ErrorLoc, NoteLoc;
9688     SourceRange ErrorRange, NoteRange;
9689     // If clause is write:
9690     //  x = expr;
9691     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9692       const auto *AtomicBinOp =
9693           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9694       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9695         X = AtomicBinOp->getLHS();
9696         E = AtomicBinOp->getRHS();
9697         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9698             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
9699           if (!X->isLValue()) {
9700             ErrorFound = NotAnLValue;
9701             ErrorLoc = AtomicBinOp->getExprLoc();
9702             ErrorRange = AtomicBinOp->getSourceRange();
9703             NoteLoc = X->getExprLoc();
9704             NoteRange = X->getSourceRange();
9705           }
9706         } else if (!X->isInstantiationDependent() ||
9707                    !E->isInstantiationDependent()) {
9708           const Expr *NotScalarExpr =
9709               (X->isInstantiationDependent() || X->getType()->isScalarType())
9710                   ? E
9711                   : X;
9712           ErrorFound = NotAScalarType;
9713           ErrorLoc = AtomicBinOp->getExprLoc();
9714           ErrorRange = AtomicBinOp->getSourceRange();
9715           NoteLoc = NotScalarExpr->getExprLoc();
9716           NoteRange = NotScalarExpr->getSourceRange();
9717         }
9718       } else if (!AtomicBody->isInstantiationDependent()) {
9719         ErrorFound = NotAnAssignmentOp;
9720         ErrorLoc = AtomicBody->getExprLoc();
9721         ErrorRange = AtomicBody->getSourceRange();
9722         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9723                               : AtomicBody->getExprLoc();
9724         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9725                                 : AtomicBody->getSourceRange();
9726       }
9727     } else {
9728       ErrorFound = NotAnExpression;
9729       NoteLoc = ErrorLoc = Body->getBeginLoc();
9730       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9731     }
9732     if (ErrorFound != NoError) {
9733       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9734           << ErrorRange;
9735       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9736                                                       << NoteRange;
9737       return StmtError();
9738     }
9739     if (CurContext->isDependentContext())
9740       E = X = nullptr;
9741   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
9742     // If clause is update:
9743     //  x++;
9744     //  x--;
9745     //  ++x;
9746     //  --x;
9747     //  x binop= expr;
9748     //  x = x binop expr;
9749     //  x = expr binop x;
9750     OpenMPAtomicUpdateChecker Checker(*this);
9751     if (Checker.checkStatement(
9752             Body, (AtomicKind == OMPC_update)
9753                       ? diag::err_omp_atomic_update_not_expression_statement
9754                       : diag::err_omp_atomic_not_expression_statement,
9755             diag::note_omp_atomic_update))
9756       return StmtError();
9757     if (!CurContext->isDependentContext()) {
9758       E = Checker.getExpr();
9759       X = Checker.getX();
9760       UE = Checker.getUpdateExpr();
9761       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9762     }
9763   } else if (AtomicKind == OMPC_capture) {
9764     enum {
9765       NotAnAssignmentOp,
9766       NotACompoundStatement,
9767       NotTwoSubstatements,
9768       NotASpecificExpression,
9769       NoError
9770     } ErrorFound = NoError;
9771     SourceLocation ErrorLoc, NoteLoc;
9772     SourceRange ErrorRange, NoteRange;
9773     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9774       // If clause is a capture:
9775       //  v = x++;
9776       //  v = x--;
9777       //  v = ++x;
9778       //  v = --x;
9779       //  v = x binop= expr;
9780       //  v = x = x binop expr;
9781       //  v = x = expr binop x;
9782       const auto *AtomicBinOp =
9783           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9784       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9785         V = AtomicBinOp->getLHS();
9786         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9787         OpenMPAtomicUpdateChecker Checker(*this);
9788         if (Checker.checkStatement(
9789                 Body, diag::err_omp_atomic_capture_not_expression_statement,
9790                 diag::note_omp_atomic_update))
9791           return StmtError();
9792         E = Checker.getExpr();
9793         X = Checker.getX();
9794         UE = Checker.getUpdateExpr();
9795         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9796         IsPostfixUpdate = Checker.isPostfixUpdate();
9797       } else if (!AtomicBody->isInstantiationDependent()) {
9798         ErrorLoc = AtomicBody->getExprLoc();
9799         ErrorRange = AtomicBody->getSourceRange();
9800         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9801                               : AtomicBody->getExprLoc();
9802         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9803                                 : AtomicBody->getSourceRange();
9804         ErrorFound = NotAnAssignmentOp;
9805       }
9806       if (ErrorFound != NoError) {
9807         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9808             << ErrorRange;
9809         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9810         return StmtError();
9811       }
9812       if (CurContext->isDependentContext())
9813         UE = V = E = X = nullptr;
9814     } else {
9815       // If clause is a capture:
9816       //  { v = x; x = expr; }
9817       //  { v = x; x++; }
9818       //  { v = x; x--; }
9819       //  { v = x; ++x; }
9820       //  { v = x; --x; }
9821       //  { v = x; x binop= expr; }
9822       //  { v = x; x = x binop expr; }
9823       //  { v = x; x = expr binop x; }
9824       //  { x++; v = x; }
9825       //  { x--; v = x; }
9826       //  { ++x; v = x; }
9827       //  { --x; v = x; }
9828       //  { x binop= expr; v = x; }
9829       //  { x = x binop expr; v = x; }
9830       //  { x = expr binop x; v = x; }
9831       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9832         // Check that this is { expr1; expr2; }
9833         if (CS->size() == 2) {
9834           Stmt *First = CS->body_front();
9835           Stmt *Second = CS->body_back();
9836           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9837             First = EWC->getSubExpr()->IgnoreParenImpCasts();
9838           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9839             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9840           // Need to find what subexpression is 'v' and what is 'x'.
9841           OpenMPAtomicUpdateChecker Checker(*this);
9842           bool IsUpdateExprFound = !Checker.checkStatement(Second);
9843           BinaryOperator *BinOp = nullptr;
9844           if (IsUpdateExprFound) {
9845             BinOp = dyn_cast<BinaryOperator>(First);
9846             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9847           }
9848           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9849             //  { v = x; x++; }
9850             //  { v = x; x--; }
9851             //  { v = x; ++x; }
9852             //  { v = x; --x; }
9853             //  { v = x; x binop= expr; }
9854             //  { v = x; x = x binop expr; }
9855             //  { v = x; x = expr binop x; }
9856             // Check that the first expression has form v = x.
9857             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
9858             llvm::FoldingSetNodeID XId, PossibleXId;
9859             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9860             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9861             IsUpdateExprFound = XId == PossibleXId;
9862             if (IsUpdateExprFound) {
9863               V = BinOp->getLHS();
9864               X = Checker.getX();
9865               E = Checker.getExpr();
9866               UE = Checker.getUpdateExpr();
9867               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9868               IsPostfixUpdate = true;
9869             }
9870           }
9871           if (!IsUpdateExprFound) {
9872             IsUpdateExprFound = !Checker.checkStatement(First);
9873             BinOp = nullptr;
9874             if (IsUpdateExprFound) {
9875               BinOp = dyn_cast<BinaryOperator>(Second);
9876               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9877             }
9878             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9879               //  { x++; v = x; }
9880               //  { x--; v = x; }
9881               //  { ++x; v = x; }
9882               //  { --x; v = x; }
9883               //  { x binop= expr; v = x; }
9884               //  { x = x binop expr; v = x; }
9885               //  { x = expr binop x; v = x; }
9886               // Check that the second expression has form v = x.
9887               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
9888               llvm::FoldingSetNodeID XId, PossibleXId;
9889               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9890               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9891               IsUpdateExprFound = XId == PossibleXId;
9892               if (IsUpdateExprFound) {
9893                 V = BinOp->getLHS();
9894                 X = Checker.getX();
9895                 E = Checker.getExpr();
9896                 UE = Checker.getUpdateExpr();
9897                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9898                 IsPostfixUpdate = false;
9899               }
9900             }
9901           }
9902           if (!IsUpdateExprFound) {
9903             //  { v = x; x = expr; }
9904             auto *FirstExpr = dyn_cast<Expr>(First);
9905             auto *SecondExpr = dyn_cast<Expr>(Second);
9906             if (!FirstExpr || !SecondExpr ||
9907                 !(FirstExpr->isInstantiationDependent() ||
9908                   SecondExpr->isInstantiationDependent())) {
9909               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9910               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
9911                 ErrorFound = NotAnAssignmentOp;
9912                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
9913                                                 : First->getBeginLoc();
9914                 NoteRange = ErrorRange = FirstBinOp
9915                                              ? FirstBinOp->getSourceRange()
9916                                              : SourceRange(ErrorLoc, ErrorLoc);
9917               } else {
9918                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9919                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9920                   ErrorFound = NotAnAssignmentOp;
9921                   NoteLoc = ErrorLoc = SecondBinOp
9922                                            ? SecondBinOp->getOperatorLoc()
9923                                            : Second->getBeginLoc();
9924                   NoteRange = ErrorRange =
9925                       SecondBinOp ? SecondBinOp->getSourceRange()
9926                                   : SourceRange(ErrorLoc, ErrorLoc);
9927                 } else {
9928                   Expr *PossibleXRHSInFirst =
9929                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
9930                   Expr *PossibleXLHSInSecond =
9931                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
9932                   llvm::FoldingSetNodeID X1Id, X2Id;
9933                   PossibleXRHSInFirst->Profile(X1Id, Context,
9934                                                /*Canonical=*/true);
9935                   PossibleXLHSInSecond->Profile(X2Id, Context,
9936                                                 /*Canonical=*/true);
9937                   IsUpdateExprFound = X1Id == X2Id;
9938                   if (IsUpdateExprFound) {
9939                     V = FirstBinOp->getLHS();
9940                     X = SecondBinOp->getLHS();
9941                     E = SecondBinOp->getRHS();
9942                     UE = nullptr;
9943                     IsXLHSInRHSPart = false;
9944                     IsPostfixUpdate = true;
9945                   } else {
9946                     ErrorFound = NotASpecificExpression;
9947                     ErrorLoc = FirstBinOp->getExprLoc();
9948                     ErrorRange = FirstBinOp->getSourceRange();
9949                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9950                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
9951                   }
9952                 }
9953               }
9954             }
9955           }
9956         } else {
9957           NoteLoc = ErrorLoc = Body->getBeginLoc();
9958           NoteRange = ErrorRange =
9959               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
9960           ErrorFound = NotTwoSubstatements;
9961         }
9962       } else {
9963         NoteLoc = ErrorLoc = Body->getBeginLoc();
9964         NoteRange = ErrorRange =
9965             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
9966         ErrorFound = NotACompoundStatement;
9967       }
9968       if (ErrorFound != NoError) {
9969         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9970             << ErrorRange;
9971         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9972         return StmtError();
9973       }
9974       if (CurContext->isDependentContext())
9975         UE = V = E = X = nullptr;
9976     }
9977   }
9978 
9979   setFunctionHasBranchProtectedScope();
9980 
9981   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9982                                     X, V, E, UE, IsXLHSInRHSPart,
9983                                     IsPostfixUpdate);
9984 }
9985 
9986 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9987                                             Stmt *AStmt,
9988                                             SourceLocation StartLoc,
9989                                             SourceLocation EndLoc) {
9990   if (!AStmt)
9991     return StmtError();
9992 
9993   auto *CS = cast<CapturedStmt>(AStmt);
9994   // 1.2.2 OpenMP Language Terminology
9995   // Structured block - An executable statement with a single entry at the
9996   // top and a single exit at the bottom.
9997   // The point of exit cannot be a branch out of the structured block.
9998   // longjmp() and throw() must not violate the entry/exit criteria.
9999   CS->getCapturedDecl()->setNothrow();
10000   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
10001        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10002     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10003     // 1.2.2 OpenMP Language Terminology
10004     // Structured block - An executable statement with a single entry at the
10005     // top and a single exit at the bottom.
10006     // The point of exit cannot be a branch out of the structured block.
10007     // longjmp() and throw() must not violate the entry/exit criteria.
10008     CS->getCapturedDecl()->setNothrow();
10009   }
10010 
10011   // OpenMP [2.16, Nesting of Regions]
10012   // If specified, a teams construct must be contained within a target
10013   // construct. That target construct must contain no statements or directives
10014   // outside of the teams construct.
10015   if (DSAStack->hasInnerTeamsRegion()) {
10016     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
10017     bool OMPTeamsFound = true;
10018     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
10019       auto I = CS->body_begin();
10020       while (I != CS->body_end()) {
10021         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
10022         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
10023             OMPTeamsFound) {
10024 
10025           OMPTeamsFound = false;
10026           break;
10027         }
10028         ++I;
10029       }
10030       assert(I != CS->body_end() && "Not found statement");
10031       S = *I;
10032     } else {
10033       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
10034       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
10035     }
10036     if (!OMPTeamsFound) {
10037       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
10038       Diag(DSAStack->getInnerTeamsRegionLoc(),
10039            diag::note_omp_nested_teams_construct_here);
10040       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
10041           << isa<OMPExecutableDirective>(S);
10042       return StmtError();
10043     }
10044   }
10045 
10046   setFunctionHasBranchProtectedScope();
10047 
10048   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10049 }
10050 
10051 StmtResult
10052 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10053                                          Stmt *AStmt, SourceLocation StartLoc,
10054                                          SourceLocation EndLoc) {
10055   if (!AStmt)
10056     return StmtError();
10057 
10058   auto *CS = cast<CapturedStmt>(AStmt);
10059   // 1.2.2 OpenMP Language Terminology
10060   // Structured block - An executable statement with a single entry at the
10061   // top and a single exit at the bottom.
10062   // The point of exit cannot be a branch out of the structured block.
10063   // longjmp() and throw() must not violate the entry/exit criteria.
10064   CS->getCapturedDecl()->setNothrow();
10065   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
10066        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10067     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10068     // 1.2.2 OpenMP Language Terminology
10069     // Structured block - An executable statement with a single entry at the
10070     // top and a single exit at the bottom.
10071     // The point of exit cannot be a branch out of the structured block.
10072     // longjmp() and throw() must not violate the entry/exit criteria.
10073     CS->getCapturedDecl()->setNothrow();
10074   }
10075 
10076   setFunctionHasBranchProtectedScope();
10077 
10078   return OMPTargetParallelDirective::Create(
10079       Context, StartLoc, EndLoc, Clauses, AStmt,
10080       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10081 }
10082 
10083 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
10084     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10085     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10086   if (!AStmt)
10087     return StmtError();
10088 
10089   auto *CS = cast<CapturedStmt>(AStmt);
10090   // 1.2.2 OpenMP Language Terminology
10091   // Structured block - An executable statement with a single entry at the
10092   // top and a single exit at the bottom.
10093   // The point of exit cannot be a branch out of the structured block.
10094   // longjmp() and throw() must not violate the entry/exit criteria.
10095   CS->getCapturedDecl()->setNothrow();
10096   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10097        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10098     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10099     // 1.2.2 OpenMP Language Terminology
10100     // Structured block - An executable statement with a single entry at the
10101     // top and a single exit at the bottom.
10102     // The point of exit cannot be a branch out of the structured block.
10103     // longjmp() and throw() must not violate the entry/exit criteria.
10104     CS->getCapturedDecl()->setNothrow();
10105   }
10106 
10107   OMPLoopDirective::HelperExprs B;
10108   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10109   // define the nested loops number.
10110   unsigned NestedLoopCount =
10111       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
10112                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
10113                       VarsWithImplicitDSA, B);
10114   if (NestedLoopCount == 0)
10115     return StmtError();
10116 
10117   assert((CurContext->isDependentContext() || B.builtAll()) &&
10118          "omp target parallel for loop exprs were not built");
10119 
10120   if (!CurContext->isDependentContext()) {
10121     // Finalize the clauses that need pre-built expressions for CodeGen.
10122     for (OMPClause *C : Clauses) {
10123       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10124         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10125                                      B.NumIterations, *this, CurScope,
10126                                      DSAStack))
10127           return StmtError();
10128     }
10129   }
10130 
10131   setFunctionHasBranchProtectedScope();
10132   return OMPTargetParallelForDirective::Create(
10133       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10134       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10135 }
10136 
10137 /// Check for existence of a map clause in the list of clauses.
10138 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
10139                        const OpenMPClauseKind K) {
10140   return llvm::any_of(
10141       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
10142 }
10143 
10144 template <typename... Params>
10145 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
10146                        const Params... ClauseTypes) {
10147   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
10148 }
10149 
10150 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10151                                                 Stmt *AStmt,
10152                                                 SourceLocation StartLoc,
10153                                                 SourceLocation EndLoc) {
10154   if (!AStmt)
10155     return StmtError();
10156 
10157   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10158 
10159   // OpenMP [2.12.2, target data Construct, Restrictions]
10160   // At least one map, use_device_addr or use_device_ptr clause must appear on
10161   // the directive.
10162   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
10163       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
10164     StringRef Expected;
10165     if (LangOpts.OpenMP < 50)
10166       Expected = "'map' or 'use_device_ptr'";
10167     else
10168       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
10169     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10170         << Expected << getOpenMPDirectiveName(OMPD_target_data);
10171     return StmtError();
10172   }
10173 
10174   setFunctionHasBranchProtectedScope();
10175 
10176   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10177                                         AStmt);
10178 }
10179 
10180 StmtResult
10181 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10182                                           SourceLocation StartLoc,
10183                                           SourceLocation EndLoc, Stmt *AStmt) {
10184   if (!AStmt)
10185     return StmtError();
10186 
10187   auto *CS = cast<CapturedStmt>(AStmt);
10188   // 1.2.2 OpenMP Language Terminology
10189   // Structured block - An executable statement with a single entry at the
10190   // top and a single exit at the bottom.
10191   // The point of exit cannot be a branch out of the structured block.
10192   // longjmp() and throw() must not violate the entry/exit criteria.
10193   CS->getCapturedDecl()->setNothrow();
10194   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
10195        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10196     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10197     // 1.2.2 OpenMP Language Terminology
10198     // Structured block - An executable statement with a single entry at the
10199     // top and a single exit at the bottom.
10200     // The point of exit cannot be a branch out of the structured block.
10201     // longjmp() and throw() must not violate the entry/exit criteria.
10202     CS->getCapturedDecl()->setNothrow();
10203   }
10204 
10205   // OpenMP [2.10.2, Restrictions, p. 99]
10206   // At least one map clause must appear on the directive.
10207   if (!hasClauses(Clauses, OMPC_map)) {
10208     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10209         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
10210     return StmtError();
10211   }
10212 
10213   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10214                                              AStmt);
10215 }
10216 
10217 StmtResult
10218 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10219                                          SourceLocation StartLoc,
10220                                          SourceLocation EndLoc, Stmt *AStmt) {
10221   if (!AStmt)
10222     return StmtError();
10223 
10224   auto *CS = cast<CapturedStmt>(AStmt);
10225   // 1.2.2 OpenMP Language Terminology
10226   // Structured block - An executable statement with a single entry at the
10227   // top and a single exit at the bottom.
10228   // The point of exit cannot be a branch out of the structured block.
10229   // longjmp() and throw() must not violate the entry/exit criteria.
10230   CS->getCapturedDecl()->setNothrow();
10231   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
10232        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10233     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10234     // 1.2.2 OpenMP Language Terminology
10235     // Structured block - An executable statement with a single entry at the
10236     // top and a single exit at the bottom.
10237     // The point of exit cannot be a branch out of the structured block.
10238     // longjmp() and throw() must not violate the entry/exit criteria.
10239     CS->getCapturedDecl()->setNothrow();
10240   }
10241 
10242   // OpenMP [2.10.3, Restrictions, p. 102]
10243   // At least one map clause must appear on the directive.
10244   if (!hasClauses(Clauses, OMPC_map)) {
10245     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10246         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
10247     return StmtError();
10248   }
10249 
10250   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10251                                             AStmt);
10252 }
10253 
10254 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10255                                                   SourceLocation StartLoc,
10256                                                   SourceLocation EndLoc,
10257                                                   Stmt *AStmt) {
10258   if (!AStmt)
10259     return StmtError();
10260 
10261   auto *CS = cast<CapturedStmt>(AStmt);
10262   // 1.2.2 OpenMP Language Terminology
10263   // Structured block - An executable statement with a single entry at the
10264   // top and a single exit at the bottom.
10265   // The point of exit cannot be a branch out of the structured block.
10266   // longjmp() and throw() must not violate the entry/exit criteria.
10267   CS->getCapturedDecl()->setNothrow();
10268   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
10269        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10270     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10271     // 1.2.2 OpenMP Language Terminology
10272     // Structured block - An executable statement with a single entry at the
10273     // top and a single exit at the bottom.
10274     // The point of exit cannot be a branch out of the structured block.
10275     // longjmp() and throw() must not violate the entry/exit criteria.
10276     CS->getCapturedDecl()->setNothrow();
10277   }
10278 
10279   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
10280     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
10281     return StmtError();
10282   }
10283   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
10284                                           AStmt);
10285 }
10286 
10287 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10288                                            Stmt *AStmt, SourceLocation StartLoc,
10289                                            SourceLocation EndLoc) {
10290   if (!AStmt)
10291     return StmtError();
10292 
10293   auto *CS = cast<CapturedStmt>(AStmt);
10294   // 1.2.2 OpenMP Language Terminology
10295   // Structured block - An executable statement with a single entry at the
10296   // top and a single exit at the bottom.
10297   // The point of exit cannot be a branch out of the structured block.
10298   // longjmp() and throw() must not violate the entry/exit criteria.
10299   CS->getCapturedDecl()->setNothrow();
10300 
10301   setFunctionHasBranchProtectedScope();
10302 
10303   DSAStack->setParentTeamsRegionLoc(StartLoc);
10304 
10305   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10306 }
10307 
10308 StmtResult
10309 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10310                                             SourceLocation EndLoc,
10311                                             OpenMPDirectiveKind CancelRegion) {
10312   if (DSAStack->isParentNowaitRegion()) {
10313     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
10314     return StmtError();
10315   }
10316   if (DSAStack->isParentOrderedRegion()) {
10317     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
10318     return StmtError();
10319   }
10320   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
10321                                                CancelRegion);
10322 }
10323 
10324 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10325                                             SourceLocation StartLoc,
10326                                             SourceLocation EndLoc,
10327                                             OpenMPDirectiveKind CancelRegion) {
10328   if (DSAStack->isParentNowaitRegion()) {
10329     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
10330     return StmtError();
10331   }
10332   if (DSAStack->isParentOrderedRegion()) {
10333     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
10334     return StmtError();
10335   }
10336   DSAStack->setParentCancelRegion(/*Cancel=*/true);
10337   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
10338                                     CancelRegion);
10339 }
10340 
10341 static bool checkGrainsizeNumTasksClauses(Sema &S,
10342                                           ArrayRef<OMPClause *> Clauses) {
10343   const OMPClause *PrevClause = nullptr;
10344   bool ErrorFound = false;
10345   for (const OMPClause *C : Clauses) {
10346     if (C->getClauseKind() == OMPC_grainsize ||
10347         C->getClauseKind() == OMPC_num_tasks) {
10348       if (!PrevClause)
10349         PrevClause = C;
10350       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10351         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10352             << getOpenMPClauseName(C->getClauseKind())
10353             << getOpenMPClauseName(PrevClause->getClauseKind());
10354         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10355             << getOpenMPClauseName(PrevClause->getClauseKind());
10356         ErrorFound = true;
10357       }
10358     }
10359   }
10360   return ErrorFound;
10361 }
10362 
10363 static bool checkReductionClauseWithNogroup(Sema &S,
10364                                             ArrayRef<OMPClause *> Clauses) {
10365   const OMPClause *ReductionClause = nullptr;
10366   const OMPClause *NogroupClause = nullptr;
10367   for (const OMPClause *C : Clauses) {
10368     if (C->getClauseKind() == OMPC_reduction) {
10369       ReductionClause = C;
10370       if (NogroupClause)
10371         break;
10372       continue;
10373     }
10374     if (C->getClauseKind() == OMPC_nogroup) {
10375       NogroupClause = C;
10376       if (ReductionClause)
10377         break;
10378       continue;
10379     }
10380   }
10381   if (ReductionClause && NogroupClause) {
10382     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
10383         << SourceRange(NogroupClause->getBeginLoc(),
10384                        NogroupClause->getEndLoc());
10385     return true;
10386   }
10387   return false;
10388 }
10389 
10390 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
10391     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10392     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10393   if (!AStmt)
10394     return StmtError();
10395 
10396   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10397   OMPLoopDirective::HelperExprs B;
10398   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10399   // define the nested loops number.
10400   unsigned NestedLoopCount =
10401       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
10402                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10403                       VarsWithImplicitDSA, B);
10404   if (NestedLoopCount == 0)
10405     return StmtError();
10406 
10407   assert((CurContext->isDependentContext() || B.builtAll()) &&
10408          "omp for loop exprs were not built");
10409 
10410   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10411   // The grainsize clause and num_tasks clause are mutually exclusive and may
10412   // not appear on the same taskloop directive.
10413   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10414     return StmtError();
10415   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10416   // If a reduction clause is present on the taskloop directive, the nogroup
10417   // clause must not be specified.
10418   if (checkReductionClauseWithNogroup(*this, Clauses))
10419     return StmtError();
10420 
10421   setFunctionHasBranchProtectedScope();
10422   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10423                                       NestedLoopCount, Clauses, AStmt, B,
10424                                       DSAStack->isCancelRegion());
10425 }
10426 
10427 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
10428     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10429     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10430   if (!AStmt)
10431     return StmtError();
10432 
10433   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10434   OMPLoopDirective::HelperExprs B;
10435   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10436   // define the nested loops number.
10437   unsigned NestedLoopCount =
10438       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
10439                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10440                       VarsWithImplicitDSA, B);
10441   if (NestedLoopCount == 0)
10442     return StmtError();
10443 
10444   assert((CurContext->isDependentContext() || B.builtAll()) &&
10445          "omp for loop exprs were not built");
10446 
10447   if (!CurContext->isDependentContext()) {
10448     // Finalize the clauses that need pre-built expressions for CodeGen.
10449     for (OMPClause *C : Clauses) {
10450       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10451         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10452                                      B.NumIterations, *this, CurScope,
10453                                      DSAStack))
10454           return StmtError();
10455     }
10456   }
10457 
10458   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10459   // The grainsize clause and num_tasks clause are mutually exclusive and may
10460   // not appear on the same taskloop directive.
10461   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10462     return StmtError();
10463   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10464   // If a reduction clause is present on the taskloop directive, the nogroup
10465   // clause must not be specified.
10466   if (checkReductionClauseWithNogroup(*this, Clauses))
10467     return StmtError();
10468   if (checkSimdlenSafelenSpecified(*this, Clauses))
10469     return StmtError();
10470 
10471   setFunctionHasBranchProtectedScope();
10472   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
10473                                           NestedLoopCount, Clauses, AStmt, B);
10474 }
10475 
10476 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
10477     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10478     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10479   if (!AStmt)
10480     return StmtError();
10481 
10482   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10483   OMPLoopDirective::HelperExprs B;
10484   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10485   // define the nested loops number.
10486   unsigned NestedLoopCount =
10487       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
10488                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10489                       VarsWithImplicitDSA, B);
10490   if (NestedLoopCount == 0)
10491     return StmtError();
10492 
10493   assert((CurContext->isDependentContext() || B.builtAll()) &&
10494          "omp for loop exprs were not built");
10495 
10496   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10497   // The grainsize clause and num_tasks clause are mutually exclusive and may
10498   // not appear on the same taskloop directive.
10499   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10500     return StmtError();
10501   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10502   // If a reduction clause is present on the taskloop directive, the nogroup
10503   // clause must not be specified.
10504   if (checkReductionClauseWithNogroup(*this, Clauses))
10505     return StmtError();
10506 
10507   setFunctionHasBranchProtectedScope();
10508   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10509                                             NestedLoopCount, Clauses, AStmt, B,
10510                                             DSAStack->isCancelRegion());
10511 }
10512 
10513 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
10514     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10515     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10516   if (!AStmt)
10517     return StmtError();
10518 
10519   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10520   OMPLoopDirective::HelperExprs B;
10521   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10522   // define the nested loops number.
10523   unsigned NestedLoopCount =
10524       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10525                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10526                       VarsWithImplicitDSA, B);
10527   if (NestedLoopCount == 0)
10528     return StmtError();
10529 
10530   assert((CurContext->isDependentContext() || B.builtAll()) &&
10531          "omp for loop exprs were not built");
10532 
10533   if (!CurContext->isDependentContext()) {
10534     // Finalize the clauses that need pre-built expressions for CodeGen.
10535     for (OMPClause *C : Clauses) {
10536       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10537         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10538                                      B.NumIterations, *this, CurScope,
10539                                      DSAStack))
10540           return StmtError();
10541     }
10542   }
10543 
10544   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10545   // The grainsize clause and num_tasks clause are mutually exclusive and may
10546   // not appear on the same taskloop directive.
10547   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10548     return StmtError();
10549   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10550   // If a reduction clause is present on the taskloop directive, the nogroup
10551   // clause must not be specified.
10552   if (checkReductionClauseWithNogroup(*this, Clauses))
10553     return StmtError();
10554   if (checkSimdlenSafelenSpecified(*this, Clauses))
10555     return StmtError();
10556 
10557   setFunctionHasBranchProtectedScope();
10558   return OMPMasterTaskLoopSimdDirective::Create(
10559       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10560 }
10561 
10562 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
10563     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10564     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10565   if (!AStmt)
10566     return StmtError();
10567 
10568   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10569   auto *CS = cast<CapturedStmt>(AStmt);
10570   // 1.2.2 OpenMP Language Terminology
10571   // Structured block - An executable statement with a single entry at the
10572   // top and a single exit at the bottom.
10573   // The point of exit cannot be a branch out of the structured block.
10574   // longjmp() and throw() must not violate the entry/exit criteria.
10575   CS->getCapturedDecl()->setNothrow();
10576   for (int ThisCaptureLevel =
10577            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
10578        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10579     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10580     // 1.2.2 OpenMP Language Terminology
10581     // Structured block - An executable statement with a single entry at the
10582     // top and a single exit at the bottom.
10583     // The point of exit cannot be a branch out of the structured block.
10584     // longjmp() and throw() must not violate the entry/exit criteria.
10585     CS->getCapturedDecl()->setNothrow();
10586   }
10587 
10588   OMPLoopDirective::HelperExprs B;
10589   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10590   // define the nested loops number.
10591   unsigned NestedLoopCount = checkOpenMPLoop(
10592       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
10593       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10594       VarsWithImplicitDSA, B);
10595   if (NestedLoopCount == 0)
10596     return StmtError();
10597 
10598   assert((CurContext->isDependentContext() || B.builtAll()) &&
10599          "omp for loop exprs were not built");
10600 
10601   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10602   // The grainsize clause and num_tasks clause are mutually exclusive and may
10603   // not appear on the same taskloop directive.
10604   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10605     return StmtError();
10606   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10607   // If a reduction clause is present on the taskloop directive, the nogroup
10608   // clause must not be specified.
10609   if (checkReductionClauseWithNogroup(*this, Clauses))
10610     return StmtError();
10611 
10612   setFunctionHasBranchProtectedScope();
10613   return OMPParallelMasterTaskLoopDirective::Create(
10614       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10615       DSAStack->isCancelRegion());
10616 }
10617 
10618 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10619     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10620     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10621   if (!AStmt)
10622     return StmtError();
10623 
10624   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10625   auto *CS = cast<CapturedStmt>(AStmt);
10626   // 1.2.2 OpenMP Language Terminology
10627   // Structured block - An executable statement with a single entry at the
10628   // top and a single exit at the bottom.
10629   // The point of exit cannot be a branch out of the structured block.
10630   // longjmp() and throw() must not violate the entry/exit criteria.
10631   CS->getCapturedDecl()->setNothrow();
10632   for (int ThisCaptureLevel =
10633            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
10634        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10635     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10636     // 1.2.2 OpenMP Language Terminology
10637     // Structured block - An executable statement with a single entry at the
10638     // top and a single exit at the bottom.
10639     // The point of exit cannot be a branch out of the structured block.
10640     // longjmp() and throw() must not violate the entry/exit criteria.
10641     CS->getCapturedDecl()->setNothrow();
10642   }
10643 
10644   OMPLoopDirective::HelperExprs B;
10645   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10646   // define the nested loops number.
10647   unsigned NestedLoopCount = checkOpenMPLoop(
10648       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10649       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10650       VarsWithImplicitDSA, B);
10651   if (NestedLoopCount == 0)
10652     return StmtError();
10653 
10654   assert((CurContext->isDependentContext() || B.builtAll()) &&
10655          "omp for loop exprs were not built");
10656 
10657   if (!CurContext->isDependentContext()) {
10658     // Finalize the clauses that need pre-built expressions for CodeGen.
10659     for (OMPClause *C : Clauses) {
10660       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10661         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10662                                      B.NumIterations, *this, CurScope,
10663                                      DSAStack))
10664           return StmtError();
10665     }
10666   }
10667 
10668   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10669   // The grainsize clause and num_tasks clause are mutually exclusive and may
10670   // not appear on the same taskloop directive.
10671   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10672     return StmtError();
10673   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10674   // If a reduction clause is present on the taskloop directive, the nogroup
10675   // clause must not be specified.
10676   if (checkReductionClauseWithNogroup(*this, Clauses))
10677     return StmtError();
10678   if (checkSimdlenSafelenSpecified(*this, Clauses))
10679     return StmtError();
10680 
10681   setFunctionHasBranchProtectedScope();
10682   return OMPParallelMasterTaskLoopSimdDirective::Create(
10683       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10684 }
10685 
10686 StmtResult Sema::ActOnOpenMPDistributeDirective(
10687     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10688     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10689   if (!AStmt)
10690     return StmtError();
10691 
10692   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10693   OMPLoopDirective::HelperExprs B;
10694   // In presence of clause 'collapse' with number of loops, it will
10695   // define the nested loops number.
10696   unsigned NestedLoopCount =
10697       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
10698                       nullptr /*ordered not a clause on distribute*/, AStmt,
10699                       *this, *DSAStack, VarsWithImplicitDSA, B);
10700   if (NestedLoopCount == 0)
10701     return StmtError();
10702 
10703   assert((CurContext->isDependentContext() || B.builtAll()) &&
10704          "omp for loop exprs were not built");
10705 
10706   setFunctionHasBranchProtectedScope();
10707   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
10708                                         NestedLoopCount, Clauses, AStmt, B);
10709 }
10710 
10711 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10712     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10713     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10714   if (!AStmt)
10715     return StmtError();
10716 
10717   auto *CS = cast<CapturedStmt>(AStmt);
10718   // 1.2.2 OpenMP Language Terminology
10719   // Structured block - An executable statement with a single entry at the
10720   // top and a single exit at the bottom.
10721   // The point of exit cannot be a branch out of the structured block.
10722   // longjmp() and throw() must not violate the entry/exit criteria.
10723   CS->getCapturedDecl()->setNothrow();
10724   for (int ThisCaptureLevel =
10725            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10726        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10727     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10728     // 1.2.2 OpenMP Language Terminology
10729     // Structured block - An executable statement with a single entry at the
10730     // top and a single exit at the bottom.
10731     // The point of exit cannot be a branch out of the structured block.
10732     // longjmp() and throw() must not violate the entry/exit criteria.
10733     CS->getCapturedDecl()->setNothrow();
10734   }
10735 
10736   OMPLoopDirective::HelperExprs B;
10737   // In presence of clause 'collapse' with number of loops, it will
10738   // define the nested loops number.
10739   unsigned NestedLoopCount = checkOpenMPLoop(
10740       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10741       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
10742       VarsWithImplicitDSA, B);
10743   if (NestedLoopCount == 0)
10744     return StmtError();
10745 
10746   assert((CurContext->isDependentContext() || B.builtAll()) &&
10747          "omp for loop exprs were not built");
10748 
10749   setFunctionHasBranchProtectedScope();
10750   return OMPDistributeParallelForDirective::Create(
10751       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10752       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10753 }
10754 
10755 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10756     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10757     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10758   if (!AStmt)
10759     return StmtError();
10760 
10761   auto *CS = cast<CapturedStmt>(AStmt);
10762   // 1.2.2 OpenMP Language Terminology
10763   // Structured block - An executable statement with a single entry at the
10764   // top and a single exit at the bottom.
10765   // The point of exit cannot be a branch out of the structured block.
10766   // longjmp() and throw() must not violate the entry/exit criteria.
10767   CS->getCapturedDecl()->setNothrow();
10768   for (int ThisCaptureLevel =
10769            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10770        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10771     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10772     // 1.2.2 OpenMP Language Terminology
10773     // Structured block - An executable statement with a single entry at the
10774     // top and a single exit at the bottom.
10775     // The point of exit cannot be a branch out of the structured block.
10776     // longjmp() and throw() must not violate the entry/exit criteria.
10777     CS->getCapturedDecl()->setNothrow();
10778   }
10779 
10780   OMPLoopDirective::HelperExprs B;
10781   // In presence of clause 'collapse' with number of loops, it will
10782   // define the nested loops number.
10783   unsigned NestedLoopCount = checkOpenMPLoop(
10784       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
10785       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
10786       VarsWithImplicitDSA, B);
10787   if (NestedLoopCount == 0)
10788     return StmtError();
10789 
10790   assert((CurContext->isDependentContext() || B.builtAll()) &&
10791          "omp for loop exprs were not built");
10792 
10793   if (!CurContext->isDependentContext()) {
10794     // Finalize the clauses that need pre-built expressions for CodeGen.
10795     for (OMPClause *C : Clauses) {
10796       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10797         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10798                                      B.NumIterations, *this, CurScope,
10799                                      DSAStack))
10800           return StmtError();
10801     }
10802   }
10803 
10804   if (checkSimdlenSafelenSpecified(*this, Clauses))
10805     return StmtError();
10806 
10807   setFunctionHasBranchProtectedScope();
10808   return OMPDistributeParallelForSimdDirective::Create(
10809       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10810 }
10811 
10812 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10813     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10814     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10815   if (!AStmt)
10816     return StmtError();
10817 
10818   auto *CS = cast<CapturedStmt>(AStmt);
10819   // 1.2.2 OpenMP Language Terminology
10820   // Structured block - An executable statement with a single entry at the
10821   // top and a single exit at the bottom.
10822   // The point of exit cannot be a branch out of the structured block.
10823   // longjmp() and throw() must not violate the entry/exit criteria.
10824   CS->getCapturedDecl()->setNothrow();
10825   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10826        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10827     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10828     // 1.2.2 OpenMP Language Terminology
10829     // Structured block - An executable statement with a single entry at the
10830     // top and a single exit at the bottom.
10831     // The point of exit cannot be a branch out of the structured block.
10832     // longjmp() and throw() must not violate the entry/exit criteria.
10833     CS->getCapturedDecl()->setNothrow();
10834   }
10835 
10836   OMPLoopDirective::HelperExprs B;
10837   // In presence of clause 'collapse' with number of loops, it will
10838   // define the nested loops number.
10839   unsigned NestedLoopCount =
10840       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
10841                       nullptr /*ordered not a clause on distribute*/, CS, *this,
10842                       *DSAStack, VarsWithImplicitDSA, B);
10843   if (NestedLoopCount == 0)
10844     return StmtError();
10845 
10846   assert((CurContext->isDependentContext() || B.builtAll()) &&
10847          "omp for loop exprs were not built");
10848 
10849   if (!CurContext->isDependentContext()) {
10850     // Finalize the clauses that need pre-built expressions for CodeGen.
10851     for (OMPClause *C : Clauses) {
10852       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10853         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10854                                      B.NumIterations, *this, CurScope,
10855                                      DSAStack))
10856           return StmtError();
10857     }
10858   }
10859 
10860   if (checkSimdlenSafelenSpecified(*this, Clauses))
10861     return StmtError();
10862 
10863   setFunctionHasBranchProtectedScope();
10864   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10865                                             NestedLoopCount, Clauses, AStmt, B);
10866 }
10867 
10868 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10869     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10870     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10871   if (!AStmt)
10872     return StmtError();
10873 
10874   auto *CS = cast<CapturedStmt>(AStmt);
10875   // 1.2.2 OpenMP Language Terminology
10876   // Structured block - An executable statement with a single entry at the
10877   // top and a single exit at the bottom.
10878   // The point of exit cannot be a branch out of the structured block.
10879   // longjmp() and throw() must not violate the entry/exit criteria.
10880   CS->getCapturedDecl()->setNothrow();
10881   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10882        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10883     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10884     // 1.2.2 OpenMP Language Terminology
10885     // Structured block - An executable statement with a single entry at the
10886     // top and a single exit at the bottom.
10887     // The point of exit cannot be a branch out of the structured block.
10888     // longjmp() and throw() must not violate the entry/exit criteria.
10889     CS->getCapturedDecl()->setNothrow();
10890   }
10891 
10892   OMPLoopDirective::HelperExprs B;
10893   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10894   // define the nested loops number.
10895   unsigned NestedLoopCount = checkOpenMPLoop(
10896       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
10897       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
10898       VarsWithImplicitDSA, B);
10899   if (NestedLoopCount == 0)
10900     return StmtError();
10901 
10902   assert((CurContext->isDependentContext() || B.builtAll()) &&
10903          "omp target parallel for simd loop exprs were not built");
10904 
10905   if (!CurContext->isDependentContext()) {
10906     // Finalize the clauses that need pre-built expressions for CodeGen.
10907     for (OMPClause *C : Clauses) {
10908       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10909         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10910                                      B.NumIterations, *this, CurScope,
10911                                      DSAStack))
10912           return StmtError();
10913     }
10914   }
10915   if (checkSimdlenSafelenSpecified(*this, Clauses))
10916     return StmtError();
10917 
10918   setFunctionHasBranchProtectedScope();
10919   return OMPTargetParallelForSimdDirective::Create(
10920       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10921 }
10922 
10923 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10924     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10925     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10926   if (!AStmt)
10927     return StmtError();
10928 
10929   auto *CS = cast<CapturedStmt>(AStmt);
10930   // 1.2.2 OpenMP Language Terminology
10931   // Structured block - An executable statement with a single entry at the
10932   // top and a single exit at the bottom.
10933   // The point of exit cannot be a branch out of the structured block.
10934   // longjmp() and throw() must not violate the entry/exit criteria.
10935   CS->getCapturedDecl()->setNothrow();
10936   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10937        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10938     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10939     // 1.2.2 OpenMP Language Terminology
10940     // Structured block - An executable statement with a single entry at the
10941     // top and a single exit at the bottom.
10942     // The point of exit cannot be a branch out of the structured block.
10943     // longjmp() and throw() must not violate the entry/exit criteria.
10944     CS->getCapturedDecl()->setNothrow();
10945   }
10946 
10947   OMPLoopDirective::HelperExprs B;
10948   // In presence of clause 'collapse' with number of loops, it will define the
10949   // nested loops number.
10950   unsigned NestedLoopCount =
10951       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
10952                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
10953                       VarsWithImplicitDSA, B);
10954   if (NestedLoopCount == 0)
10955     return StmtError();
10956 
10957   assert((CurContext->isDependentContext() || B.builtAll()) &&
10958          "omp target simd loop exprs were not built");
10959 
10960   if (!CurContext->isDependentContext()) {
10961     // Finalize the clauses that need pre-built expressions for CodeGen.
10962     for (OMPClause *C : Clauses) {
10963       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10964         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10965                                      B.NumIterations, *this, CurScope,
10966                                      DSAStack))
10967           return StmtError();
10968     }
10969   }
10970 
10971   if (checkSimdlenSafelenSpecified(*this, Clauses))
10972     return StmtError();
10973 
10974   setFunctionHasBranchProtectedScope();
10975   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10976                                         NestedLoopCount, Clauses, AStmt, B);
10977 }
10978 
10979 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10980     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10981     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10982   if (!AStmt)
10983     return StmtError();
10984 
10985   auto *CS = cast<CapturedStmt>(AStmt);
10986   // 1.2.2 OpenMP Language Terminology
10987   // Structured block - An executable statement with a single entry at the
10988   // top and a single exit at the bottom.
10989   // The point of exit cannot be a branch out of the structured block.
10990   // longjmp() and throw() must not violate the entry/exit criteria.
10991   CS->getCapturedDecl()->setNothrow();
10992   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10993        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10994     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10995     // 1.2.2 OpenMP Language Terminology
10996     // Structured block - An executable statement with a single entry at the
10997     // top and a single exit at the bottom.
10998     // The point of exit cannot be a branch out of the structured block.
10999     // longjmp() and throw() must not violate the entry/exit criteria.
11000     CS->getCapturedDecl()->setNothrow();
11001   }
11002 
11003   OMPLoopDirective::HelperExprs B;
11004   // In presence of clause 'collapse' with number of loops, it will
11005   // define the nested loops number.
11006   unsigned NestedLoopCount =
11007       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
11008                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11009                       *DSAStack, VarsWithImplicitDSA, B);
11010   if (NestedLoopCount == 0)
11011     return StmtError();
11012 
11013   assert((CurContext->isDependentContext() || B.builtAll()) &&
11014          "omp teams distribute loop exprs were not built");
11015 
11016   setFunctionHasBranchProtectedScope();
11017 
11018   DSAStack->setParentTeamsRegionLoc(StartLoc);
11019 
11020   return OMPTeamsDistributeDirective::Create(
11021       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11022 }
11023 
11024 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
11025     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11026     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11027   if (!AStmt)
11028     return StmtError();
11029 
11030   auto *CS = cast<CapturedStmt>(AStmt);
11031   // 1.2.2 OpenMP Language Terminology
11032   // Structured block - An executable statement with a single entry at the
11033   // top and a single exit at the bottom.
11034   // The point of exit cannot be a branch out of the structured block.
11035   // longjmp() and throw() must not violate the entry/exit criteria.
11036   CS->getCapturedDecl()->setNothrow();
11037   for (int ThisCaptureLevel =
11038            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
11039        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11040     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11041     // 1.2.2 OpenMP Language Terminology
11042     // Structured block - An executable statement with a single entry at the
11043     // top and a single exit at the bottom.
11044     // The point of exit cannot be a branch out of the structured block.
11045     // longjmp() and throw() must not violate the entry/exit criteria.
11046     CS->getCapturedDecl()->setNothrow();
11047   }
11048 
11049   OMPLoopDirective::HelperExprs B;
11050   // In presence of clause 'collapse' with number of loops, it will
11051   // define the nested loops number.
11052   unsigned NestedLoopCount = checkOpenMPLoop(
11053       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11054       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11055       VarsWithImplicitDSA, B);
11056 
11057   if (NestedLoopCount == 0)
11058     return StmtError();
11059 
11060   assert((CurContext->isDependentContext() || B.builtAll()) &&
11061          "omp teams distribute simd loop exprs were not built");
11062 
11063   if (!CurContext->isDependentContext()) {
11064     // Finalize the clauses that need pre-built expressions for CodeGen.
11065     for (OMPClause *C : Clauses) {
11066       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11067         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11068                                      B.NumIterations, *this, CurScope,
11069                                      DSAStack))
11070           return StmtError();
11071     }
11072   }
11073 
11074   if (checkSimdlenSafelenSpecified(*this, Clauses))
11075     return StmtError();
11076 
11077   setFunctionHasBranchProtectedScope();
11078 
11079   DSAStack->setParentTeamsRegionLoc(StartLoc);
11080 
11081   return OMPTeamsDistributeSimdDirective::Create(
11082       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11083 }
11084 
11085 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11086     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11087     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11088   if (!AStmt)
11089     return StmtError();
11090 
11091   auto *CS = cast<CapturedStmt>(AStmt);
11092   // 1.2.2 OpenMP Language Terminology
11093   // Structured block - An executable statement with a single entry at the
11094   // top and a single exit at the bottom.
11095   // The point of exit cannot be a branch out of the structured block.
11096   // longjmp() and throw() must not violate the entry/exit criteria.
11097   CS->getCapturedDecl()->setNothrow();
11098 
11099   for (int ThisCaptureLevel =
11100            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
11101        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11102     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11103     // 1.2.2 OpenMP Language Terminology
11104     // Structured block - An executable statement with a single entry at the
11105     // top and a single exit at the bottom.
11106     // The point of exit cannot be a branch out of the structured block.
11107     // longjmp() and throw() must not violate the entry/exit criteria.
11108     CS->getCapturedDecl()->setNothrow();
11109   }
11110 
11111   OMPLoopDirective::HelperExprs B;
11112   // In presence of clause 'collapse' with number of loops, it will
11113   // define the nested loops number.
11114   unsigned NestedLoopCount = checkOpenMPLoop(
11115       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11116       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11117       VarsWithImplicitDSA, B);
11118 
11119   if (NestedLoopCount == 0)
11120     return StmtError();
11121 
11122   assert((CurContext->isDependentContext() || B.builtAll()) &&
11123          "omp for loop exprs were not built");
11124 
11125   if (!CurContext->isDependentContext()) {
11126     // Finalize the clauses that need pre-built expressions for CodeGen.
11127     for (OMPClause *C : Clauses) {
11128       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11129         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11130                                      B.NumIterations, *this, CurScope,
11131                                      DSAStack))
11132           return StmtError();
11133     }
11134   }
11135 
11136   if (checkSimdlenSafelenSpecified(*this, Clauses))
11137     return StmtError();
11138 
11139   setFunctionHasBranchProtectedScope();
11140 
11141   DSAStack->setParentTeamsRegionLoc(StartLoc);
11142 
11143   return OMPTeamsDistributeParallelForSimdDirective::Create(
11144       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11145 }
11146 
11147 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
11148     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11149     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11150   if (!AStmt)
11151     return StmtError();
11152 
11153   auto *CS = cast<CapturedStmt>(AStmt);
11154   // 1.2.2 OpenMP Language Terminology
11155   // Structured block - An executable statement with a single entry at the
11156   // top and a single exit at the bottom.
11157   // The point of exit cannot be a branch out of the structured block.
11158   // longjmp() and throw() must not violate the entry/exit criteria.
11159   CS->getCapturedDecl()->setNothrow();
11160 
11161   for (int ThisCaptureLevel =
11162            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
11163        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11164     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11165     // 1.2.2 OpenMP Language Terminology
11166     // Structured block - An executable statement with a single entry at the
11167     // top and a single exit at the bottom.
11168     // The point of exit cannot be a branch out of the structured block.
11169     // longjmp() and throw() must not violate the entry/exit criteria.
11170     CS->getCapturedDecl()->setNothrow();
11171   }
11172 
11173   OMPLoopDirective::HelperExprs B;
11174   // In presence of clause 'collapse' with number of loops, it will
11175   // define the nested loops number.
11176   unsigned NestedLoopCount = checkOpenMPLoop(
11177       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11178       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11179       VarsWithImplicitDSA, B);
11180 
11181   if (NestedLoopCount == 0)
11182     return StmtError();
11183 
11184   assert((CurContext->isDependentContext() || B.builtAll()) &&
11185          "omp for loop exprs were not built");
11186 
11187   setFunctionHasBranchProtectedScope();
11188 
11189   DSAStack->setParentTeamsRegionLoc(StartLoc);
11190 
11191   return OMPTeamsDistributeParallelForDirective::Create(
11192       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11193       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11194 }
11195 
11196 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11197                                                  Stmt *AStmt,
11198                                                  SourceLocation StartLoc,
11199                                                  SourceLocation EndLoc) {
11200   if (!AStmt)
11201     return StmtError();
11202 
11203   auto *CS = cast<CapturedStmt>(AStmt);
11204   // 1.2.2 OpenMP Language Terminology
11205   // Structured block - An executable statement with a single entry at the
11206   // top and a single exit at the bottom.
11207   // The point of exit cannot be a branch out of the structured block.
11208   // longjmp() and throw() must not violate the entry/exit criteria.
11209   CS->getCapturedDecl()->setNothrow();
11210 
11211   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
11212        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11213     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11214     // 1.2.2 OpenMP Language Terminology
11215     // Structured block - An executable statement with a single entry at the
11216     // top and a single exit at the bottom.
11217     // The point of exit cannot be a branch out of the structured block.
11218     // longjmp() and throw() must not violate the entry/exit criteria.
11219     CS->getCapturedDecl()->setNothrow();
11220   }
11221   setFunctionHasBranchProtectedScope();
11222 
11223   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
11224                                          AStmt);
11225 }
11226 
11227 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
11228     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11229     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11230   if (!AStmt)
11231     return StmtError();
11232 
11233   auto *CS = cast<CapturedStmt>(AStmt);
11234   // 1.2.2 OpenMP Language Terminology
11235   // Structured block - An executable statement with a single entry at the
11236   // top and a single exit at the bottom.
11237   // The point of exit cannot be a branch out of the structured block.
11238   // longjmp() and throw() must not violate the entry/exit criteria.
11239   CS->getCapturedDecl()->setNothrow();
11240   for (int ThisCaptureLevel =
11241            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
11242        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11243     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11244     // 1.2.2 OpenMP Language Terminology
11245     // Structured block - An executable statement with a single entry at the
11246     // top and a single exit at the bottom.
11247     // The point of exit cannot be a branch out of the structured block.
11248     // longjmp() and throw() must not violate the entry/exit criteria.
11249     CS->getCapturedDecl()->setNothrow();
11250   }
11251 
11252   OMPLoopDirective::HelperExprs B;
11253   // In presence of clause 'collapse' with number of loops, it will
11254   // define the nested loops number.
11255   unsigned NestedLoopCount = checkOpenMPLoop(
11256       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
11257       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11258       VarsWithImplicitDSA, B);
11259   if (NestedLoopCount == 0)
11260     return StmtError();
11261 
11262   assert((CurContext->isDependentContext() || B.builtAll()) &&
11263          "omp target teams distribute loop exprs were not built");
11264 
11265   setFunctionHasBranchProtectedScope();
11266   return OMPTargetTeamsDistributeDirective::Create(
11267       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11268 }
11269 
11270 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11271     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11272     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11273   if (!AStmt)
11274     return StmtError();
11275 
11276   auto *CS = cast<CapturedStmt>(AStmt);
11277   // 1.2.2 OpenMP Language Terminology
11278   // Structured block - An executable statement with a single entry at the
11279   // top and a single exit at the bottom.
11280   // The point of exit cannot be a branch out of the structured block.
11281   // longjmp() and throw() must not violate the entry/exit criteria.
11282   CS->getCapturedDecl()->setNothrow();
11283   for (int ThisCaptureLevel =
11284            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
11285        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11286     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11287     // 1.2.2 OpenMP Language Terminology
11288     // Structured block - An executable statement with a single entry at the
11289     // top and a single exit at the bottom.
11290     // The point of exit cannot be a branch out of the structured block.
11291     // longjmp() and throw() must not violate the entry/exit criteria.
11292     CS->getCapturedDecl()->setNothrow();
11293   }
11294 
11295   OMPLoopDirective::HelperExprs B;
11296   // In presence of clause 'collapse' with number of loops, it will
11297   // define the nested loops number.
11298   unsigned NestedLoopCount = checkOpenMPLoop(
11299       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11300       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11301       VarsWithImplicitDSA, B);
11302   if (NestedLoopCount == 0)
11303     return StmtError();
11304 
11305   assert((CurContext->isDependentContext() || B.builtAll()) &&
11306          "omp target teams distribute parallel for loop exprs were not built");
11307 
11308   if (!CurContext->isDependentContext()) {
11309     // Finalize the clauses that need pre-built expressions for CodeGen.
11310     for (OMPClause *C : Clauses) {
11311       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11312         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11313                                      B.NumIterations, *this, CurScope,
11314                                      DSAStack))
11315           return StmtError();
11316     }
11317   }
11318 
11319   setFunctionHasBranchProtectedScope();
11320   return OMPTargetTeamsDistributeParallelForDirective::Create(
11321       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11322       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11323 }
11324 
11325 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11326     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11327     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11328   if (!AStmt)
11329     return StmtError();
11330 
11331   auto *CS = cast<CapturedStmt>(AStmt);
11332   // 1.2.2 OpenMP Language Terminology
11333   // Structured block - An executable statement with a single entry at the
11334   // top and a single exit at the bottom.
11335   // The point of exit cannot be a branch out of the structured block.
11336   // longjmp() and throw() must not violate the entry/exit criteria.
11337   CS->getCapturedDecl()->setNothrow();
11338   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
11339            OMPD_target_teams_distribute_parallel_for_simd);
11340        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11341     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11342     // 1.2.2 OpenMP Language Terminology
11343     // Structured block - An executable statement with a single entry at the
11344     // top and a single exit at the bottom.
11345     // The point of exit cannot be a branch out of the structured block.
11346     // longjmp() and throw() must not violate the entry/exit criteria.
11347     CS->getCapturedDecl()->setNothrow();
11348   }
11349 
11350   OMPLoopDirective::HelperExprs B;
11351   // In presence of clause 'collapse' with number of loops, it will
11352   // define the nested loops number.
11353   unsigned NestedLoopCount =
11354       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
11355                       getCollapseNumberExpr(Clauses),
11356                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11357                       *DSAStack, VarsWithImplicitDSA, B);
11358   if (NestedLoopCount == 0)
11359     return StmtError();
11360 
11361   assert((CurContext->isDependentContext() || B.builtAll()) &&
11362          "omp target teams distribute parallel for simd loop exprs were not "
11363          "built");
11364 
11365   if (!CurContext->isDependentContext()) {
11366     // Finalize the clauses that need pre-built expressions for CodeGen.
11367     for (OMPClause *C : Clauses) {
11368       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11369         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11370                                      B.NumIterations, *this, CurScope,
11371                                      DSAStack))
11372           return StmtError();
11373     }
11374   }
11375 
11376   if (checkSimdlenSafelenSpecified(*this, Clauses))
11377     return StmtError();
11378 
11379   setFunctionHasBranchProtectedScope();
11380   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
11381       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11382 }
11383 
11384 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
11385     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11386     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11387   if (!AStmt)
11388     return StmtError();
11389 
11390   auto *CS = cast<CapturedStmt>(AStmt);
11391   // 1.2.2 OpenMP Language Terminology
11392   // Structured block - An executable statement with a single entry at the
11393   // top and a single exit at the bottom.
11394   // The point of exit cannot be a branch out of the structured block.
11395   // longjmp() and throw() must not violate the entry/exit criteria.
11396   CS->getCapturedDecl()->setNothrow();
11397   for (int ThisCaptureLevel =
11398            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
11399        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11400     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11401     // 1.2.2 OpenMP Language Terminology
11402     // Structured block - An executable statement with a single entry at the
11403     // top and a single exit at the bottom.
11404     // The point of exit cannot be a branch out of the structured block.
11405     // longjmp() and throw() must not violate the entry/exit criteria.
11406     CS->getCapturedDecl()->setNothrow();
11407   }
11408 
11409   OMPLoopDirective::HelperExprs B;
11410   // In presence of clause 'collapse' with number of loops, it will
11411   // define the nested loops number.
11412   unsigned NestedLoopCount = checkOpenMPLoop(
11413       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11414       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11415       VarsWithImplicitDSA, B);
11416   if (NestedLoopCount == 0)
11417     return StmtError();
11418 
11419   assert((CurContext->isDependentContext() || B.builtAll()) &&
11420          "omp target teams distribute simd loop exprs were not built");
11421 
11422   if (!CurContext->isDependentContext()) {
11423     // Finalize the clauses that need pre-built expressions for CodeGen.
11424     for (OMPClause *C : Clauses) {
11425       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11426         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11427                                      B.NumIterations, *this, CurScope,
11428                                      DSAStack))
11429           return StmtError();
11430     }
11431   }
11432 
11433   if (checkSimdlenSafelenSpecified(*this, Clauses))
11434     return StmtError();
11435 
11436   setFunctionHasBranchProtectedScope();
11437   return OMPTargetTeamsDistributeSimdDirective::Create(
11438       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11439 }
11440 
11441 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
11442                                              SourceLocation StartLoc,
11443                                              SourceLocation LParenLoc,
11444                                              SourceLocation EndLoc) {
11445   OMPClause *Res = nullptr;
11446   switch (Kind) {
11447   case OMPC_final:
11448     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
11449     break;
11450   case OMPC_num_threads:
11451     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
11452     break;
11453   case OMPC_safelen:
11454     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
11455     break;
11456   case OMPC_simdlen:
11457     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
11458     break;
11459   case OMPC_allocator:
11460     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
11461     break;
11462   case OMPC_collapse:
11463     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
11464     break;
11465   case OMPC_ordered:
11466     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
11467     break;
11468   case OMPC_num_teams:
11469     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
11470     break;
11471   case OMPC_thread_limit:
11472     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
11473     break;
11474   case OMPC_priority:
11475     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
11476     break;
11477   case OMPC_grainsize:
11478     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
11479     break;
11480   case OMPC_num_tasks:
11481     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
11482     break;
11483   case OMPC_hint:
11484     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
11485     break;
11486   case OMPC_depobj:
11487     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
11488     break;
11489   case OMPC_detach:
11490     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
11491     break;
11492   case OMPC_device:
11493   case OMPC_if:
11494   case OMPC_default:
11495   case OMPC_proc_bind:
11496   case OMPC_schedule:
11497   case OMPC_private:
11498   case OMPC_firstprivate:
11499   case OMPC_lastprivate:
11500   case OMPC_shared:
11501   case OMPC_reduction:
11502   case OMPC_task_reduction:
11503   case OMPC_in_reduction:
11504   case OMPC_linear:
11505   case OMPC_aligned:
11506   case OMPC_copyin:
11507   case OMPC_copyprivate:
11508   case OMPC_nowait:
11509   case OMPC_untied:
11510   case OMPC_mergeable:
11511   case OMPC_threadprivate:
11512   case OMPC_allocate:
11513   case OMPC_flush:
11514   case OMPC_read:
11515   case OMPC_write:
11516   case OMPC_update:
11517   case OMPC_capture:
11518   case OMPC_seq_cst:
11519   case OMPC_acq_rel:
11520   case OMPC_acquire:
11521   case OMPC_release:
11522   case OMPC_relaxed:
11523   case OMPC_depend:
11524   case OMPC_threads:
11525   case OMPC_simd:
11526   case OMPC_map:
11527   case OMPC_nogroup:
11528   case OMPC_dist_schedule:
11529   case OMPC_defaultmap:
11530   case OMPC_unknown:
11531   case OMPC_uniform:
11532   case OMPC_to:
11533   case OMPC_from:
11534   case OMPC_use_device_ptr:
11535   case OMPC_use_device_addr:
11536   case OMPC_is_device_ptr:
11537   case OMPC_unified_address:
11538   case OMPC_unified_shared_memory:
11539   case OMPC_reverse_offload:
11540   case OMPC_dynamic_allocators:
11541   case OMPC_atomic_default_mem_order:
11542   case OMPC_device_type:
11543   case OMPC_match:
11544   case OMPC_nontemporal:
11545   case OMPC_order:
11546   case OMPC_destroy:
11547   case OMPC_inclusive:
11548   case OMPC_exclusive:
11549   case OMPC_uses_allocators:
11550   case OMPC_affinity:
11551     llvm_unreachable("Clause is not allowed.");
11552   }
11553   return Res;
11554 }
11555 
11556 // An OpenMP directive such as 'target parallel' has two captured regions:
11557 // for the 'target' and 'parallel' respectively.  This function returns
11558 // the region in which to capture expressions associated with a clause.
11559 // A return value of OMPD_unknown signifies that the expression should not
11560 // be captured.
11561 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
11562     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
11563     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
11564   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11565   switch (CKind) {
11566   case OMPC_if:
11567     switch (DKind) {
11568     case OMPD_target_parallel_for_simd:
11569       if (OpenMPVersion >= 50 &&
11570           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11571         CaptureRegion = OMPD_parallel;
11572         break;
11573       }
11574       LLVM_FALLTHROUGH;
11575     case OMPD_target_parallel:
11576     case OMPD_target_parallel_for:
11577       // If this clause applies to the nested 'parallel' region, capture within
11578       // the 'target' region, otherwise do not capture.
11579       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11580         CaptureRegion = OMPD_target;
11581       break;
11582     case OMPD_target_teams_distribute_parallel_for_simd:
11583       if (OpenMPVersion >= 50 &&
11584           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11585         CaptureRegion = OMPD_parallel;
11586         break;
11587       }
11588       LLVM_FALLTHROUGH;
11589     case OMPD_target_teams_distribute_parallel_for:
11590       // If this clause applies to the nested 'parallel' region, capture within
11591       // the 'teams' region, otherwise do not capture.
11592       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11593         CaptureRegion = OMPD_teams;
11594       break;
11595     case OMPD_teams_distribute_parallel_for_simd:
11596       if (OpenMPVersion >= 50 &&
11597           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11598         CaptureRegion = OMPD_parallel;
11599         break;
11600       }
11601       LLVM_FALLTHROUGH;
11602     case OMPD_teams_distribute_parallel_for:
11603       CaptureRegion = OMPD_teams;
11604       break;
11605     case OMPD_target_update:
11606     case OMPD_target_enter_data:
11607     case OMPD_target_exit_data:
11608       CaptureRegion = OMPD_task;
11609       break;
11610     case OMPD_parallel_master_taskloop:
11611       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
11612         CaptureRegion = OMPD_parallel;
11613       break;
11614     case OMPD_parallel_master_taskloop_simd:
11615       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
11616           NameModifier == OMPD_taskloop) {
11617         CaptureRegion = OMPD_parallel;
11618         break;
11619       }
11620       if (OpenMPVersion <= 45)
11621         break;
11622       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11623         CaptureRegion = OMPD_taskloop;
11624       break;
11625     case OMPD_parallel_for_simd:
11626       if (OpenMPVersion <= 45)
11627         break;
11628       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11629         CaptureRegion = OMPD_parallel;
11630       break;
11631     case OMPD_taskloop_simd:
11632     case OMPD_master_taskloop_simd:
11633       if (OpenMPVersion <= 45)
11634         break;
11635       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11636         CaptureRegion = OMPD_taskloop;
11637       break;
11638     case OMPD_distribute_parallel_for_simd:
11639       if (OpenMPVersion <= 45)
11640         break;
11641       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11642         CaptureRegion = OMPD_parallel;
11643       break;
11644     case OMPD_target_simd:
11645       if (OpenMPVersion >= 50 &&
11646           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11647         CaptureRegion = OMPD_target;
11648       break;
11649     case OMPD_teams_distribute_simd:
11650     case OMPD_target_teams_distribute_simd:
11651       if (OpenMPVersion >= 50 &&
11652           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11653         CaptureRegion = OMPD_teams;
11654       break;
11655     case OMPD_cancel:
11656     case OMPD_parallel:
11657     case OMPD_parallel_master:
11658     case OMPD_parallel_sections:
11659     case OMPD_parallel_for:
11660     case OMPD_target:
11661     case OMPD_target_teams:
11662     case OMPD_target_teams_distribute:
11663     case OMPD_distribute_parallel_for:
11664     case OMPD_task:
11665     case OMPD_taskloop:
11666     case OMPD_master_taskloop:
11667     case OMPD_target_data:
11668     case OMPD_simd:
11669     case OMPD_for_simd:
11670     case OMPD_distribute_simd:
11671       // Do not capture if-clause expressions.
11672       break;
11673     case OMPD_threadprivate:
11674     case OMPD_allocate:
11675     case OMPD_taskyield:
11676     case OMPD_barrier:
11677     case OMPD_taskwait:
11678     case OMPD_cancellation_point:
11679     case OMPD_flush:
11680     case OMPD_depobj:
11681     case OMPD_scan:
11682     case OMPD_declare_reduction:
11683     case OMPD_declare_mapper:
11684     case OMPD_declare_simd:
11685     case OMPD_declare_variant:
11686     case OMPD_begin_declare_variant:
11687     case OMPD_end_declare_variant:
11688     case OMPD_declare_target:
11689     case OMPD_end_declare_target:
11690     case OMPD_teams:
11691     case OMPD_for:
11692     case OMPD_sections:
11693     case OMPD_section:
11694     case OMPD_single:
11695     case OMPD_master:
11696     case OMPD_critical:
11697     case OMPD_taskgroup:
11698     case OMPD_distribute:
11699     case OMPD_ordered:
11700     case OMPD_atomic:
11701     case OMPD_teams_distribute:
11702     case OMPD_requires:
11703       llvm_unreachable("Unexpected OpenMP directive with if-clause");
11704     case OMPD_unknown:
11705       llvm_unreachable("Unknown OpenMP directive");
11706     }
11707     break;
11708   case OMPC_num_threads:
11709     switch (DKind) {
11710     case OMPD_target_parallel:
11711     case OMPD_target_parallel_for:
11712     case OMPD_target_parallel_for_simd:
11713       CaptureRegion = OMPD_target;
11714       break;
11715     case OMPD_teams_distribute_parallel_for:
11716     case OMPD_teams_distribute_parallel_for_simd:
11717     case OMPD_target_teams_distribute_parallel_for:
11718     case OMPD_target_teams_distribute_parallel_for_simd:
11719       CaptureRegion = OMPD_teams;
11720       break;
11721     case OMPD_parallel:
11722     case OMPD_parallel_master:
11723     case OMPD_parallel_sections:
11724     case OMPD_parallel_for:
11725     case OMPD_parallel_for_simd:
11726     case OMPD_distribute_parallel_for:
11727     case OMPD_distribute_parallel_for_simd:
11728     case OMPD_parallel_master_taskloop:
11729     case OMPD_parallel_master_taskloop_simd:
11730       // Do not capture num_threads-clause expressions.
11731       break;
11732     case OMPD_target_data:
11733     case OMPD_target_enter_data:
11734     case OMPD_target_exit_data:
11735     case OMPD_target_update:
11736     case OMPD_target:
11737     case OMPD_target_simd:
11738     case OMPD_target_teams:
11739     case OMPD_target_teams_distribute:
11740     case OMPD_target_teams_distribute_simd:
11741     case OMPD_cancel:
11742     case OMPD_task:
11743     case OMPD_taskloop:
11744     case OMPD_taskloop_simd:
11745     case OMPD_master_taskloop:
11746     case OMPD_master_taskloop_simd:
11747     case OMPD_threadprivate:
11748     case OMPD_allocate:
11749     case OMPD_taskyield:
11750     case OMPD_barrier:
11751     case OMPD_taskwait:
11752     case OMPD_cancellation_point:
11753     case OMPD_flush:
11754     case OMPD_depobj:
11755     case OMPD_scan:
11756     case OMPD_declare_reduction:
11757     case OMPD_declare_mapper:
11758     case OMPD_declare_simd:
11759     case OMPD_declare_variant:
11760     case OMPD_begin_declare_variant:
11761     case OMPD_end_declare_variant:
11762     case OMPD_declare_target:
11763     case OMPD_end_declare_target:
11764     case OMPD_teams:
11765     case OMPD_simd:
11766     case OMPD_for:
11767     case OMPD_for_simd:
11768     case OMPD_sections:
11769     case OMPD_section:
11770     case OMPD_single:
11771     case OMPD_master:
11772     case OMPD_critical:
11773     case OMPD_taskgroup:
11774     case OMPD_distribute:
11775     case OMPD_ordered:
11776     case OMPD_atomic:
11777     case OMPD_distribute_simd:
11778     case OMPD_teams_distribute:
11779     case OMPD_teams_distribute_simd:
11780     case OMPD_requires:
11781       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11782     case OMPD_unknown:
11783       llvm_unreachable("Unknown OpenMP directive");
11784     }
11785     break;
11786   case OMPC_num_teams:
11787     switch (DKind) {
11788     case OMPD_target_teams:
11789     case OMPD_target_teams_distribute:
11790     case OMPD_target_teams_distribute_simd:
11791     case OMPD_target_teams_distribute_parallel_for:
11792     case OMPD_target_teams_distribute_parallel_for_simd:
11793       CaptureRegion = OMPD_target;
11794       break;
11795     case OMPD_teams_distribute_parallel_for:
11796     case OMPD_teams_distribute_parallel_for_simd:
11797     case OMPD_teams:
11798     case OMPD_teams_distribute:
11799     case OMPD_teams_distribute_simd:
11800       // Do not capture num_teams-clause expressions.
11801       break;
11802     case OMPD_distribute_parallel_for:
11803     case OMPD_distribute_parallel_for_simd:
11804     case OMPD_task:
11805     case OMPD_taskloop:
11806     case OMPD_taskloop_simd:
11807     case OMPD_master_taskloop:
11808     case OMPD_master_taskloop_simd:
11809     case OMPD_parallel_master_taskloop:
11810     case OMPD_parallel_master_taskloop_simd:
11811     case OMPD_target_data:
11812     case OMPD_target_enter_data:
11813     case OMPD_target_exit_data:
11814     case OMPD_target_update:
11815     case OMPD_cancel:
11816     case OMPD_parallel:
11817     case OMPD_parallel_master:
11818     case OMPD_parallel_sections:
11819     case OMPD_parallel_for:
11820     case OMPD_parallel_for_simd:
11821     case OMPD_target:
11822     case OMPD_target_simd:
11823     case OMPD_target_parallel:
11824     case OMPD_target_parallel_for:
11825     case OMPD_target_parallel_for_simd:
11826     case OMPD_threadprivate:
11827     case OMPD_allocate:
11828     case OMPD_taskyield:
11829     case OMPD_barrier:
11830     case OMPD_taskwait:
11831     case OMPD_cancellation_point:
11832     case OMPD_flush:
11833     case OMPD_depobj:
11834     case OMPD_scan:
11835     case OMPD_declare_reduction:
11836     case OMPD_declare_mapper:
11837     case OMPD_declare_simd:
11838     case OMPD_declare_variant:
11839     case OMPD_begin_declare_variant:
11840     case OMPD_end_declare_variant:
11841     case OMPD_declare_target:
11842     case OMPD_end_declare_target:
11843     case OMPD_simd:
11844     case OMPD_for:
11845     case OMPD_for_simd:
11846     case OMPD_sections:
11847     case OMPD_section:
11848     case OMPD_single:
11849     case OMPD_master:
11850     case OMPD_critical:
11851     case OMPD_taskgroup:
11852     case OMPD_distribute:
11853     case OMPD_ordered:
11854     case OMPD_atomic:
11855     case OMPD_distribute_simd:
11856     case OMPD_requires:
11857       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11858     case OMPD_unknown:
11859       llvm_unreachable("Unknown OpenMP directive");
11860     }
11861     break;
11862   case OMPC_thread_limit:
11863     switch (DKind) {
11864     case OMPD_target_teams:
11865     case OMPD_target_teams_distribute:
11866     case OMPD_target_teams_distribute_simd:
11867     case OMPD_target_teams_distribute_parallel_for:
11868     case OMPD_target_teams_distribute_parallel_for_simd:
11869       CaptureRegion = OMPD_target;
11870       break;
11871     case OMPD_teams_distribute_parallel_for:
11872     case OMPD_teams_distribute_parallel_for_simd:
11873     case OMPD_teams:
11874     case OMPD_teams_distribute:
11875     case OMPD_teams_distribute_simd:
11876       // Do not capture thread_limit-clause expressions.
11877       break;
11878     case OMPD_distribute_parallel_for:
11879     case OMPD_distribute_parallel_for_simd:
11880     case OMPD_task:
11881     case OMPD_taskloop:
11882     case OMPD_taskloop_simd:
11883     case OMPD_master_taskloop:
11884     case OMPD_master_taskloop_simd:
11885     case OMPD_parallel_master_taskloop:
11886     case OMPD_parallel_master_taskloop_simd:
11887     case OMPD_target_data:
11888     case OMPD_target_enter_data:
11889     case OMPD_target_exit_data:
11890     case OMPD_target_update:
11891     case OMPD_cancel:
11892     case OMPD_parallel:
11893     case OMPD_parallel_master:
11894     case OMPD_parallel_sections:
11895     case OMPD_parallel_for:
11896     case OMPD_parallel_for_simd:
11897     case OMPD_target:
11898     case OMPD_target_simd:
11899     case OMPD_target_parallel:
11900     case OMPD_target_parallel_for:
11901     case OMPD_target_parallel_for_simd:
11902     case OMPD_threadprivate:
11903     case OMPD_allocate:
11904     case OMPD_taskyield:
11905     case OMPD_barrier:
11906     case OMPD_taskwait:
11907     case OMPD_cancellation_point:
11908     case OMPD_flush:
11909     case OMPD_depobj:
11910     case OMPD_scan:
11911     case OMPD_declare_reduction:
11912     case OMPD_declare_mapper:
11913     case OMPD_declare_simd:
11914     case OMPD_declare_variant:
11915     case OMPD_begin_declare_variant:
11916     case OMPD_end_declare_variant:
11917     case OMPD_declare_target:
11918     case OMPD_end_declare_target:
11919     case OMPD_simd:
11920     case OMPD_for:
11921     case OMPD_for_simd:
11922     case OMPD_sections:
11923     case OMPD_section:
11924     case OMPD_single:
11925     case OMPD_master:
11926     case OMPD_critical:
11927     case OMPD_taskgroup:
11928     case OMPD_distribute:
11929     case OMPD_ordered:
11930     case OMPD_atomic:
11931     case OMPD_distribute_simd:
11932     case OMPD_requires:
11933       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11934     case OMPD_unknown:
11935       llvm_unreachable("Unknown OpenMP directive");
11936     }
11937     break;
11938   case OMPC_schedule:
11939     switch (DKind) {
11940     case OMPD_parallel_for:
11941     case OMPD_parallel_for_simd:
11942     case OMPD_distribute_parallel_for:
11943     case OMPD_distribute_parallel_for_simd:
11944     case OMPD_teams_distribute_parallel_for:
11945     case OMPD_teams_distribute_parallel_for_simd:
11946     case OMPD_target_parallel_for:
11947     case OMPD_target_parallel_for_simd:
11948     case OMPD_target_teams_distribute_parallel_for:
11949     case OMPD_target_teams_distribute_parallel_for_simd:
11950       CaptureRegion = OMPD_parallel;
11951       break;
11952     case OMPD_for:
11953     case OMPD_for_simd:
11954       // Do not capture schedule-clause expressions.
11955       break;
11956     case OMPD_task:
11957     case OMPD_taskloop:
11958     case OMPD_taskloop_simd:
11959     case OMPD_master_taskloop:
11960     case OMPD_master_taskloop_simd:
11961     case OMPD_parallel_master_taskloop:
11962     case OMPD_parallel_master_taskloop_simd:
11963     case OMPD_target_data:
11964     case OMPD_target_enter_data:
11965     case OMPD_target_exit_data:
11966     case OMPD_target_update:
11967     case OMPD_teams:
11968     case OMPD_teams_distribute:
11969     case OMPD_teams_distribute_simd:
11970     case OMPD_target_teams_distribute:
11971     case OMPD_target_teams_distribute_simd:
11972     case OMPD_target:
11973     case OMPD_target_simd:
11974     case OMPD_target_parallel:
11975     case OMPD_cancel:
11976     case OMPD_parallel:
11977     case OMPD_parallel_master:
11978     case OMPD_parallel_sections:
11979     case OMPD_threadprivate:
11980     case OMPD_allocate:
11981     case OMPD_taskyield:
11982     case OMPD_barrier:
11983     case OMPD_taskwait:
11984     case OMPD_cancellation_point:
11985     case OMPD_flush:
11986     case OMPD_depobj:
11987     case OMPD_scan:
11988     case OMPD_declare_reduction:
11989     case OMPD_declare_mapper:
11990     case OMPD_declare_simd:
11991     case OMPD_declare_variant:
11992     case OMPD_begin_declare_variant:
11993     case OMPD_end_declare_variant:
11994     case OMPD_declare_target:
11995     case OMPD_end_declare_target:
11996     case OMPD_simd:
11997     case OMPD_sections:
11998     case OMPD_section:
11999     case OMPD_single:
12000     case OMPD_master:
12001     case OMPD_critical:
12002     case OMPD_taskgroup:
12003     case OMPD_distribute:
12004     case OMPD_ordered:
12005     case OMPD_atomic:
12006     case OMPD_distribute_simd:
12007     case OMPD_target_teams:
12008     case OMPD_requires:
12009       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12010     case OMPD_unknown:
12011       llvm_unreachable("Unknown OpenMP directive");
12012     }
12013     break;
12014   case OMPC_dist_schedule:
12015     switch (DKind) {
12016     case OMPD_teams_distribute_parallel_for:
12017     case OMPD_teams_distribute_parallel_for_simd:
12018     case OMPD_teams_distribute:
12019     case OMPD_teams_distribute_simd:
12020     case OMPD_target_teams_distribute_parallel_for:
12021     case OMPD_target_teams_distribute_parallel_for_simd:
12022     case OMPD_target_teams_distribute:
12023     case OMPD_target_teams_distribute_simd:
12024       CaptureRegion = OMPD_teams;
12025       break;
12026     case OMPD_distribute_parallel_for:
12027     case OMPD_distribute_parallel_for_simd:
12028     case OMPD_distribute:
12029     case OMPD_distribute_simd:
12030       // Do not capture thread_limit-clause expressions.
12031       break;
12032     case OMPD_parallel_for:
12033     case OMPD_parallel_for_simd:
12034     case OMPD_target_parallel_for_simd:
12035     case OMPD_target_parallel_for:
12036     case OMPD_task:
12037     case OMPD_taskloop:
12038     case OMPD_taskloop_simd:
12039     case OMPD_master_taskloop:
12040     case OMPD_master_taskloop_simd:
12041     case OMPD_parallel_master_taskloop:
12042     case OMPD_parallel_master_taskloop_simd:
12043     case OMPD_target_data:
12044     case OMPD_target_enter_data:
12045     case OMPD_target_exit_data:
12046     case OMPD_target_update:
12047     case OMPD_teams:
12048     case OMPD_target:
12049     case OMPD_target_simd:
12050     case OMPD_target_parallel:
12051     case OMPD_cancel:
12052     case OMPD_parallel:
12053     case OMPD_parallel_master:
12054     case OMPD_parallel_sections:
12055     case OMPD_threadprivate:
12056     case OMPD_allocate:
12057     case OMPD_taskyield:
12058     case OMPD_barrier:
12059     case OMPD_taskwait:
12060     case OMPD_cancellation_point:
12061     case OMPD_flush:
12062     case OMPD_depobj:
12063     case OMPD_scan:
12064     case OMPD_declare_reduction:
12065     case OMPD_declare_mapper:
12066     case OMPD_declare_simd:
12067     case OMPD_declare_variant:
12068     case OMPD_begin_declare_variant:
12069     case OMPD_end_declare_variant:
12070     case OMPD_declare_target:
12071     case OMPD_end_declare_target:
12072     case OMPD_simd:
12073     case OMPD_for:
12074     case OMPD_for_simd:
12075     case OMPD_sections:
12076     case OMPD_section:
12077     case OMPD_single:
12078     case OMPD_master:
12079     case OMPD_critical:
12080     case OMPD_taskgroup:
12081     case OMPD_ordered:
12082     case OMPD_atomic:
12083     case OMPD_target_teams:
12084     case OMPD_requires:
12085       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12086     case OMPD_unknown:
12087       llvm_unreachable("Unknown OpenMP directive");
12088     }
12089     break;
12090   case OMPC_device:
12091     switch (DKind) {
12092     case OMPD_target_update:
12093     case OMPD_target_enter_data:
12094     case OMPD_target_exit_data:
12095     case OMPD_target:
12096     case OMPD_target_simd:
12097     case OMPD_target_teams:
12098     case OMPD_target_parallel:
12099     case OMPD_target_teams_distribute:
12100     case OMPD_target_teams_distribute_simd:
12101     case OMPD_target_parallel_for:
12102     case OMPD_target_parallel_for_simd:
12103     case OMPD_target_teams_distribute_parallel_for:
12104     case OMPD_target_teams_distribute_parallel_for_simd:
12105       CaptureRegion = OMPD_task;
12106       break;
12107     case OMPD_target_data:
12108       // Do not capture device-clause expressions.
12109       break;
12110     case OMPD_teams_distribute_parallel_for:
12111     case OMPD_teams_distribute_parallel_for_simd:
12112     case OMPD_teams:
12113     case OMPD_teams_distribute:
12114     case OMPD_teams_distribute_simd:
12115     case OMPD_distribute_parallel_for:
12116     case OMPD_distribute_parallel_for_simd:
12117     case OMPD_task:
12118     case OMPD_taskloop:
12119     case OMPD_taskloop_simd:
12120     case OMPD_master_taskloop:
12121     case OMPD_master_taskloop_simd:
12122     case OMPD_parallel_master_taskloop:
12123     case OMPD_parallel_master_taskloop_simd:
12124     case OMPD_cancel:
12125     case OMPD_parallel:
12126     case OMPD_parallel_master:
12127     case OMPD_parallel_sections:
12128     case OMPD_parallel_for:
12129     case OMPD_parallel_for_simd:
12130     case OMPD_threadprivate:
12131     case OMPD_allocate:
12132     case OMPD_taskyield:
12133     case OMPD_barrier:
12134     case OMPD_taskwait:
12135     case OMPD_cancellation_point:
12136     case OMPD_flush:
12137     case OMPD_depobj:
12138     case OMPD_scan:
12139     case OMPD_declare_reduction:
12140     case OMPD_declare_mapper:
12141     case OMPD_declare_simd:
12142     case OMPD_declare_variant:
12143     case OMPD_begin_declare_variant:
12144     case OMPD_end_declare_variant:
12145     case OMPD_declare_target:
12146     case OMPD_end_declare_target:
12147     case OMPD_simd:
12148     case OMPD_for:
12149     case OMPD_for_simd:
12150     case OMPD_sections:
12151     case OMPD_section:
12152     case OMPD_single:
12153     case OMPD_master:
12154     case OMPD_critical:
12155     case OMPD_taskgroup:
12156     case OMPD_distribute:
12157     case OMPD_ordered:
12158     case OMPD_atomic:
12159     case OMPD_distribute_simd:
12160     case OMPD_requires:
12161       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
12162     case OMPD_unknown:
12163       llvm_unreachable("Unknown OpenMP directive");
12164     }
12165     break;
12166   case OMPC_grainsize:
12167   case OMPC_num_tasks:
12168   case OMPC_final:
12169   case OMPC_priority:
12170     switch (DKind) {
12171     case OMPD_task:
12172     case OMPD_taskloop:
12173     case OMPD_taskloop_simd:
12174     case OMPD_master_taskloop:
12175     case OMPD_master_taskloop_simd:
12176       break;
12177     case OMPD_parallel_master_taskloop:
12178     case OMPD_parallel_master_taskloop_simd:
12179       CaptureRegion = OMPD_parallel;
12180       break;
12181     case OMPD_target_update:
12182     case OMPD_target_enter_data:
12183     case OMPD_target_exit_data:
12184     case OMPD_target:
12185     case OMPD_target_simd:
12186     case OMPD_target_teams:
12187     case OMPD_target_parallel:
12188     case OMPD_target_teams_distribute:
12189     case OMPD_target_teams_distribute_simd:
12190     case OMPD_target_parallel_for:
12191     case OMPD_target_parallel_for_simd:
12192     case OMPD_target_teams_distribute_parallel_for:
12193     case OMPD_target_teams_distribute_parallel_for_simd:
12194     case OMPD_target_data:
12195     case OMPD_teams_distribute_parallel_for:
12196     case OMPD_teams_distribute_parallel_for_simd:
12197     case OMPD_teams:
12198     case OMPD_teams_distribute:
12199     case OMPD_teams_distribute_simd:
12200     case OMPD_distribute_parallel_for:
12201     case OMPD_distribute_parallel_for_simd:
12202     case OMPD_cancel:
12203     case OMPD_parallel:
12204     case OMPD_parallel_master:
12205     case OMPD_parallel_sections:
12206     case OMPD_parallel_for:
12207     case OMPD_parallel_for_simd:
12208     case OMPD_threadprivate:
12209     case OMPD_allocate:
12210     case OMPD_taskyield:
12211     case OMPD_barrier:
12212     case OMPD_taskwait:
12213     case OMPD_cancellation_point:
12214     case OMPD_flush:
12215     case OMPD_depobj:
12216     case OMPD_scan:
12217     case OMPD_declare_reduction:
12218     case OMPD_declare_mapper:
12219     case OMPD_declare_simd:
12220     case OMPD_declare_variant:
12221     case OMPD_begin_declare_variant:
12222     case OMPD_end_declare_variant:
12223     case OMPD_declare_target:
12224     case OMPD_end_declare_target:
12225     case OMPD_simd:
12226     case OMPD_for:
12227     case OMPD_for_simd:
12228     case OMPD_sections:
12229     case OMPD_section:
12230     case OMPD_single:
12231     case OMPD_master:
12232     case OMPD_critical:
12233     case OMPD_taskgroup:
12234     case OMPD_distribute:
12235     case OMPD_ordered:
12236     case OMPD_atomic:
12237     case OMPD_distribute_simd:
12238     case OMPD_requires:
12239       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
12240     case OMPD_unknown:
12241       llvm_unreachable("Unknown OpenMP directive");
12242     }
12243     break;
12244   case OMPC_firstprivate:
12245   case OMPC_lastprivate:
12246   case OMPC_reduction:
12247   case OMPC_task_reduction:
12248   case OMPC_in_reduction:
12249   case OMPC_linear:
12250   case OMPC_default:
12251   case OMPC_proc_bind:
12252   case OMPC_safelen:
12253   case OMPC_simdlen:
12254   case OMPC_allocator:
12255   case OMPC_collapse:
12256   case OMPC_private:
12257   case OMPC_shared:
12258   case OMPC_aligned:
12259   case OMPC_copyin:
12260   case OMPC_copyprivate:
12261   case OMPC_ordered:
12262   case OMPC_nowait:
12263   case OMPC_untied:
12264   case OMPC_mergeable:
12265   case OMPC_threadprivate:
12266   case OMPC_allocate:
12267   case OMPC_flush:
12268   case OMPC_depobj:
12269   case OMPC_read:
12270   case OMPC_write:
12271   case OMPC_update:
12272   case OMPC_capture:
12273   case OMPC_seq_cst:
12274   case OMPC_acq_rel:
12275   case OMPC_acquire:
12276   case OMPC_release:
12277   case OMPC_relaxed:
12278   case OMPC_depend:
12279   case OMPC_threads:
12280   case OMPC_simd:
12281   case OMPC_map:
12282   case OMPC_nogroup:
12283   case OMPC_hint:
12284   case OMPC_defaultmap:
12285   case OMPC_unknown:
12286   case OMPC_uniform:
12287   case OMPC_to:
12288   case OMPC_from:
12289   case OMPC_use_device_ptr:
12290   case OMPC_use_device_addr:
12291   case OMPC_is_device_ptr:
12292   case OMPC_unified_address:
12293   case OMPC_unified_shared_memory:
12294   case OMPC_reverse_offload:
12295   case OMPC_dynamic_allocators:
12296   case OMPC_atomic_default_mem_order:
12297   case OMPC_device_type:
12298   case OMPC_match:
12299   case OMPC_nontemporal:
12300   case OMPC_order:
12301   case OMPC_destroy:
12302   case OMPC_detach:
12303   case OMPC_inclusive:
12304   case OMPC_exclusive:
12305   case OMPC_uses_allocators:
12306   case OMPC_affinity:
12307     llvm_unreachable("Unexpected OpenMP clause.");
12308   }
12309   return CaptureRegion;
12310 }
12311 
12312 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
12313                                      Expr *Condition, SourceLocation StartLoc,
12314                                      SourceLocation LParenLoc,
12315                                      SourceLocation NameModifierLoc,
12316                                      SourceLocation ColonLoc,
12317                                      SourceLocation EndLoc) {
12318   Expr *ValExpr = Condition;
12319   Stmt *HelperValStmt = nullptr;
12320   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12321   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12322       !Condition->isInstantiationDependent() &&
12323       !Condition->containsUnexpandedParameterPack()) {
12324     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12325     if (Val.isInvalid())
12326       return nullptr;
12327 
12328     ValExpr = Val.get();
12329 
12330     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12331     CaptureRegion = getOpenMPCaptureRegionForClause(
12332         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
12333     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12334       ValExpr = MakeFullExpr(ValExpr).get();
12335       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12336       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12337       HelperValStmt = buildPreInits(Context, Captures);
12338     }
12339   }
12340 
12341   return new (Context)
12342       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
12343                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
12344 }
12345 
12346 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
12347                                         SourceLocation StartLoc,
12348                                         SourceLocation LParenLoc,
12349                                         SourceLocation EndLoc) {
12350   Expr *ValExpr = Condition;
12351   Stmt *HelperValStmt = nullptr;
12352   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12353   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12354       !Condition->isInstantiationDependent() &&
12355       !Condition->containsUnexpandedParameterPack()) {
12356     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12357     if (Val.isInvalid())
12358       return nullptr;
12359 
12360     ValExpr = MakeFullExpr(Val.get()).get();
12361 
12362     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12363     CaptureRegion =
12364         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
12365     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12366       ValExpr = MakeFullExpr(ValExpr).get();
12367       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12368       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12369       HelperValStmt = buildPreInits(Context, Captures);
12370     }
12371   }
12372 
12373   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
12374                                       StartLoc, LParenLoc, EndLoc);
12375 }
12376 
12377 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
12378                                                         Expr *Op) {
12379   if (!Op)
12380     return ExprError();
12381 
12382   class IntConvertDiagnoser : public ICEConvertDiagnoser {
12383   public:
12384     IntConvertDiagnoser()
12385         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
12386     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12387                                          QualType T) override {
12388       return S.Diag(Loc, diag::err_omp_not_integral) << T;
12389     }
12390     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
12391                                              QualType T) override {
12392       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
12393     }
12394     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
12395                                                QualType T,
12396                                                QualType ConvTy) override {
12397       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
12398     }
12399     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
12400                                            QualType ConvTy) override {
12401       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12402              << ConvTy->isEnumeralType() << ConvTy;
12403     }
12404     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
12405                                             QualType T) override {
12406       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
12407     }
12408     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
12409                                         QualType ConvTy) override {
12410       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12411              << ConvTy->isEnumeralType() << ConvTy;
12412     }
12413     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
12414                                              QualType) override {
12415       llvm_unreachable("conversion functions are permitted");
12416     }
12417   } ConvertDiagnoser;
12418   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
12419 }
12420 
12421 static bool
12422 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
12423                           bool StrictlyPositive, bool BuildCapture = false,
12424                           OpenMPDirectiveKind DKind = OMPD_unknown,
12425                           OpenMPDirectiveKind *CaptureRegion = nullptr,
12426                           Stmt **HelperValStmt = nullptr) {
12427   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
12428       !ValExpr->isInstantiationDependent()) {
12429     SourceLocation Loc = ValExpr->getExprLoc();
12430     ExprResult Value =
12431         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
12432     if (Value.isInvalid())
12433       return false;
12434 
12435     ValExpr = Value.get();
12436     // The expression must evaluate to a non-negative integer value.
12437     llvm::APSInt Result;
12438     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
12439         Result.isSigned() &&
12440         !((!StrictlyPositive && Result.isNonNegative()) ||
12441           (StrictlyPositive && Result.isStrictlyPositive()))) {
12442       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
12443           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12444           << ValExpr->getSourceRange();
12445       return false;
12446     }
12447     if (!BuildCapture)
12448       return true;
12449     *CaptureRegion =
12450         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
12451     if (*CaptureRegion != OMPD_unknown &&
12452         !SemaRef.CurContext->isDependentContext()) {
12453       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
12454       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12455       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
12456       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
12457     }
12458   }
12459   return true;
12460 }
12461 
12462 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
12463                                              SourceLocation StartLoc,
12464                                              SourceLocation LParenLoc,
12465                                              SourceLocation EndLoc) {
12466   Expr *ValExpr = NumThreads;
12467   Stmt *HelperValStmt = nullptr;
12468 
12469   // OpenMP [2.5, Restrictions]
12470   //  The num_threads expression must evaluate to a positive integer value.
12471   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
12472                                  /*StrictlyPositive=*/true))
12473     return nullptr;
12474 
12475   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12476   OpenMPDirectiveKind CaptureRegion =
12477       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
12478   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12479     ValExpr = MakeFullExpr(ValExpr).get();
12480     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12481     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12482     HelperValStmt = buildPreInits(Context, Captures);
12483   }
12484 
12485   return new (Context) OMPNumThreadsClause(
12486       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12487 }
12488 
12489 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
12490                                                        OpenMPClauseKind CKind,
12491                                                        bool StrictlyPositive) {
12492   if (!E)
12493     return ExprError();
12494   if (E->isValueDependent() || E->isTypeDependent() ||
12495       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
12496     return E;
12497   llvm::APSInt Result;
12498   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
12499   if (ICE.isInvalid())
12500     return ExprError();
12501   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
12502       (!StrictlyPositive && !Result.isNonNegative())) {
12503     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
12504         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12505         << E->getSourceRange();
12506     return ExprError();
12507   }
12508   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
12509     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
12510         << E->getSourceRange();
12511     return ExprError();
12512   }
12513   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
12514     DSAStack->setAssociatedLoops(Result.getExtValue());
12515   else if (CKind == OMPC_ordered)
12516     DSAStack->setAssociatedLoops(Result.getExtValue());
12517   return ICE;
12518 }
12519 
12520 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
12521                                           SourceLocation LParenLoc,
12522                                           SourceLocation EndLoc) {
12523   // OpenMP [2.8.1, simd construct, Description]
12524   // The parameter of the safelen clause must be a constant
12525   // positive integer expression.
12526   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
12527   if (Safelen.isInvalid())
12528     return nullptr;
12529   return new (Context)
12530       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
12531 }
12532 
12533 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
12534                                           SourceLocation LParenLoc,
12535                                           SourceLocation EndLoc) {
12536   // OpenMP [2.8.1, simd construct, Description]
12537   // The parameter of the simdlen clause must be a constant
12538   // positive integer expression.
12539   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
12540   if (Simdlen.isInvalid())
12541     return nullptr;
12542   return new (Context)
12543       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
12544 }
12545 
12546 /// Tries to find omp_allocator_handle_t type.
12547 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
12548                                     DSAStackTy *Stack) {
12549   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
12550   if (!OMPAllocatorHandleT.isNull())
12551     return true;
12552   // Build the predefined allocator expressions.
12553   bool ErrorFound = false;
12554   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
12555     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
12556     StringRef Allocator =
12557         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
12558     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
12559     auto *VD = dyn_cast_or_null<ValueDecl>(
12560         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
12561     if (!VD) {
12562       ErrorFound = true;
12563       break;
12564     }
12565     QualType AllocatorType =
12566         VD->getType().getNonLValueExprType(S.getASTContext());
12567     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
12568     if (!Res.isUsable()) {
12569       ErrorFound = true;
12570       break;
12571     }
12572     if (OMPAllocatorHandleT.isNull())
12573       OMPAllocatorHandleT = AllocatorType;
12574     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
12575       ErrorFound = true;
12576       break;
12577     }
12578     Stack->setAllocator(AllocatorKind, Res.get());
12579   }
12580   if (ErrorFound) {
12581     S.Diag(Loc, diag::err_omp_implied_type_not_found)
12582         << "omp_allocator_handle_t";
12583     return false;
12584   }
12585   OMPAllocatorHandleT.addConst();
12586   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
12587   return true;
12588 }
12589 
12590 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
12591                                             SourceLocation LParenLoc,
12592                                             SourceLocation EndLoc) {
12593   // OpenMP [2.11.3, allocate Directive, Description]
12594   // allocator is an expression of omp_allocator_handle_t type.
12595   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
12596     return nullptr;
12597 
12598   ExprResult Allocator = DefaultLvalueConversion(A);
12599   if (Allocator.isInvalid())
12600     return nullptr;
12601   Allocator = PerformImplicitConversion(Allocator.get(),
12602                                         DSAStack->getOMPAllocatorHandleT(),
12603                                         Sema::AA_Initializing,
12604                                         /*AllowExplicit=*/true);
12605   if (Allocator.isInvalid())
12606     return nullptr;
12607   return new (Context)
12608       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
12609 }
12610 
12611 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
12612                                            SourceLocation StartLoc,
12613                                            SourceLocation LParenLoc,
12614                                            SourceLocation EndLoc) {
12615   // OpenMP [2.7.1, loop construct, Description]
12616   // OpenMP [2.8.1, simd construct, Description]
12617   // OpenMP [2.9.6, distribute construct, Description]
12618   // The parameter of the collapse clause must be a constant
12619   // positive integer expression.
12620   ExprResult NumForLoopsResult =
12621       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
12622   if (NumForLoopsResult.isInvalid())
12623     return nullptr;
12624   return new (Context)
12625       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
12626 }
12627 
12628 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
12629                                           SourceLocation EndLoc,
12630                                           SourceLocation LParenLoc,
12631                                           Expr *NumForLoops) {
12632   // OpenMP [2.7.1, loop construct, Description]
12633   // OpenMP [2.8.1, simd construct, Description]
12634   // OpenMP [2.9.6, distribute construct, Description]
12635   // The parameter of the ordered clause must be a constant
12636   // positive integer expression if any.
12637   if (NumForLoops && LParenLoc.isValid()) {
12638     ExprResult NumForLoopsResult =
12639         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
12640     if (NumForLoopsResult.isInvalid())
12641       return nullptr;
12642     NumForLoops = NumForLoopsResult.get();
12643   } else {
12644     NumForLoops = nullptr;
12645   }
12646   auto *Clause = OMPOrderedClause::Create(
12647       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
12648       StartLoc, LParenLoc, EndLoc);
12649   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
12650   return Clause;
12651 }
12652 
12653 OMPClause *Sema::ActOnOpenMPSimpleClause(
12654     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
12655     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12656   OMPClause *Res = nullptr;
12657   switch (Kind) {
12658   case OMPC_default:
12659     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
12660                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12661     break;
12662   case OMPC_proc_bind:
12663     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
12664                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12665     break;
12666   case OMPC_atomic_default_mem_order:
12667     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
12668         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
12669         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12670     break;
12671   case OMPC_order:
12672     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
12673                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12674     break;
12675   case OMPC_update:
12676     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
12677                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12678     break;
12679   case OMPC_if:
12680   case OMPC_final:
12681   case OMPC_num_threads:
12682   case OMPC_safelen:
12683   case OMPC_simdlen:
12684   case OMPC_allocator:
12685   case OMPC_collapse:
12686   case OMPC_schedule:
12687   case OMPC_private:
12688   case OMPC_firstprivate:
12689   case OMPC_lastprivate:
12690   case OMPC_shared:
12691   case OMPC_reduction:
12692   case OMPC_task_reduction:
12693   case OMPC_in_reduction:
12694   case OMPC_linear:
12695   case OMPC_aligned:
12696   case OMPC_copyin:
12697   case OMPC_copyprivate:
12698   case OMPC_ordered:
12699   case OMPC_nowait:
12700   case OMPC_untied:
12701   case OMPC_mergeable:
12702   case OMPC_threadprivate:
12703   case OMPC_allocate:
12704   case OMPC_flush:
12705   case OMPC_depobj:
12706   case OMPC_read:
12707   case OMPC_write:
12708   case OMPC_capture:
12709   case OMPC_seq_cst:
12710   case OMPC_acq_rel:
12711   case OMPC_acquire:
12712   case OMPC_release:
12713   case OMPC_relaxed:
12714   case OMPC_depend:
12715   case OMPC_device:
12716   case OMPC_threads:
12717   case OMPC_simd:
12718   case OMPC_map:
12719   case OMPC_num_teams:
12720   case OMPC_thread_limit:
12721   case OMPC_priority:
12722   case OMPC_grainsize:
12723   case OMPC_nogroup:
12724   case OMPC_num_tasks:
12725   case OMPC_hint:
12726   case OMPC_dist_schedule:
12727   case OMPC_defaultmap:
12728   case OMPC_unknown:
12729   case OMPC_uniform:
12730   case OMPC_to:
12731   case OMPC_from:
12732   case OMPC_use_device_ptr:
12733   case OMPC_use_device_addr:
12734   case OMPC_is_device_ptr:
12735   case OMPC_unified_address:
12736   case OMPC_unified_shared_memory:
12737   case OMPC_reverse_offload:
12738   case OMPC_dynamic_allocators:
12739   case OMPC_device_type:
12740   case OMPC_match:
12741   case OMPC_nontemporal:
12742   case OMPC_destroy:
12743   case OMPC_detach:
12744   case OMPC_inclusive:
12745   case OMPC_exclusive:
12746   case OMPC_uses_allocators:
12747   case OMPC_affinity:
12748     llvm_unreachable("Clause is not allowed.");
12749   }
12750   return Res;
12751 }
12752 
12753 static std::string
12754 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
12755                         ArrayRef<unsigned> Exclude = llvm::None) {
12756   SmallString<256> Buffer;
12757   llvm::raw_svector_ostream Out(Buffer);
12758   unsigned Skipped = Exclude.size();
12759   auto S = Exclude.begin(), E = Exclude.end();
12760   for (unsigned I = First; I < Last; ++I) {
12761     if (std::find(S, E, I) != E) {
12762       --Skipped;
12763       continue;
12764     }
12765     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
12766     if (I + Skipped + 2 == Last)
12767       Out << " or ";
12768     else if (I + Skipped + 1 != Last)
12769       Out << ", ";
12770   }
12771   return std::string(Out.str());
12772 }
12773 
12774 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
12775                                           SourceLocation KindKwLoc,
12776                                           SourceLocation StartLoc,
12777                                           SourceLocation LParenLoc,
12778                                           SourceLocation EndLoc) {
12779   if (Kind == OMP_DEFAULT_unknown) {
12780     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12781         << getListOfPossibleValues(OMPC_default, /*First=*/0,
12782                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
12783         << getOpenMPClauseName(OMPC_default);
12784     return nullptr;
12785   }
12786   if (Kind == OMP_DEFAULT_none)
12787     DSAStack->setDefaultDSANone(KindKwLoc);
12788   else if (Kind == OMP_DEFAULT_shared)
12789     DSAStack->setDefaultDSAShared(KindKwLoc);
12790 
12791   return new (Context)
12792       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12793 }
12794 
12795 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
12796                                            SourceLocation KindKwLoc,
12797                                            SourceLocation StartLoc,
12798                                            SourceLocation LParenLoc,
12799                                            SourceLocation EndLoc) {
12800   if (Kind == OMP_PROC_BIND_unknown) {
12801     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12802         << getListOfPossibleValues(OMPC_proc_bind,
12803                                    /*First=*/unsigned(OMP_PROC_BIND_master),
12804                                    /*Last=*/5)
12805         << getOpenMPClauseName(OMPC_proc_bind);
12806     return nullptr;
12807   }
12808   return new (Context)
12809       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12810 }
12811 
12812 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12813     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12814     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12815   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12816     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12817         << getListOfPossibleValues(
12818                OMPC_atomic_default_mem_order, /*First=*/0,
12819                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12820         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12821     return nullptr;
12822   }
12823   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12824                                                       LParenLoc, EndLoc);
12825 }
12826 
12827 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
12828                                         SourceLocation KindKwLoc,
12829                                         SourceLocation StartLoc,
12830                                         SourceLocation LParenLoc,
12831                                         SourceLocation EndLoc) {
12832   if (Kind == OMPC_ORDER_unknown) {
12833     static_assert(OMPC_ORDER_unknown > 0,
12834                   "OMPC_ORDER_unknown not greater than 0");
12835     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12836         << getListOfPossibleValues(OMPC_order, /*First=*/0,
12837                                    /*Last=*/OMPC_ORDER_unknown)
12838         << getOpenMPClauseName(OMPC_order);
12839     return nullptr;
12840   }
12841   return new (Context)
12842       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12843 }
12844 
12845 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
12846                                          SourceLocation KindKwLoc,
12847                                          SourceLocation StartLoc,
12848                                          SourceLocation LParenLoc,
12849                                          SourceLocation EndLoc) {
12850   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
12851       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
12852     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
12853                          OMPC_DEPEND_depobj};
12854     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12855         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12856                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12857         << getOpenMPClauseName(OMPC_update);
12858     return nullptr;
12859   }
12860   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
12861                                  EndLoc);
12862 }
12863 
12864 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
12865     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
12866     SourceLocation StartLoc, SourceLocation LParenLoc,
12867     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
12868     SourceLocation EndLoc) {
12869   OMPClause *Res = nullptr;
12870   switch (Kind) {
12871   case OMPC_schedule:
12872     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12873     assert(Argument.size() == NumberOfElements &&
12874            ArgumentLoc.size() == NumberOfElements);
12875     Res = ActOnOpenMPScheduleClause(
12876         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12877         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12878         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12879         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12880         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
12881     break;
12882   case OMPC_if:
12883     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12884     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12885                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12886                               DelimLoc, EndLoc);
12887     break;
12888   case OMPC_dist_schedule:
12889     Res = ActOnOpenMPDistScheduleClause(
12890         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12891         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12892     break;
12893   case OMPC_defaultmap:
12894     enum { Modifier, DefaultmapKind };
12895     Res = ActOnOpenMPDefaultmapClause(
12896         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12897         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
12898         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12899         EndLoc);
12900     break;
12901   case OMPC_device:
12902     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12903     Res = ActOnOpenMPDeviceClause(
12904         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
12905         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
12906     break;
12907   case OMPC_final:
12908   case OMPC_num_threads:
12909   case OMPC_safelen:
12910   case OMPC_simdlen:
12911   case OMPC_allocator:
12912   case OMPC_collapse:
12913   case OMPC_default:
12914   case OMPC_proc_bind:
12915   case OMPC_private:
12916   case OMPC_firstprivate:
12917   case OMPC_lastprivate:
12918   case OMPC_shared:
12919   case OMPC_reduction:
12920   case OMPC_task_reduction:
12921   case OMPC_in_reduction:
12922   case OMPC_linear:
12923   case OMPC_aligned:
12924   case OMPC_copyin:
12925   case OMPC_copyprivate:
12926   case OMPC_ordered:
12927   case OMPC_nowait:
12928   case OMPC_untied:
12929   case OMPC_mergeable:
12930   case OMPC_threadprivate:
12931   case OMPC_allocate:
12932   case OMPC_flush:
12933   case OMPC_depobj:
12934   case OMPC_read:
12935   case OMPC_write:
12936   case OMPC_update:
12937   case OMPC_capture:
12938   case OMPC_seq_cst:
12939   case OMPC_acq_rel:
12940   case OMPC_acquire:
12941   case OMPC_release:
12942   case OMPC_relaxed:
12943   case OMPC_depend:
12944   case OMPC_threads:
12945   case OMPC_simd:
12946   case OMPC_map:
12947   case OMPC_num_teams:
12948   case OMPC_thread_limit:
12949   case OMPC_priority:
12950   case OMPC_grainsize:
12951   case OMPC_nogroup:
12952   case OMPC_num_tasks:
12953   case OMPC_hint:
12954   case OMPC_unknown:
12955   case OMPC_uniform:
12956   case OMPC_to:
12957   case OMPC_from:
12958   case OMPC_use_device_ptr:
12959   case OMPC_use_device_addr:
12960   case OMPC_is_device_ptr:
12961   case OMPC_unified_address:
12962   case OMPC_unified_shared_memory:
12963   case OMPC_reverse_offload:
12964   case OMPC_dynamic_allocators:
12965   case OMPC_atomic_default_mem_order:
12966   case OMPC_device_type:
12967   case OMPC_match:
12968   case OMPC_nontemporal:
12969   case OMPC_order:
12970   case OMPC_destroy:
12971   case OMPC_detach:
12972   case OMPC_inclusive:
12973   case OMPC_exclusive:
12974   case OMPC_uses_allocators:
12975   case OMPC_affinity:
12976     llvm_unreachable("Clause is not allowed.");
12977   }
12978   return Res;
12979 }
12980 
12981 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12982                                    OpenMPScheduleClauseModifier M2,
12983                                    SourceLocation M1Loc, SourceLocation M2Loc) {
12984   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12985     SmallVector<unsigned, 2> Excluded;
12986     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12987       Excluded.push_back(M2);
12988     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12989       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12990     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12991       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12992     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12993         << getListOfPossibleValues(OMPC_schedule,
12994                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12995                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12996                                    Excluded)
12997         << getOpenMPClauseName(OMPC_schedule);
12998     return true;
12999   }
13000   return false;
13001 }
13002 
13003 OMPClause *Sema::ActOnOpenMPScheduleClause(
13004     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
13005     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13006     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
13007     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
13008   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
13009       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
13010     return nullptr;
13011   // OpenMP, 2.7.1, Loop Construct, Restrictions
13012   // Either the monotonic modifier or the nonmonotonic modifier can be specified
13013   // but not both.
13014   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
13015       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
13016        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
13017       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
13018        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
13019     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
13020         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
13021         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
13022     return nullptr;
13023   }
13024   if (Kind == OMPC_SCHEDULE_unknown) {
13025     std::string Values;
13026     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
13027       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
13028       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13029                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13030                                        Exclude);
13031     } else {
13032       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13033                                        /*Last=*/OMPC_SCHEDULE_unknown);
13034     }
13035     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13036         << Values << getOpenMPClauseName(OMPC_schedule);
13037     return nullptr;
13038   }
13039   // OpenMP, 2.7.1, Loop Construct, Restrictions
13040   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
13041   // schedule(guided).
13042   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
13043        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
13044       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
13045     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
13046          diag::err_omp_schedule_nonmonotonic_static);
13047     return nullptr;
13048   }
13049   Expr *ValExpr = ChunkSize;
13050   Stmt *HelperValStmt = nullptr;
13051   if (ChunkSize) {
13052     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13053         !ChunkSize->isInstantiationDependent() &&
13054         !ChunkSize->containsUnexpandedParameterPack()) {
13055       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13056       ExprResult Val =
13057           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13058       if (Val.isInvalid())
13059         return nullptr;
13060 
13061       ValExpr = Val.get();
13062 
13063       // OpenMP [2.7.1, Restrictions]
13064       //  chunk_size must be a loop invariant integer expression with a positive
13065       //  value.
13066       llvm::APSInt Result;
13067       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13068         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13069           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13070               << "schedule" << 1 << ChunkSize->getSourceRange();
13071           return nullptr;
13072         }
13073       } else if (getOpenMPCaptureRegionForClause(
13074                      DSAStack->getCurrentDirective(), OMPC_schedule,
13075                      LangOpts.OpenMP) != OMPD_unknown &&
13076                  !CurContext->isDependentContext()) {
13077         ValExpr = MakeFullExpr(ValExpr).get();
13078         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13079         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13080         HelperValStmt = buildPreInits(Context, Captures);
13081       }
13082     }
13083   }
13084 
13085   return new (Context)
13086       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
13087                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
13088 }
13089 
13090 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
13091                                    SourceLocation StartLoc,
13092                                    SourceLocation EndLoc) {
13093   OMPClause *Res = nullptr;
13094   switch (Kind) {
13095   case OMPC_ordered:
13096     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
13097     break;
13098   case OMPC_nowait:
13099     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
13100     break;
13101   case OMPC_untied:
13102     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
13103     break;
13104   case OMPC_mergeable:
13105     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
13106     break;
13107   case OMPC_read:
13108     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
13109     break;
13110   case OMPC_write:
13111     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
13112     break;
13113   case OMPC_update:
13114     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
13115     break;
13116   case OMPC_capture:
13117     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
13118     break;
13119   case OMPC_seq_cst:
13120     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
13121     break;
13122   case OMPC_acq_rel:
13123     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
13124     break;
13125   case OMPC_acquire:
13126     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
13127     break;
13128   case OMPC_release:
13129     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
13130     break;
13131   case OMPC_relaxed:
13132     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
13133     break;
13134   case OMPC_threads:
13135     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
13136     break;
13137   case OMPC_simd:
13138     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
13139     break;
13140   case OMPC_nogroup:
13141     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
13142     break;
13143   case OMPC_unified_address:
13144     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
13145     break;
13146   case OMPC_unified_shared_memory:
13147     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13148     break;
13149   case OMPC_reverse_offload:
13150     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
13151     break;
13152   case OMPC_dynamic_allocators:
13153     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
13154     break;
13155   case OMPC_destroy:
13156     Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc);
13157     break;
13158   case OMPC_if:
13159   case OMPC_final:
13160   case OMPC_num_threads:
13161   case OMPC_safelen:
13162   case OMPC_simdlen:
13163   case OMPC_allocator:
13164   case OMPC_collapse:
13165   case OMPC_schedule:
13166   case OMPC_private:
13167   case OMPC_firstprivate:
13168   case OMPC_lastprivate:
13169   case OMPC_shared:
13170   case OMPC_reduction:
13171   case OMPC_task_reduction:
13172   case OMPC_in_reduction:
13173   case OMPC_linear:
13174   case OMPC_aligned:
13175   case OMPC_copyin:
13176   case OMPC_copyprivate:
13177   case OMPC_default:
13178   case OMPC_proc_bind:
13179   case OMPC_threadprivate:
13180   case OMPC_allocate:
13181   case OMPC_flush:
13182   case OMPC_depobj:
13183   case OMPC_depend:
13184   case OMPC_device:
13185   case OMPC_map:
13186   case OMPC_num_teams:
13187   case OMPC_thread_limit:
13188   case OMPC_priority:
13189   case OMPC_grainsize:
13190   case OMPC_num_tasks:
13191   case OMPC_hint:
13192   case OMPC_dist_schedule:
13193   case OMPC_defaultmap:
13194   case OMPC_unknown:
13195   case OMPC_uniform:
13196   case OMPC_to:
13197   case OMPC_from:
13198   case OMPC_use_device_ptr:
13199   case OMPC_use_device_addr:
13200   case OMPC_is_device_ptr:
13201   case OMPC_atomic_default_mem_order:
13202   case OMPC_device_type:
13203   case OMPC_match:
13204   case OMPC_nontemporal:
13205   case OMPC_order:
13206   case OMPC_detach:
13207   case OMPC_inclusive:
13208   case OMPC_exclusive:
13209   case OMPC_uses_allocators:
13210   case OMPC_affinity:
13211     llvm_unreachable("Clause is not allowed.");
13212   }
13213   return Res;
13214 }
13215 
13216 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
13217                                          SourceLocation EndLoc) {
13218   DSAStack->setNowaitRegion();
13219   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
13220 }
13221 
13222 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
13223                                          SourceLocation EndLoc) {
13224   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
13225 }
13226 
13227 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
13228                                             SourceLocation EndLoc) {
13229   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
13230 }
13231 
13232 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
13233                                        SourceLocation EndLoc) {
13234   return new (Context) OMPReadClause(StartLoc, EndLoc);
13235 }
13236 
13237 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
13238                                         SourceLocation EndLoc) {
13239   return new (Context) OMPWriteClause(StartLoc, EndLoc);
13240 }
13241 
13242 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
13243                                          SourceLocation EndLoc) {
13244   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
13245 }
13246 
13247 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
13248                                           SourceLocation EndLoc) {
13249   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
13250 }
13251 
13252 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
13253                                          SourceLocation EndLoc) {
13254   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
13255 }
13256 
13257 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
13258                                          SourceLocation EndLoc) {
13259   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
13260 }
13261 
13262 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
13263                                           SourceLocation EndLoc) {
13264   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
13265 }
13266 
13267 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
13268                                           SourceLocation EndLoc) {
13269   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
13270 }
13271 
13272 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
13273                                           SourceLocation EndLoc) {
13274   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
13275 }
13276 
13277 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
13278                                           SourceLocation EndLoc) {
13279   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
13280 }
13281 
13282 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
13283                                        SourceLocation EndLoc) {
13284   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
13285 }
13286 
13287 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
13288                                           SourceLocation EndLoc) {
13289   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
13290 }
13291 
13292 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
13293                                                  SourceLocation EndLoc) {
13294   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
13295 }
13296 
13297 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
13298                                                       SourceLocation EndLoc) {
13299   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13300 }
13301 
13302 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
13303                                                  SourceLocation EndLoc) {
13304   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
13305 }
13306 
13307 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
13308                                                     SourceLocation EndLoc) {
13309   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
13310 }
13311 
13312 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc,
13313                                           SourceLocation EndLoc) {
13314   return new (Context) OMPDestroyClause(StartLoc, EndLoc);
13315 }
13316 
13317 OMPClause *Sema::ActOnOpenMPVarListClause(
13318     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
13319     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
13320     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
13321     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
13322     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13323     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
13324     SourceLocation ExtraModifierLoc) {
13325   SourceLocation StartLoc = Locs.StartLoc;
13326   SourceLocation LParenLoc = Locs.LParenLoc;
13327   SourceLocation EndLoc = Locs.EndLoc;
13328   OMPClause *Res = nullptr;
13329   switch (Kind) {
13330   case OMPC_private:
13331     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13332     break;
13333   case OMPC_firstprivate:
13334     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13335     break;
13336   case OMPC_lastprivate:
13337     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
13338            "Unexpected lastprivate modifier.");
13339     Res = ActOnOpenMPLastprivateClause(
13340         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
13341         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
13342     break;
13343   case OMPC_shared:
13344     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
13345     break;
13346   case OMPC_reduction:
13347     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
13348            "Unexpected lastprivate modifier.");
13349     Res = ActOnOpenMPReductionClause(
13350         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
13351         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
13352         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
13353     break;
13354   case OMPC_task_reduction:
13355     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13356                                          EndLoc, ReductionOrMapperIdScopeSpec,
13357                                          ReductionOrMapperId);
13358     break;
13359   case OMPC_in_reduction:
13360     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13361                                        EndLoc, ReductionOrMapperIdScopeSpec,
13362                                        ReductionOrMapperId);
13363     break;
13364   case OMPC_linear:
13365     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
13366            "Unexpected linear modifier.");
13367     Res = ActOnOpenMPLinearClause(
13368         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
13369         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
13370         ColonLoc, EndLoc);
13371     break;
13372   case OMPC_aligned:
13373     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
13374                                    LParenLoc, ColonLoc, EndLoc);
13375     break;
13376   case OMPC_copyin:
13377     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
13378     break;
13379   case OMPC_copyprivate:
13380     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13381     break;
13382   case OMPC_flush:
13383     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
13384     break;
13385   case OMPC_depend:
13386     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
13387            "Unexpected depend modifier.");
13388     Res = ActOnOpenMPDependClause(
13389         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
13390         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
13391     break;
13392   case OMPC_map:
13393     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
13394            "Unexpected map modifier.");
13395     Res = ActOnOpenMPMapClause(
13396         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
13397         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
13398         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
13399     break;
13400   case OMPC_to:
13401     Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
13402                               ReductionOrMapperId, Locs);
13403     break;
13404   case OMPC_from:
13405     Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
13406                                 ReductionOrMapperId, Locs);
13407     break;
13408   case OMPC_use_device_ptr:
13409     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
13410     break;
13411   case OMPC_use_device_addr:
13412     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
13413     break;
13414   case OMPC_is_device_ptr:
13415     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
13416     break;
13417   case OMPC_allocate:
13418     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
13419                                     LParenLoc, ColonLoc, EndLoc);
13420     break;
13421   case OMPC_nontemporal:
13422     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
13423     break;
13424   case OMPC_inclusive:
13425     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13426     break;
13427   case OMPC_exclusive:
13428     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13429     break;
13430   case OMPC_affinity:
13431     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
13432                                     DepModOrTailExpr, VarList);
13433     break;
13434   case OMPC_if:
13435   case OMPC_depobj:
13436   case OMPC_final:
13437   case OMPC_num_threads:
13438   case OMPC_safelen:
13439   case OMPC_simdlen:
13440   case OMPC_allocator:
13441   case OMPC_collapse:
13442   case OMPC_default:
13443   case OMPC_proc_bind:
13444   case OMPC_schedule:
13445   case OMPC_ordered:
13446   case OMPC_nowait:
13447   case OMPC_untied:
13448   case OMPC_mergeable:
13449   case OMPC_threadprivate:
13450   case OMPC_read:
13451   case OMPC_write:
13452   case OMPC_update:
13453   case OMPC_capture:
13454   case OMPC_seq_cst:
13455   case OMPC_acq_rel:
13456   case OMPC_acquire:
13457   case OMPC_release:
13458   case OMPC_relaxed:
13459   case OMPC_device:
13460   case OMPC_threads:
13461   case OMPC_simd:
13462   case OMPC_num_teams:
13463   case OMPC_thread_limit:
13464   case OMPC_priority:
13465   case OMPC_grainsize:
13466   case OMPC_nogroup:
13467   case OMPC_num_tasks:
13468   case OMPC_hint:
13469   case OMPC_dist_schedule:
13470   case OMPC_defaultmap:
13471   case OMPC_unknown:
13472   case OMPC_uniform:
13473   case OMPC_unified_address:
13474   case OMPC_unified_shared_memory:
13475   case OMPC_reverse_offload:
13476   case OMPC_dynamic_allocators:
13477   case OMPC_atomic_default_mem_order:
13478   case OMPC_device_type:
13479   case OMPC_match:
13480   case OMPC_order:
13481   case OMPC_destroy:
13482   case OMPC_detach:
13483   case OMPC_uses_allocators:
13484     llvm_unreachable("Clause is not allowed.");
13485   }
13486   return Res;
13487 }
13488 
13489 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
13490                                        ExprObjectKind OK, SourceLocation Loc) {
13491   ExprResult Res = BuildDeclRefExpr(
13492       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
13493   if (!Res.isUsable())
13494     return ExprError();
13495   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
13496     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
13497     if (!Res.isUsable())
13498       return ExprError();
13499   }
13500   if (VK != VK_LValue && Res.get()->isGLValue()) {
13501     Res = DefaultLvalueConversion(Res.get());
13502     if (!Res.isUsable())
13503       return ExprError();
13504   }
13505   return Res;
13506 }
13507 
13508 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
13509                                           SourceLocation StartLoc,
13510                                           SourceLocation LParenLoc,
13511                                           SourceLocation EndLoc) {
13512   SmallVector<Expr *, 8> Vars;
13513   SmallVector<Expr *, 8> PrivateCopies;
13514   for (Expr *RefExpr : VarList) {
13515     assert(RefExpr && "NULL expr in OpenMP private clause.");
13516     SourceLocation ELoc;
13517     SourceRange ERange;
13518     Expr *SimpleRefExpr = RefExpr;
13519     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13520     if (Res.second) {
13521       // It will be analyzed later.
13522       Vars.push_back(RefExpr);
13523       PrivateCopies.push_back(nullptr);
13524     }
13525     ValueDecl *D = Res.first;
13526     if (!D)
13527       continue;
13528 
13529     QualType Type = D->getType();
13530     auto *VD = dyn_cast<VarDecl>(D);
13531 
13532     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13533     //  A variable that appears in a private clause must not have an incomplete
13534     //  type or a reference type.
13535     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
13536       continue;
13537     Type = Type.getNonReferenceType();
13538 
13539     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13540     // A variable that is privatized must not have a const-qualified type
13541     // unless it is of class type with a mutable member. This restriction does
13542     // not apply to the firstprivate clause.
13543     //
13544     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
13545     // A variable that appears in a private clause must not have a
13546     // const-qualified type unless it is of class type with a mutable member.
13547     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
13548       continue;
13549 
13550     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13551     // in a Construct]
13552     //  Variables with the predetermined data-sharing attributes may not be
13553     //  listed in data-sharing attributes clauses, except for the cases
13554     //  listed below. For these exceptions only, listing a predetermined
13555     //  variable in a data-sharing attribute clause is allowed and overrides
13556     //  the variable's predetermined data-sharing attributes.
13557     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13558     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
13559       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13560                                           << getOpenMPClauseName(OMPC_private);
13561       reportOriginalDsa(*this, DSAStack, D, DVar);
13562       continue;
13563     }
13564 
13565     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
13566     // Variably modified types are not supported for tasks.
13567     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
13568         isOpenMPTaskingDirective(CurrDir)) {
13569       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13570           << getOpenMPClauseName(OMPC_private) << Type
13571           << getOpenMPDirectiveName(CurrDir);
13572       bool IsDecl =
13573           !VD ||
13574           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13575       Diag(D->getLocation(),
13576            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13577           << D;
13578       continue;
13579     }
13580 
13581     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13582     // A list item cannot appear in both a map clause and a data-sharing
13583     // attribute clause on the same construct
13584     //
13585     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13586     // A list item cannot appear in both a map clause and a data-sharing
13587     // attribute clause on the same construct unless the construct is a
13588     // combined construct.
13589     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
13590         CurrDir == OMPD_target) {
13591       OpenMPClauseKind ConflictKind;
13592       if (DSAStack->checkMappableExprComponentListsForDecl(
13593               VD, /*CurrentRegionOnly=*/true,
13594               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
13595                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
13596                 ConflictKind = WhereFoundClauseKind;
13597                 return true;
13598               })) {
13599         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13600             << getOpenMPClauseName(OMPC_private)
13601             << getOpenMPClauseName(ConflictKind)
13602             << getOpenMPDirectiveName(CurrDir);
13603         reportOriginalDsa(*this, DSAStack, D, DVar);
13604         continue;
13605       }
13606     }
13607 
13608     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
13609     //  A variable of class type (or array thereof) that appears in a private
13610     //  clause requires an accessible, unambiguous default constructor for the
13611     //  class type.
13612     // Generate helper private variable and initialize it with the default
13613     // value. The address of the original variable is replaced by the address of
13614     // the new private variable in CodeGen. This new variable is not added to
13615     // IdResolver, so the code in the OpenMP region uses original variable for
13616     // proper diagnostics.
13617     Type = Type.getUnqualifiedType();
13618     VarDecl *VDPrivate =
13619         buildVarDecl(*this, ELoc, Type, D->getName(),
13620                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13621                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13622     ActOnUninitializedDecl(VDPrivate);
13623     if (VDPrivate->isInvalidDecl())
13624       continue;
13625     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13626         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13627 
13628     DeclRefExpr *Ref = nullptr;
13629     if (!VD && !CurContext->isDependentContext())
13630       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
13631     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
13632     Vars.push_back((VD || CurContext->isDependentContext())
13633                        ? RefExpr->IgnoreParens()
13634                        : Ref);
13635     PrivateCopies.push_back(VDPrivateRefExpr);
13636   }
13637 
13638   if (Vars.empty())
13639     return nullptr;
13640 
13641   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
13642                                   PrivateCopies);
13643 }
13644 
13645 namespace {
13646 class DiagsUninitializedSeveretyRAII {
13647 private:
13648   DiagnosticsEngine &Diags;
13649   SourceLocation SavedLoc;
13650   bool IsIgnored = false;
13651 
13652 public:
13653   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
13654                                  bool IsIgnored)
13655       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
13656     if (!IsIgnored) {
13657       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
13658                         /*Map*/ diag::Severity::Ignored, Loc);
13659     }
13660   }
13661   ~DiagsUninitializedSeveretyRAII() {
13662     if (!IsIgnored)
13663       Diags.popMappings(SavedLoc);
13664   }
13665 };
13666 }
13667 
13668 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
13669                                                SourceLocation StartLoc,
13670                                                SourceLocation LParenLoc,
13671                                                SourceLocation EndLoc) {
13672   SmallVector<Expr *, 8> Vars;
13673   SmallVector<Expr *, 8> PrivateCopies;
13674   SmallVector<Expr *, 8> Inits;
13675   SmallVector<Decl *, 4> ExprCaptures;
13676   bool IsImplicitClause =
13677       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
13678   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
13679 
13680   for (Expr *RefExpr : VarList) {
13681     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
13682     SourceLocation ELoc;
13683     SourceRange ERange;
13684     Expr *SimpleRefExpr = RefExpr;
13685     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13686     if (Res.second) {
13687       // It will be analyzed later.
13688       Vars.push_back(RefExpr);
13689       PrivateCopies.push_back(nullptr);
13690       Inits.push_back(nullptr);
13691     }
13692     ValueDecl *D = Res.first;
13693     if (!D)
13694       continue;
13695 
13696     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
13697     QualType Type = D->getType();
13698     auto *VD = dyn_cast<VarDecl>(D);
13699 
13700     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13701     //  A variable that appears in a private clause must not have an incomplete
13702     //  type or a reference type.
13703     if (RequireCompleteType(ELoc, Type,
13704                             diag::err_omp_firstprivate_incomplete_type))
13705       continue;
13706     Type = Type.getNonReferenceType();
13707 
13708     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
13709     //  A variable of class type (or array thereof) that appears in a private
13710     //  clause requires an accessible, unambiguous copy constructor for the
13711     //  class type.
13712     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
13713 
13714     // If an implicit firstprivate variable found it was checked already.
13715     DSAStackTy::DSAVarData TopDVar;
13716     if (!IsImplicitClause) {
13717       DSAStackTy::DSAVarData DVar =
13718           DSAStack->getTopDSA(D, /*FromParent=*/false);
13719       TopDVar = DVar;
13720       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
13721       bool IsConstant = ElemType.isConstant(Context);
13722       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
13723       //  A list item that specifies a given variable may not appear in more
13724       // than one clause on the same directive, except that a variable may be
13725       //  specified in both firstprivate and lastprivate clauses.
13726       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13727       // A list item may appear in a firstprivate or lastprivate clause but not
13728       // both.
13729       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
13730           (isOpenMPDistributeDirective(CurrDir) ||
13731            DVar.CKind != OMPC_lastprivate) &&
13732           DVar.RefExpr) {
13733         Diag(ELoc, diag::err_omp_wrong_dsa)
13734             << getOpenMPClauseName(DVar.CKind)
13735             << getOpenMPClauseName(OMPC_firstprivate);
13736         reportOriginalDsa(*this, DSAStack, D, DVar);
13737         continue;
13738       }
13739 
13740       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13741       // in a Construct]
13742       //  Variables with the predetermined data-sharing attributes may not be
13743       //  listed in data-sharing attributes clauses, except for the cases
13744       //  listed below. For these exceptions only, listing a predetermined
13745       //  variable in a data-sharing attribute clause is allowed and overrides
13746       //  the variable's predetermined data-sharing attributes.
13747       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13748       // in a Construct, C/C++, p.2]
13749       //  Variables with const-qualified type having no mutable member may be
13750       //  listed in a firstprivate clause, even if they are static data members.
13751       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
13752           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
13753         Diag(ELoc, diag::err_omp_wrong_dsa)
13754             << getOpenMPClauseName(DVar.CKind)
13755             << getOpenMPClauseName(OMPC_firstprivate);
13756         reportOriginalDsa(*this, DSAStack, D, DVar);
13757         continue;
13758       }
13759 
13760       // OpenMP [2.9.3.4, Restrictions, p.2]
13761       //  A list item that is private within a parallel region must not appear
13762       //  in a firstprivate clause on a worksharing construct if any of the
13763       //  worksharing regions arising from the worksharing construct ever bind
13764       //  to any of the parallel regions arising from the parallel construct.
13765       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13766       // A list item that is private within a teams region must not appear in a
13767       // firstprivate clause on a distribute construct if any of the distribute
13768       // regions arising from the distribute construct ever bind to any of the
13769       // teams regions arising from the teams construct.
13770       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13771       // A list item that appears in a reduction clause of a teams construct
13772       // must not appear in a firstprivate clause on a distribute construct if
13773       // any of the distribute regions arising from the distribute construct
13774       // ever bind to any of the teams regions arising from the teams construct.
13775       if ((isOpenMPWorksharingDirective(CurrDir) ||
13776            isOpenMPDistributeDirective(CurrDir)) &&
13777           !isOpenMPParallelDirective(CurrDir) &&
13778           !isOpenMPTeamsDirective(CurrDir)) {
13779         DVar = DSAStack->getImplicitDSA(D, true);
13780         if (DVar.CKind != OMPC_shared &&
13781             (isOpenMPParallelDirective(DVar.DKind) ||
13782              isOpenMPTeamsDirective(DVar.DKind) ||
13783              DVar.DKind == OMPD_unknown)) {
13784           Diag(ELoc, diag::err_omp_required_access)
13785               << getOpenMPClauseName(OMPC_firstprivate)
13786               << getOpenMPClauseName(OMPC_shared);
13787           reportOriginalDsa(*this, DSAStack, D, DVar);
13788           continue;
13789         }
13790       }
13791       // OpenMP [2.9.3.4, Restrictions, p.3]
13792       //  A list item that appears in a reduction clause of a parallel construct
13793       //  must not appear in a firstprivate clause on a worksharing or task
13794       //  construct if any of the worksharing or task regions arising from the
13795       //  worksharing or task construct ever bind to any of the parallel regions
13796       //  arising from the parallel construct.
13797       // OpenMP [2.9.3.4, Restrictions, p.4]
13798       //  A list item that appears in a reduction clause in worksharing
13799       //  construct must not appear in a firstprivate clause in a task construct
13800       //  encountered during execution of any of the worksharing regions arising
13801       //  from the worksharing construct.
13802       if (isOpenMPTaskingDirective(CurrDir)) {
13803         DVar = DSAStack->hasInnermostDSA(
13804             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
13805             [](OpenMPDirectiveKind K) {
13806               return isOpenMPParallelDirective(K) ||
13807                      isOpenMPWorksharingDirective(K) ||
13808                      isOpenMPTeamsDirective(K);
13809             },
13810             /*FromParent=*/true);
13811         if (DVar.CKind == OMPC_reduction &&
13812             (isOpenMPParallelDirective(DVar.DKind) ||
13813              isOpenMPWorksharingDirective(DVar.DKind) ||
13814              isOpenMPTeamsDirective(DVar.DKind))) {
13815           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
13816               << getOpenMPDirectiveName(DVar.DKind);
13817           reportOriginalDsa(*this, DSAStack, D, DVar);
13818           continue;
13819         }
13820       }
13821 
13822       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13823       // A list item cannot appear in both a map clause and a data-sharing
13824       // attribute clause on the same construct
13825       //
13826       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13827       // A list item cannot appear in both a map clause and a data-sharing
13828       // attribute clause on the same construct unless the construct is a
13829       // combined construct.
13830       if ((LangOpts.OpenMP <= 45 &&
13831            isOpenMPTargetExecutionDirective(CurrDir)) ||
13832           CurrDir == OMPD_target) {
13833         OpenMPClauseKind ConflictKind;
13834         if (DSAStack->checkMappableExprComponentListsForDecl(
13835                 VD, /*CurrentRegionOnly=*/true,
13836                 [&ConflictKind](
13837                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
13838                     OpenMPClauseKind WhereFoundClauseKind) {
13839                   ConflictKind = WhereFoundClauseKind;
13840                   return true;
13841                 })) {
13842           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13843               << getOpenMPClauseName(OMPC_firstprivate)
13844               << getOpenMPClauseName(ConflictKind)
13845               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13846           reportOriginalDsa(*this, DSAStack, D, DVar);
13847           continue;
13848         }
13849       }
13850     }
13851 
13852     // Variably modified types are not supported for tasks.
13853     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
13854         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
13855       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13856           << getOpenMPClauseName(OMPC_firstprivate) << Type
13857           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13858       bool IsDecl =
13859           !VD ||
13860           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13861       Diag(D->getLocation(),
13862            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13863           << D;
13864       continue;
13865     }
13866 
13867     Type = Type.getUnqualifiedType();
13868     VarDecl *VDPrivate =
13869         buildVarDecl(*this, ELoc, Type, D->getName(),
13870                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13871                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13872     // Generate helper private variable and initialize it with the value of the
13873     // original variable. The address of the original variable is replaced by
13874     // the address of the new private variable in the CodeGen. This new variable
13875     // is not added to IdResolver, so the code in the OpenMP region uses
13876     // original variable for proper diagnostics and variable capturing.
13877     Expr *VDInitRefExpr = nullptr;
13878     // For arrays generate initializer for single element and replace it by the
13879     // original array element in CodeGen.
13880     if (Type->isArrayType()) {
13881       VarDecl *VDInit =
13882           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
13883       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
13884       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
13885       ElemType = ElemType.getUnqualifiedType();
13886       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
13887                                          ".firstprivate.temp");
13888       InitializedEntity Entity =
13889           InitializedEntity::InitializeVariable(VDInitTemp);
13890       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
13891 
13892       InitializationSequence InitSeq(*this, Entity, Kind, Init);
13893       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
13894       if (Result.isInvalid())
13895         VDPrivate->setInvalidDecl();
13896       else
13897         VDPrivate->setInit(Result.getAs<Expr>());
13898       // Remove temp variable declaration.
13899       Context.Deallocate(VDInitTemp);
13900     } else {
13901       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
13902                                      ".firstprivate.temp");
13903       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13904                                        RefExpr->getExprLoc());
13905       AddInitializerToDecl(VDPrivate,
13906                            DefaultLvalueConversion(VDInitRefExpr).get(),
13907                            /*DirectInit=*/false);
13908     }
13909     if (VDPrivate->isInvalidDecl()) {
13910       if (IsImplicitClause) {
13911         Diag(RefExpr->getExprLoc(),
13912              diag::note_omp_task_predetermined_firstprivate_here);
13913       }
13914       continue;
13915     }
13916     CurContext->addDecl(VDPrivate);
13917     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13918         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
13919         RefExpr->getExprLoc());
13920     DeclRefExpr *Ref = nullptr;
13921     if (!VD && !CurContext->isDependentContext()) {
13922       if (TopDVar.CKind == OMPC_lastprivate) {
13923         Ref = TopDVar.PrivateCopy;
13924       } else {
13925         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13926         if (!isOpenMPCapturedDecl(D))
13927           ExprCaptures.push_back(Ref->getDecl());
13928       }
13929     }
13930     if (!IsImplicitClause)
13931       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13932     Vars.push_back((VD || CurContext->isDependentContext())
13933                        ? RefExpr->IgnoreParens()
13934                        : Ref);
13935     PrivateCopies.push_back(VDPrivateRefExpr);
13936     Inits.push_back(VDInitRefExpr);
13937   }
13938 
13939   if (Vars.empty())
13940     return nullptr;
13941 
13942   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13943                                        Vars, PrivateCopies, Inits,
13944                                        buildPreInits(Context, ExprCaptures));
13945 }
13946 
13947 OMPClause *Sema::ActOnOpenMPLastprivateClause(
13948     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13949     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13950     SourceLocation LParenLoc, SourceLocation EndLoc) {
13951   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13952     assert(ColonLoc.isValid() && "Colon location must be valid.");
13953     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13954         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13955                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
13956         << getOpenMPClauseName(OMPC_lastprivate);
13957     return nullptr;
13958   }
13959 
13960   SmallVector<Expr *, 8> Vars;
13961   SmallVector<Expr *, 8> SrcExprs;
13962   SmallVector<Expr *, 8> DstExprs;
13963   SmallVector<Expr *, 8> AssignmentOps;
13964   SmallVector<Decl *, 4> ExprCaptures;
13965   SmallVector<Expr *, 4> ExprPostUpdates;
13966   for (Expr *RefExpr : VarList) {
13967     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
13968     SourceLocation ELoc;
13969     SourceRange ERange;
13970     Expr *SimpleRefExpr = RefExpr;
13971     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13972     if (Res.second) {
13973       // It will be analyzed later.
13974       Vars.push_back(RefExpr);
13975       SrcExprs.push_back(nullptr);
13976       DstExprs.push_back(nullptr);
13977       AssignmentOps.push_back(nullptr);
13978     }
13979     ValueDecl *D = Res.first;
13980     if (!D)
13981       continue;
13982 
13983     QualType Type = D->getType();
13984     auto *VD = dyn_cast<VarDecl>(D);
13985 
13986     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13987     //  A variable that appears in a lastprivate clause must not have an
13988     //  incomplete type or a reference type.
13989     if (RequireCompleteType(ELoc, Type,
13990                             diag::err_omp_lastprivate_incomplete_type))
13991       continue;
13992     Type = Type.getNonReferenceType();
13993 
13994     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13995     // A variable that is privatized must not have a const-qualified type
13996     // unless it is of class type with a mutable member. This restriction does
13997     // not apply to the firstprivate clause.
13998     //
13999     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
14000     // A variable that appears in a lastprivate clause must not have a
14001     // const-qualified type unless it is of class type with a mutable member.
14002     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
14003       continue;
14004 
14005     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
14006     // A list item that appears in a lastprivate clause with the conditional
14007     // modifier must be a scalar variable.
14008     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
14009       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
14010       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14011                                VarDecl::DeclarationOnly;
14012       Diag(D->getLocation(),
14013            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14014           << D;
14015       continue;
14016     }
14017 
14018     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
14019     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14020     // in a Construct]
14021     //  Variables with the predetermined data-sharing attributes may not be
14022     //  listed in data-sharing attributes clauses, except for the cases
14023     //  listed below.
14024     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
14025     // A list item may appear in a firstprivate or lastprivate clause but not
14026     // both.
14027     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14028     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
14029         (isOpenMPDistributeDirective(CurrDir) ||
14030          DVar.CKind != OMPC_firstprivate) &&
14031         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
14032       Diag(ELoc, diag::err_omp_wrong_dsa)
14033           << getOpenMPClauseName(DVar.CKind)
14034           << getOpenMPClauseName(OMPC_lastprivate);
14035       reportOriginalDsa(*this, DSAStack, D, DVar);
14036       continue;
14037     }
14038 
14039     // OpenMP [2.14.3.5, Restrictions, p.2]
14040     // A list item that is private within a parallel region, or that appears in
14041     // the reduction clause of a parallel construct, must not appear in a
14042     // lastprivate clause on a worksharing construct if any of the corresponding
14043     // worksharing regions ever binds to any of the corresponding parallel
14044     // regions.
14045     DSAStackTy::DSAVarData TopDVar = DVar;
14046     if (isOpenMPWorksharingDirective(CurrDir) &&
14047         !isOpenMPParallelDirective(CurrDir) &&
14048         !isOpenMPTeamsDirective(CurrDir)) {
14049       DVar = DSAStack->getImplicitDSA(D, true);
14050       if (DVar.CKind != OMPC_shared) {
14051         Diag(ELoc, diag::err_omp_required_access)
14052             << getOpenMPClauseName(OMPC_lastprivate)
14053             << getOpenMPClauseName(OMPC_shared);
14054         reportOriginalDsa(*this, DSAStack, D, DVar);
14055         continue;
14056       }
14057     }
14058 
14059     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
14060     //  A variable of class type (or array thereof) that appears in a
14061     //  lastprivate clause requires an accessible, unambiguous default
14062     //  constructor for the class type, unless the list item is also specified
14063     //  in a firstprivate clause.
14064     //  A variable of class type (or array thereof) that appears in a
14065     //  lastprivate clause requires an accessible, unambiguous copy assignment
14066     //  operator for the class type.
14067     Type = Context.getBaseElementType(Type).getNonReferenceType();
14068     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
14069                                   Type.getUnqualifiedType(), ".lastprivate.src",
14070                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
14071     DeclRefExpr *PseudoSrcExpr =
14072         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
14073     VarDecl *DstVD =
14074         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
14075                      D->hasAttrs() ? &D->getAttrs() : nullptr);
14076     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14077     // For arrays generate assignment operation for single element and replace
14078     // it by the original array element in CodeGen.
14079     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
14080                                          PseudoDstExpr, PseudoSrcExpr);
14081     if (AssignmentOp.isInvalid())
14082       continue;
14083     AssignmentOp =
14084         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
14085     if (AssignmentOp.isInvalid())
14086       continue;
14087 
14088     DeclRefExpr *Ref = nullptr;
14089     if (!VD && !CurContext->isDependentContext()) {
14090       if (TopDVar.CKind == OMPC_firstprivate) {
14091         Ref = TopDVar.PrivateCopy;
14092       } else {
14093         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14094         if (!isOpenMPCapturedDecl(D))
14095           ExprCaptures.push_back(Ref->getDecl());
14096       }
14097       if (TopDVar.CKind == OMPC_firstprivate ||
14098           (!isOpenMPCapturedDecl(D) &&
14099            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
14100         ExprResult RefRes = DefaultLvalueConversion(Ref);
14101         if (!RefRes.isUsable())
14102           continue;
14103         ExprResult PostUpdateRes =
14104             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14105                        RefRes.get());
14106         if (!PostUpdateRes.isUsable())
14107           continue;
14108         ExprPostUpdates.push_back(
14109             IgnoredValueConversions(PostUpdateRes.get()).get());
14110       }
14111     }
14112     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
14113     Vars.push_back((VD || CurContext->isDependentContext())
14114                        ? RefExpr->IgnoreParens()
14115                        : Ref);
14116     SrcExprs.push_back(PseudoSrcExpr);
14117     DstExprs.push_back(PseudoDstExpr);
14118     AssignmentOps.push_back(AssignmentOp.get());
14119   }
14120 
14121   if (Vars.empty())
14122     return nullptr;
14123 
14124   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14125                                       Vars, SrcExprs, DstExprs, AssignmentOps,
14126                                       LPKind, LPKindLoc, ColonLoc,
14127                                       buildPreInits(Context, ExprCaptures),
14128                                       buildPostUpdate(*this, ExprPostUpdates));
14129 }
14130 
14131 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
14132                                          SourceLocation StartLoc,
14133                                          SourceLocation LParenLoc,
14134                                          SourceLocation EndLoc) {
14135   SmallVector<Expr *, 8> Vars;
14136   for (Expr *RefExpr : VarList) {
14137     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14138     SourceLocation ELoc;
14139     SourceRange ERange;
14140     Expr *SimpleRefExpr = RefExpr;
14141     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14142     if (Res.second) {
14143       // It will be analyzed later.
14144       Vars.push_back(RefExpr);
14145     }
14146     ValueDecl *D = Res.first;
14147     if (!D)
14148       continue;
14149 
14150     auto *VD = dyn_cast<VarDecl>(D);
14151     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14152     // in a Construct]
14153     //  Variables with the predetermined data-sharing attributes may not be
14154     //  listed in data-sharing attributes clauses, except for the cases
14155     //  listed below. For these exceptions only, listing a predetermined
14156     //  variable in a data-sharing attribute clause is allowed and overrides
14157     //  the variable's predetermined data-sharing attributes.
14158     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14159     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
14160         DVar.RefExpr) {
14161       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14162                                           << getOpenMPClauseName(OMPC_shared);
14163       reportOriginalDsa(*this, DSAStack, D, DVar);
14164       continue;
14165     }
14166 
14167     DeclRefExpr *Ref = nullptr;
14168     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
14169       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14170     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
14171     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
14172                        ? RefExpr->IgnoreParens()
14173                        : Ref);
14174   }
14175 
14176   if (Vars.empty())
14177     return nullptr;
14178 
14179   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
14180 }
14181 
14182 namespace {
14183 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
14184   DSAStackTy *Stack;
14185 
14186 public:
14187   bool VisitDeclRefExpr(DeclRefExpr *E) {
14188     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
14189       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
14190       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
14191         return false;
14192       if (DVar.CKind != OMPC_unknown)
14193         return true;
14194       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
14195           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
14196           /*FromParent=*/true);
14197       return DVarPrivate.CKind != OMPC_unknown;
14198     }
14199     return false;
14200   }
14201   bool VisitStmt(Stmt *S) {
14202     for (Stmt *Child : S->children()) {
14203       if (Child && Visit(Child))
14204         return true;
14205     }
14206     return false;
14207   }
14208   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
14209 };
14210 } // namespace
14211 
14212 namespace {
14213 // Transform MemberExpression for specified FieldDecl of current class to
14214 // DeclRefExpr to specified OMPCapturedExprDecl.
14215 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
14216   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
14217   ValueDecl *Field = nullptr;
14218   DeclRefExpr *CapturedExpr = nullptr;
14219 
14220 public:
14221   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
14222       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
14223 
14224   ExprResult TransformMemberExpr(MemberExpr *E) {
14225     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
14226         E->getMemberDecl() == Field) {
14227       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
14228       return CapturedExpr;
14229     }
14230     return BaseTransform::TransformMemberExpr(E);
14231   }
14232   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
14233 };
14234 } // namespace
14235 
14236 template <typename T, typename U>
14237 static T filterLookupForUDReductionAndMapper(
14238     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
14239   for (U &Set : Lookups) {
14240     for (auto *D : Set) {
14241       if (T Res = Gen(cast<ValueDecl>(D)))
14242         return Res;
14243     }
14244   }
14245   return T();
14246 }
14247 
14248 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
14249   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
14250 
14251   for (auto RD : D->redecls()) {
14252     // Don't bother with extra checks if we already know this one isn't visible.
14253     if (RD == D)
14254       continue;
14255 
14256     auto ND = cast<NamedDecl>(RD);
14257     if (LookupResult::isVisible(SemaRef, ND))
14258       return ND;
14259   }
14260 
14261   return nullptr;
14262 }
14263 
14264 static void
14265 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
14266                         SourceLocation Loc, QualType Ty,
14267                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
14268   // Find all of the associated namespaces and classes based on the
14269   // arguments we have.
14270   Sema::AssociatedNamespaceSet AssociatedNamespaces;
14271   Sema::AssociatedClassSet AssociatedClasses;
14272   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
14273   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
14274                                              AssociatedClasses);
14275 
14276   // C++ [basic.lookup.argdep]p3:
14277   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
14278   //   and let Y be the lookup set produced by argument dependent
14279   //   lookup (defined as follows). If X contains [...] then Y is
14280   //   empty. Otherwise Y is the set of declarations found in the
14281   //   namespaces associated with the argument types as described
14282   //   below. The set of declarations found by the lookup of the name
14283   //   is the union of X and Y.
14284   //
14285   // Here, we compute Y and add its members to the overloaded
14286   // candidate set.
14287   for (auto *NS : AssociatedNamespaces) {
14288     //   When considering an associated namespace, the lookup is the
14289     //   same as the lookup performed when the associated namespace is
14290     //   used as a qualifier (3.4.3.2) except that:
14291     //
14292     //     -- Any using-directives in the associated namespace are
14293     //        ignored.
14294     //
14295     //     -- Any namespace-scope friend functions declared in
14296     //        associated classes are visible within their respective
14297     //        namespaces even if they are not visible during an ordinary
14298     //        lookup (11.4).
14299     DeclContext::lookup_result R = NS->lookup(Id.getName());
14300     for (auto *D : R) {
14301       auto *Underlying = D;
14302       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14303         Underlying = USD->getTargetDecl();
14304 
14305       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
14306           !isa<OMPDeclareMapperDecl>(Underlying))
14307         continue;
14308 
14309       if (!SemaRef.isVisible(D)) {
14310         D = findAcceptableDecl(SemaRef, D);
14311         if (!D)
14312           continue;
14313         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14314           Underlying = USD->getTargetDecl();
14315       }
14316       Lookups.emplace_back();
14317       Lookups.back().addDecl(Underlying);
14318     }
14319   }
14320 }
14321 
14322 static ExprResult
14323 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
14324                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
14325                          const DeclarationNameInfo &ReductionId, QualType Ty,
14326                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
14327   if (ReductionIdScopeSpec.isInvalid())
14328     return ExprError();
14329   SmallVector<UnresolvedSet<8>, 4> Lookups;
14330   if (S) {
14331     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14332     Lookup.suppressDiagnostics();
14333     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
14334       NamedDecl *D = Lookup.getRepresentativeDecl();
14335       do {
14336         S = S->getParent();
14337       } while (S && !S->isDeclScope(D));
14338       if (S)
14339         S = S->getParent();
14340       Lookups.emplace_back();
14341       Lookups.back().append(Lookup.begin(), Lookup.end());
14342       Lookup.clear();
14343     }
14344   } else if (auto *ULE =
14345                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
14346     Lookups.push_back(UnresolvedSet<8>());
14347     Decl *PrevD = nullptr;
14348     for (NamedDecl *D : ULE->decls()) {
14349       if (D == PrevD)
14350         Lookups.push_back(UnresolvedSet<8>());
14351       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
14352         Lookups.back().addDecl(DRD);
14353       PrevD = D;
14354     }
14355   }
14356   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
14357       Ty->isInstantiationDependentType() ||
14358       Ty->containsUnexpandedParameterPack() ||
14359       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
14360         return !D->isInvalidDecl() &&
14361                (D->getType()->isDependentType() ||
14362                 D->getType()->isInstantiationDependentType() ||
14363                 D->getType()->containsUnexpandedParameterPack());
14364       })) {
14365     UnresolvedSet<8> ResSet;
14366     for (const UnresolvedSet<8> &Set : Lookups) {
14367       if (Set.empty())
14368         continue;
14369       ResSet.append(Set.begin(), Set.end());
14370       // The last item marks the end of all declarations at the specified scope.
14371       ResSet.addDecl(Set[Set.size() - 1]);
14372     }
14373     return UnresolvedLookupExpr::Create(
14374         SemaRef.Context, /*NamingClass=*/nullptr,
14375         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
14376         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
14377   }
14378   // Lookup inside the classes.
14379   // C++ [over.match.oper]p3:
14380   //   For a unary operator @ with an operand of a type whose
14381   //   cv-unqualified version is T1, and for a binary operator @ with
14382   //   a left operand of a type whose cv-unqualified version is T1 and
14383   //   a right operand of a type whose cv-unqualified version is T2,
14384   //   three sets of candidate functions, designated member
14385   //   candidates, non-member candidates and built-in candidates, are
14386   //   constructed as follows:
14387   //     -- If T1 is a complete class type or a class currently being
14388   //        defined, the set of member candidates is the result of the
14389   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
14390   //        the set of member candidates is empty.
14391   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14392   Lookup.suppressDiagnostics();
14393   if (const auto *TyRec = Ty->getAs<RecordType>()) {
14394     // Complete the type if it can be completed.
14395     // If the type is neither complete nor being defined, bail out now.
14396     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
14397         TyRec->getDecl()->getDefinition()) {
14398       Lookup.clear();
14399       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
14400       if (Lookup.empty()) {
14401         Lookups.emplace_back();
14402         Lookups.back().append(Lookup.begin(), Lookup.end());
14403       }
14404     }
14405   }
14406   // Perform ADL.
14407   if (SemaRef.getLangOpts().CPlusPlus)
14408     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
14409   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14410           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
14411             if (!D->isInvalidDecl() &&
14412                 SemaRef.Context.hasSameType(D->getType(), Ty))
14413               return D;
14414             return nullptr;
14415           }))
14416     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
14417                                     VK_LValue, Loc);
14418   if (SemaRef.getLangOpts().CPlusPlus) {
14419     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14420             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
14421               if (!D->isInvalidDecl() &&
14422                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
14423                   !Ty.isMoreQualifiedThan(D->getType()))
14424                 return D;
14425               return nullptr;
14426             })) {
14427       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
14428                          /*DetectVirtual=*/false);
14429       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
14430         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
14431                 VD->getType().getUnqualifiedType()))) {
14432           if (SemaRef.CheckBaseClassAccess(
14433                   Loc, VD->getType(), Ty, Paths.front(),
14434                   /*DiagID=*/0) != Sema::AR_inaccessible) {
14435             SemaRef.BuildBasePathArray(Paths, BasePath);
14436             return SemaRef.BuildDeclRefExpr(
14437                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
14438           }
14439         }
14440       }
14441     }
14442   }
14443   if (ReductionIdScopeSpec.isSet()) {
14444     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
14445         << Ty << Range;
14446     return ExprError();
14447   }
14448   return ExprEmpty();
14449 }
14450 
14451 namespace {
14452 /// Data for the reduction-based clauses.
14453 struct ReductionData {
14454   /// List of original reduction items.
14455   SmallVector<Expr *, 8> Vars;
14456   /// List of private copies of the reduction items.
14457   SmallVector<Expr *, 8> Privates;
14458   /// LHS expressions for the reduction_op expressions.
14459   SmallVector<Expr *, 8> LHSs;
14460   /// RHS expressions for the reduction_op expressions.
14461   SmallVector<Expr *, 8> RHSs;
14462   /// Reduction operation expression.
14463   SmallVector<Expr *, 8> ReductionOps;
14464   /// Taskgroup descriptors for the corresponding reduction items in
14465   /// in_reduction clauses.
14466   SmallVector<Expr *, 8> TaskgroupDescriptors;
14467   /// List of captures for clause.
14468   SmallVector<Decl *, 4> ExprCaptures;
14469   /// List of postupdate expressions.
14470   SmallVector<Expr *, 4> ExprPostUpdates;
14471   /// Reduction modifier.
14472   unsigned RedModifier = 0;
14473   ReductionData() = delete;
14474   /// Reserves required memory for the reduction data.
14475   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
14476     Vars.reserve(Size);
14477     Privates.reserve(Size);
14478     LHSs.reserve(Size);
14479     RHSs.reserve(Size);
14480     ReductionOps.reserve(Size);
14481     TaskgroupDescriptors.reserve(Size);
14482     ExprCaptures.reserve(Size);
14483     ExprPostUpdates.reserve(Size);
14484   }
14485   /// Stores reduction item and reduction operation only (required for dependent
14486   /// reduction item).
14487   void push(Expr *Item, Expr *ReductionOp) {
14488     Vars.emplace_back(Item);
14489     Privates.emplace_back(nullptr);
14490     LHSs.emplace_back(nullptr);
14491     RHSs.emplace_back(nullptr);
14492     ReductionOps.emplace_back(ReductionOp);
14493     TaskgroupDescriptors.emplace_back(nullptr);
14494   }
14495   /// Stores reduction data.
14496   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
14497             Expr *TaskgroupDescriptor) {
14498     Vars.emplace_back(Item);
14499     Privates.emplace_back(Private);
14500     LHSs.emplace_back(LHS);
14501     RHSs.emplace_back(RHS);
14502     ReductionOps.emplace_back(ReductionOp);
14503     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
14504   }
14505 };
14506 } // namespace
14507 
14508 static bool checkOMPArraySectionConstantForReduction(
14509     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
14510     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
14511   const Expr *Length = OASE->getLength();
14512   if (Length == nullptr) {
14513     // For array sections of the form [1:] or [:], we would need to analyze
14514     // the lower bound...
14515     if (OASE->getColonLoc().isValid())
14516       return false;
14517 
14518     // This is an array subscript which has implicit length 1!
14519     SingleElement = true;
14520     ArraySizes.push_back(llvm::APSInt::get(1));
14521   } else {
14522     Expr::EvalResult Result;
14523     if (!Length->EvaluateAsInt(Result, Context))
14524       return false;
14525 
14526     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
14527     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
14528     ArraySizes.push_back(ConstantLengthValue);
14529   }
14530 
14531   // Get the base of this array section and walk up from there.
14532   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
14533 
14534   // We require length = 1 for all array sections except the right-most to
14535   // guarantee that the memory region is contiguous and has no holes in it.
14536   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
14537     Length = TempOASE->getLength();
14538     if (Length == nullptr) {
14539       // For array sections of the form [1:] or [:], we would need to analyze
14540       // the lower bound...
14541       if (OASE->getColonLoc().isValid())
14542         return false;
14543 
14544       // This is an array subscript which has implicit length 1!
14545       ArraySizes.push_back(llvm::APSInt::get(1));
14546     } else {
14547       Expr::EvalResult Result;
14548       if (!Length->EvaluateAsInt(Result, Context))
14549         return false;
14550 
14551       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
14552       if (ConstantLengthValue.getSExtValue() != 1)
14553         return false;
14554 
14555       ArraySizes.push_back(ConstantLengthValue);
14556     }
14557     Base = TempOASE->getBase()->IgnoreParenImpCasts();
14558   }
14559 
14560   // If we have a single element, we don't need to add the implicit lengths.
14561   if (!SingleElement) {
14562     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
14563       // Has implicit length 1!
14564       ArraySizes.push_back(llvm::APSInt::get(1));
14565       Base = TempASE->getBase()->IgnoreParenImpCasts();
14566     }
14567   }
14568 
14569   // This array section can be privatized as a single value or as a constant
14570   // sized array.
14571   return true;
14572 }
14573 
14574 static bool actOnOMPReductionKindClause(
14575     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
14576     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14577     SourceLocation ColonLoc, SourceLocation EndLoc,
14578     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14579     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
14580   DeclarationName DN = ReductionId.getName();
14581   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
14582   BinaryOperatorKind BOK = BO_Comma;
14583 
14584   ASTContext &Context = S.Context;
14585   // OpenMP [2.14.3.6, reduction clause]
14586   // C
14587   // reduction-identifier is either an identifier or one of the following
14588   // operators: +, -, *,  &, |, ^, && and ||
14589   // C++
14590   // reduction-identifier is either an id-expression or one of the following
14591   // operators: +, -, *, &, |, ^, && and ||
14592   switch (OOK) {
14593   case OO_Plus:
14594   case OO_Minus:
14595     BOK = BO_Add;
14596     break;
14597   case OO_Star:
14598     BOK = BO_Mul;
14599     break;
14600   case OO_Amp:
14601     BOK = BO_And;
14602     break;
14603   case OO_Pipe:
14604     BOK = BO_Or;
14605     break;
14606   case OO_Caret:
14607     BOK = BO_Xor;
14608     break;
14609   case OO_AmpAmp:
14610     BOK = BO_LAnd;
14611     break;
14612   case OO_PipePipe:
14613     BOK = BO_LOr;
14614     break;
14615   case OO_New:
14616   case OO_Delete:
14617   case OO_Array_New:
14618   case OO_Array_Delete:
14619   case OO_Slash:
14620   case OO_Percent:
14621   case OO_Tilde:
14622   case OO_Exclaim:
14623   case OO_Equal:
14624   case OO_Less:
14625   case OO_Greater:
14626   case OO_LessEqual:
14627   case OO_GreaterEqual:
14628   case OO_PlusEqual:
14629   case OO_MinusEqual:
14630   case OO_StarEqual:
14631   case OO_SlashEqual:
14632   case OO_PercentEqual:
14633   case OO_CaretEqual:
14634   case OO_AmpEqual:
14635   case OO_PipeEqual:
14636   case OO_LessLess:
14637   case OO_GreaterGreater:
14638   case OO_LessLessEqual:
14639   case OO_GreaterGreaterEqual:
14640   case OO_EqualEqual:
14641   case OO_ExclaimEqual:
14642   case OO_Spaceship:
14643   case OO_PlusPlus:
14644   case OO_MinusMinus:
14645   case OO_Comma:
14646   case OO_ArrowStar:
14647   case OO_Arrow:
14648   case OO_Call:
14649   case OO_Subscript:
14650   case OO_Conditional:
14651   case OO_Coawait:
14652   case NUM_OVERLOADED_OPERATORS:
14653     llvm_unreachable("Unexpected reduction identifier");
14654   case OO_None:
14655     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
14656       if (II->isStr("max"))
14657         BOK = BO_GT;
14658       else if (II->isStr("min"))
14659         BOK = BO_LT;
14660     }
14661     break;
14662   }
14663   SourceRange ReductionIdRange;
14664   if (ReductionIdScopeSpec.isValid())
14665     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
14666   else
14667     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
14668   ReductionIdRange.setEnd(ReductionId.getEndLoc());
14669 
14670   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
14671   bool FirstIter = true;
14672   for (Expr *RefExpr : VarList) {
14673     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
14674     // OpenMP [2.1, C/C++]
14675     //  A list item is a variable or array section, subject to the restrictions
14676     //  specified in Section 2.4 on page 42 and in each of the sections
14677     // describing clauses and directives for which a list appears.
14678     // OpenMP  [2.14.3.3, Restrictions, p.1]
14679     //  A variable that is part of another variable (as an array or
14680     //  structure element) cannot appear in a private clause.
14681     if (!FirstIter && IR != ER)
14682       ++IR;
14683     FirstIter = false;
14684     SourceLocation ELoc;
14685     SourceRange ERange;
14686     Expr *SimpleRefExpr = RefExpr;
14687     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
14688                               /*AllowArraySection=*/true);
14689     if (Res.second) {
14690       // Try to find 'declare reduction' corresponding construct before using
14691       // builtin/overloaded operators.
14692       QualType Type = Context.DependentTy;
14693       CXXCastPath BasePath;
14694       ExprResult DeclareReductionRef = buildDeclareReductionRef(
14695           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
14696           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14697       Expr *ReductionOp = nullptr;
14698       if (S.CurContext->isDependentContext() &&
14699           (DeclareReductionRef.isUnset() ||
14700            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
14701         ReductionOp = DeclareReductionRef.get();
14702       // It will be analyzed later.
14703       RD.push(RefExpr, ReductionOp);
14704     }
14705     ValueDecl *D = Res.first;
14706     if (!D)
14707       continue;
14708 
14709     Expr *TaskgroupDescriptor = nullptr;
14710     QualType Type;
14711     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
14712     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
14713     if (ASE) {
14714       Type = ASE->getType().getNonReferenceType();
14715     } else if (OASE) {
14716       QualType BaseType =
14717           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
14718       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
14719         Type = ATy->getElementType();
14720       else
14721         Type = BaseType->getPointeeType();
14722       Type = Type.getNonReferenceType();
14723     } else {
14724       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
14725     }
14726     auto *VD = dyn_cast<VarDecl>(D);
14727 
14728     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14729     //  A variable that appears in a private clause must not have an incomplete
14730     //  type or a reference type.
14731     if (S.RequireCompleteType(ELoc, D->getType(),
14732                               diag::err_omp_reduction_incomplete_type))
14733       continue;
14734     // OpenMP [2.14.3.6, reduction clause, Restrictions]
14735     // A list item that appears in a reduction clause must not be
14736     // const-qualified.
14737     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
14738                                   /*AcceptIfMutable*/ false, ASE || OASE))
14739       continue;
14740 
14741     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
14742     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
14743     //  If a list-item is a reference type then it must bind to the same object
14744     //  for all threads of the team.
14745     if (!ASE && !OASE) {
14746       if (VD) {
14747         VarDecl *VDDef = VD->getDefinition();
14748         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
14749           DSARefChecker Check(Stack);
14750           if (Check.Visit(VDDef->getInit())) {
14751             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
14752                 << getOpenMPClauseName(ClauseKind) << ERange;
14753             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
14754             continue;
14755           }
14756         }
14757       }
14758 
14759       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14760       // in a Construct]
14761       //  Variables with the predetermined data-sharing attributes may not be
14762       //  listed in data-sharing attributes clauses, except for the cases
14763       //  listed below. For these exceptions only, listing a predetermined
14764       //  variable in a data-sharing attribute clause is allowed and overrides
14765       //  the variable's predetermined data-sharing attributes.
14766       // OpenMP [2.14.3.6, Restrictions, p.3]
14767       //  Any number of reduction clauses can be specified on the directive,
14768       //  but a list item can appear only once in the reduction clauses for that
14769       //  directive.
14770       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
14771       if (DVar.CKind == OMPC_reduction) {
14772         S.Diag(ELoc, diag::err_omp_once_referenced)
14773             << getOpenMPClauseName(ClauseKind);
14774         if (DVar.RefExpr)
14775           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
14776         continue;
14777       }
14778       if (DVar.CKind != OMPC_unknown) {
14779         S.Diag(ELoc, diag::err_omp_wrong_dsa)
14780             << getOpenMPClauseName(DVar.CKind)
14781             << getOpenMPClauseName(OMPC_reduction);
14782         reportOriginalDsa(S, Stack, D, DVar);
14783         continue;
14784       }
14785 
14786       // OpenMP [2.14.3.6, Restrictions, p.1]
14787       //  A list item that appears in a reduction clause of a worksharing
14788       //  construct must be shared in the parallel regions to which any of the
14789       //  worksharing regions arising from the worksharing construct bind.
14790       if (isOpenMPWorksharingDirective(CurrDir) &&
14791           !isOpenMPParallelDirective(CurrDir) &&
14792           !isOpenMPTeamsDirective(CurrDir)) {
14793         DVar = Stack->getImplicitDSA(D, true);
14794         if (DVar.CKind != OMPC_shared) {
14795           S.Diag(ELoc, diag::err_omp_required_access)
14796               << getOpenMPClauseName(OMPC_reduction)
14797               << getOpenMPClauseName(OMPC_shared);
14798           reportOriginalDsa(S, Stack, D, DVar);
14799           continue;
14800         }
14801       }
14802     }
14803 
14804     // Try to find 'declare reduction' corresponding construct before using
14805     // builtin/overloaded operators.
14806     CXXCastPath BasePath;
14807     ExprResult DeclareReductionRef = buildDeclareReductionRef(
14808         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
14809         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14810     if (DeclareReductionRef.isInvalid())
14811       continue;
14812     if (S.CurContext->isDependentContext() &&
14813         (DeclareReductionRef.isUnset() ||
14814          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
14815       RD.push(RefExpr, DeclareReductionRef.get());
14816       continue;
14817     }
14818     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
14819       // Not allowed reduction identifier is found.
14820       S.Diag(ReductionId.getBeginLoc(),
14821              diag::err_omp_unknown_reduction_identifier)
14822           << Type << ReductionIdRange;
14823       continue;
14824     }
14825 
14826     // OpenMP [2.14.3.6, reduction clause, Restrictions]
14827     // The type of a list item that appears in a reduction clause must be valid
14828     // for the reduction-identifier. For a max or min reduction in C, the type
14829     // of the list item must be an allowed arithmetic data type: char, int,
14830     // float, double, or _Bool, possibly modified with long, short, signed, or
14831     // unsigned. For a max or min reduction in C++, the type of the list item
14832     // must be an allowed arithmetic data type: char, wchar_t, int, float,
14833     // double, or bool, possibly modified with long, short, signed, or unsigned.
14834     if (DeclareReductionRef.isUnset()) {
14835       if ((BOK == BO_GT || BOK == BO_LT) &&
14836           !(Type->isScalarType() ||
14837             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
14838         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
14839             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
14840         if (!ASE && !OASE) {
14841           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14842                                    VarDecl::DeclarationOnly;
14843           S.Diag(D->getLocation(),
14844                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14845               << D;
14846         }
14847         continue;
14848       }
14849       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
14850           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
14851         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
14852             << getOpenMPClauseName(ClauseKind);
14853         if (!ASE && !OASE) {
14854           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14855                                    VarDecl::DeclarationOnly;
14856           S.Diag(D->getLocation(),
14857                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14858               << D;
14859         }
14860         continue;
14861       }
14862     }
14863 
14864     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
14865     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
14866                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
14867     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
14868                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
14869     QualType PrivateTy = Type;
14870 
14871     // Try if we can determine constant lengths for all array sections and avoid
14872     // the VLA.
14873     bool ConstantLengthOASE = false;
14874     if (OASE) {
14875       bool SingleElement;
14876       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
14877       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
14878           Context, OASE, SingleElement, ArraySizes);
14879 
14880       // If we don't have a single element, we must emit a constant array type.
14881       if (ConstantLengthOASE && !SingleElement) {
14882         for (llvm::APSInt &Size : ArraySizes)
14883           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
14884                                                    ArrayType::Normal,
14885                                                    /*IndexTypeQuals=*/0);
14886       }
14887     }
14888 
14889     if ((OASE && !ConstantLengthOASE) ||
14890         (!OASE && !ASE &&
14891          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
14892       if (!Context.getTargetInfo().isVLASupported()) {
14893         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
14894           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14895           S.Diag(ELoc, diag::note_vla_unsupported);
14896         } else {
14897           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14898           S.targetDiag(ELoc, diag::note_vla_unsupported);
14899         }
14900         continue;
14901       }
14902       // For arrays/array sections only:
14903       // Create pseudo array type for private copy. The size for this array will
14904       // be generated during codegen.
14905       // For array subscripts or single variables Private Ty is the same as Type
14906       // (type of the variable or single array element).
14907       PrivateTy = Context.getVariableArrayType(
14908           Type,
14909           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
14910           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
14911     } else if (!ASE && !OASE &&
14912                Context.getAsArrayType(D->getType().getNonReferenceType())) {
14913       PrivateTy = D->getType().getNonReferenceType();
14914     }
14915     // Private copy.
14916     VarDecl *PrivateVD =
14917         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
14918                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14919                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14920     // Add initializer for private variable.
14921     Expr *Init = nullptr;
14922     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
14923     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
14924     if (DeclareReductionRef.isUsable()) {
14925       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
14926       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
14927       if (DRD->getInitializer()) {
14928         Init = DRDRef;
14929         RHSVD->setInit(DRDRef);
14930         RHSVD->setInitStyle(VarDecl::CallInit);
14931       }
14932     } else {
14933       switch (BOK) {
14934       case BO_Add:
14935       case BO_Xor:
14936       case BO_Or:
14937       case BO_LOr:
14938         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
14939         if (Type->isScalarType() || Type->isAnyComplexType())
14940           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
14941         break;
14942       case BO_Mul:
14943       case BO_LAnd:
14944         if (Type->isScalarType() || Type->isAnyComplexType()) {
14945           // '*' and '&&' reduction ops - initializer is '1'.
14946           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
14947         }
14948         break;
14949       case BO_And: {
14950         // '&' reduction op - initializer is '~0'.
14951         QualType OrigType = Type;
14952         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14953           Type = ComplexTy->getElementType();
14954         if (Type->isRealFloatingType()) {
14955           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
14956               Context.getFloatTypeSemantics(Type),
14957               Context.getTypeSize(Type));
14958           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14959                                          Type, ELoc);
14960         } else if (Type->isScalarType()) {
14961           uint64_t Size = Context.getTypeSize(Type);
14962           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14963           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14964           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14965         }
14966         if (Init && OrigType->isAnyComplexType()) {
14967           // Init = 0xFFFF + 0xFFFFi;
14968           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
14969           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
14970         }
14971         Type = OrigType;
14972         break;
14973       }
14974       case BO_LT:
14975       case BO_GT: {
14976         // 'min' reduction op - initializer is 'Largest representable number in
14977         // the reduction list item type'.
14978         // 'max' reduction op - initializer is 'Least representable number in
14979         // the reduction list item type'.
14980         if (Type->isIntegerType() || Type->isPointerType()) {
14981           bool IsSigned = Type->hasSignedIntegerRepresentation();
14982           uint64_t Size = Context.getTypeSize(Type);
14983           QualType IntTy =
14984               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14985           llvm::APInt InitValue =
14986               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14987                                         : llvm::APInt::getMinValue(Size)
14988                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14989                                         : llvm::APInt::getMaxValue(Size);
14990           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14991           if (Type->isPointerType()) {
14992             // Cast to pointer type.
14993             ExprResult CastExpr = S.BuildCStyleCastExpr(
14994                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
14995             if (CastExpr.isInvalid())
14996               continue;
14997             Init = CastExpr.get();
14998           }
14999         } else if (Type->isRealFloatingType()) {
15000           llvm::APFloat InitValue = llvm::APFloat::getLargest(
15001               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
15002           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15003                                          Type, ELoc);
15004         }
15005         break;
15006       }
15007       case BO_PtrMemD:
15008       case BO_PtrMemI:
15009       case BO_MulAssign:
15010       case BO_Div:
15011       case BO_Rem:
15012       case BO_Sub:
15013       case BO_Shl:
15014       case BO_Shr:
15015       case BO_LE:
15016       case BO_GE:
15017       case BO_EQ:
15018       case BO_NE:
15019       case BO_Cmp:
15020       case BO_AndAssign:
15021       case BO_XorAssign:
15022       case BO_OrAssign:
15023       case BO_Assign:
15024       case BO_AddAssign:
15025       case BO_SubAssign:
15026       case BO_DivAssign:
15027       case BO_RemAssign:
15028       case BO_ShlAssign:
15029       case BO_ShrAssign:
15030       case BO_Comma:
15031         llvm_unreachable("Unexpected reduction operation");
15032       }
15033     }
15034     if (Init && DeclareReductionRef.isUnset())
15035       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
15036     else if (!Init)
15037       S.ActOnUninitializedDecl(RHSVD);
15038     if (RHSVD->isInvalidDecl())
15039       continue;
15040     if (!RHSVD->hasInit() &&
15041         (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
15042       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
15043           << Type << ReductionIdRange;
15044       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15045                                VarDecl::DeclarationOnly;
15046       S.Diag(D->getLocation(),
15047              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15048           << D;
15049       continue;
15050     }
15051     // Store initializer for single element in private copy. Will be used during
15052     // codegen.
15053     PrivateVD->setInit(RHSVD->getInit());
15054     PrivateVD->setInitStyle(RHSVD->getInitStyle());
15055     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
15056     ExprResult ReductionOp;
15057     if (DeclareReductionRef.isUsable()) {
15058       QualType RedTy = DeclareReductionRef.get()->getType();
15059       QualType PtrRedTy = Context.getPointerType(RedTy);
15060       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
15061       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
15062       if (!BasePath.empty()) {
15063         LHS = S.DefaultLvalueConversion(LHS.get());
15064         RHS = S.DefaultLvalueConversion(RHS.get());
15065         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
15066                                        CK_UncheckedDerivedToBase, LHS.get(),
15067                                        &BasePath, LHS.get()->getValueKind());
15068         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
15069                                        CK_UncheckedDerivedToBase, RHS.get(),
15070                                        &BasePath, RHS.get()->getValueKind());
15071       }
15072       FunctionProtoType::ExtProtoInfo EPI;
15073       QualType Params[] = {PtrRedTy, PtrRedTy};
15074       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
15075       auto *OVE = new (Context) OpaqueValueExpr(
15076           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
15077           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
15078       Expr *Args[] = {LHS.get(), RHS.get()};
15079       ReductionOp =
15080           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
15081     } else {
15082       ReductionOp = S.BuildBinOp(
15083           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
15084       if (ReductionOp.isUsable()) {
15085         if (BOK != BO_LT && BOK != BO_GT) {
15086           ReductionOp =
15087               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15088                            BO_Assign, LHSDRE, ReductionOp.get());
15089         } else {
15090           auto *ConditionalOp = new (Context)
15091               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
15092                                   Type, VK_LValue, OK_Ordinary);
15093           ReductionOp =
15094               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15095                            BO_Assign, LHSDRE, ConditionalOp);
15096         }
15097         if (ReductionOp.isUsable())
15098           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
15099                                               /*DiscardedValue*/ false);
15100       }
15101       if (!ReductionOp.isUsable())
15102         continue;
15103     }
15104 
15105     // OpenMP [2.15.4.6, Restrictions, p.2]
15106     // A list item that appears in an in_reduction clause of a task construct
15107     // must appear in a task_reduction clause of a construct associated with a
15108     // taskgroup region that includes the participating task in its taskgroup
15109     // set. The construct associated with the innermost region that meets this
15110     // condition must specify the same reduction-identifier as the in_reduction
15111     // clause.
15112     if (ClauseKind == OMPC_in_reduction) {
15113       SourceRange ParentSR;
15114       BinaryOperatorKind ParentBOK;
15115       const Expr *ParentReductionOp = nullptr;
15116       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
15117       DSAStackTy::DSAVarData ParentBOKDSA =
15118           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
15119                                                   ParentBOKTD);
15120       DSAStackTy::DSAVarData ParentReductionOpDSA =
15121           Stack->getTopMostTaskgroupReductionData(
15122               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
15123       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
15124       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
15125       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
15126           (DeclareReductionRef.isUsable() && IsParentBOK) ||
15127           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
15128         bool EmitError = true;
15129         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
15130           llvm::FoldingSetNodeID RedId, ParentRedId;
15131           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
15132           DeclareReductionRef.get()->Profile(RedId, Context,
15133                                              /*Canonical=*/true);
15134           EmitError = RedId != ParentRedId;
15135         }
15136         if (EmitError) {
15137           S.Diag(ReductionId.getBeginLoc(),
15138                  diag::err_omp_reduction_identifier_mismatch)
15139               << ReductionIdRange << RefExpr->getSourceRange();
15140           S.Diag(ParentSR.getBegin(),
15141                  diag::note_omp_previous_reduction_identifier)
15142               << ParentSR
15143               << (IsParentBOK ? ParentBOKDSA.RefExpr
15144                               : ParentReductionOpDSA.RefExpr)
15145                      ->getSourceRange();
15146           continue;
15147         }
15148       }
15149       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
15150     }
15151 
15152     DeclRefExpr *Ref = nullptr;
15153     Expr *VarsExpr = RefExpr->IgnoreParens();
15154     if (!VD && !S.CurContext->isDependentContext()) {
15155       if (ASE || OASE) {
15156         TransformExprToCaptures RebuildToCapture(S, D);
15157         VarsExpr =
15158             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
15159         Ref = RebuildToCapture.getCapturedExpr();
15160       } else {
15161         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
15162       }
15163       if (!S.isOpenMPCapturedDecl(D)) {
15164         RD.ExprCaptures.emplace_back(Ref->getDecl());
15165         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15166           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
15167           if (!RefRes.isUsable())
15168             continue;
15169           ExprResult PostUpdateRes =
15170               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15171                            RefRes.get());
15172           if (!PostUpdateRes.isUsable())
15173             continue;
15174           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
15175               Stack->getCurrentDirective() == OMPD_taskgroup) {
15176             S.Diag(RefExpr->getExprLoc(),
15177                    diag::err_omp_reduction_non_addressable_expression)
15178                 << RefExpr->getSourceRange();
15179             continue;
15180           }
15181           RD.ExprPostUpdates.emplace_back(
15182               S.IgnoredValueConversions(PostUpdateRes.get()).get());
15183         }
15184       }
15185     }
15186     // All reduction items are still marked as reduction (to do not increase
15187     // code base size).
15188     unsigned Modifier = RD.RedModifier;
15189     // Consider task_reductions as reductions with task modifier. Required for
15190     // correct analysis of in_reduction clauses.
15191     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
15192       Modifier = OMPC_REDUCTION_task;
15193     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier);
15194     if (Modifier == OMPC_REDUCTION_task &&
15195         (CurrDir == OMPD_taskgroup ||
15196          ((isOpenMPParallelDirective(CurrDir) ||
15197            isOpenMPWorksharingDirective(CurrDir)) &&
15198           !isOpenMPSimdDirective(CurrDir)))) {
15199       if (DeclareReductionRef.isUsable())
15200         Stack->addTaskgroupReductionData(D, ReductionIdRange,
15201                                          DeclareReductionRef.get());
15202       else
15203         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
15204     }
15205     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
15206             TaskgroupDescriptor);
15207   }
15208   return RD.Vars.empty();
15209 }
15210 
15211 OMPClause *Sema::ActOnOpenMPReductionClause(
15212     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
15213     SourceLocation StartLoc, SourceLocation LParenLoc,
15214     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
15215     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15216     ArrayRef<Expr *> UnresolvedReductions) {
15217   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
15218     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
15219         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
15220                                    /*Last=*/OMPC_REDUCTION_unknown)
15221         << getOpenMPClauseName(OMPC_reduction);
15222     return nullptr;
15223   }
15224   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
15225   // A reduction clause with the inscan reduction-modifier may only appear on a
15226   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
15227   // construct, a parallel worksharing-loop construct or a parallel
15228   // worksharing-loop SIMD construct.
15229   if (Modifier == OMPC_REDUCTION_inscan &&
15230       (DSAStack->getCurrentDirective() != OMPD_for &&
15231        DSAStack->getCurrentDirective() != OMPD_for_simd &&
15232        DSAStack->getCurrentDirective() != OMPD_simd &&
15233        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
15234        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
15235     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
15236     return nullptr;
15237   }
15238 
15239   ReductionData RD(VarList.size(), Modifier);
15240   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
15241                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15242                                   ReductionIdScopeSpec, ReductionId,
15243                                   UnresolvedReductions, RD))
15244     return nullptr;
15245 
15246   return OMPReductionClause::Create(
15247       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
15248       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15249       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
15250       buildPreInits(Context, RD.ExprCaptures),
15251       buildPostUpdate(*this, RD.ExprPostUpdates));
15252 }
15253 
15254 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
15255     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15256     SourceLocation ColonLoc, SourceLocation EndLoc,
15257     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15258     ArrayRef<Expr *> UnresolvedReductions) {
15259   ReductionData RD(VarList.size());
15260   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
15261                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15262                                   ReductionIdScopeSpec, ReductionId,
15263                                   UnresolvedReductions, RD))
15264     return nullptr;
15265 
15266   return OMPTaskReductionClause::Create(
15267       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15268       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15269       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
15270       buildPreInits(Context, RD.ExprCaptures),
15271       buildPostUpdate(*this, RD.ExprPostUpdates));
15272 }
15273 
15274 OMPClause *Sema::ActOnOpenMPInReductionClause(
15275     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15276     SourceLocation ColonLoc, SourceLocation EndLoc,
15277     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15278     ArrayRef<Expr *> UnresolvedReductions) {
15279   ReductionData RD(VarList.size());
15280   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
15281                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15282                                   ReductionIdScopeSpec, ReductionId,
15283                                   UnresolvedReductions, RD))
15284     return nullptr;
15285 
15286   return OMPInReductionClause::Create(
15287       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15288       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15289       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
15290       buildPreInits(Context, RD.ExprCaptures),
15291       buildPostUpdate(*this, RD.ExprPostUpdates));
15292 }
15293 
15294 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
15295                                      SourceLocation LinLoc) {
15296   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
15297       LinKind == OMPC_LINEAR_unknown) {
15298     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
15299     return true;
15300   }
15301   return false;
15302 }
15303 
15304 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
15305                                  OpenMPLinearClauseKind LinKind, QualType Type,
15306                                  bool IsDeclareSimd) {
15307   const auto *VD = dyn_cast_or_null<VarDecl>(D);
15308   // A variable must not have an incomplete type or a reference type.
15309   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
15310     return true;
15311   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
15312       !Type->isReferenceType()) {
15313     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
15314         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
15315     return true;
15316   }
15317   Type = Type.getNonReferenceType();
15318 
15319   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15320   // A variable that is privatized must not have a const-qualified type
15321   // unless it is of class type with a mutable member. This restriction does
15322   // not apply to the firstprivate clause, nor to the linear clause on
15323   // declarative directives (like declare simd).
15324   if (!IsDeclareSimd &&
15325       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
15326     return true;
15327 
15328   // A list item must be of integral or pointer type.
15329   Type = Type.getUnqualifiedType().getCanonicalType();
15330   const auto *Ty = Type.getTypePtrOrNull();
15331   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
15332               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
15333     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
15334     if (D) {
15335       bool IsDecl =
15336           !VD ||
15337           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15338       Diag(D->getLocation(),
15339            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15340           << D;
15341     }
15342     return true;
15343   }
15344   return false;
15345 }
15346 
15347 OMPClause *Sema::ActOnOpenMPLinearClause(
15348     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
15349     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
15350     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15351   SmallVector<Expr *, 8> Vars;
15352   SmallVector<Expr *, 8> Privates;
15353   SmallVector<Expr *, 8> Inits;
15354   SmallVector<Decl *, 4> ExprCaptures;
15355   SmallVector<Expr *, 4> ExprPostUpdates;
15356   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
15357     LinKind = OMPC_LINEAR_val;
15358   for (Expr *RefExpr : VarList) {
15359     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15360     SourceLocation ELoc;
15361     SourceRange ERange;
15362     Expr *SimpleRefExpr = RefExpr;
15363     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15364     if (Res.second) {
15365       // It will be analyzed later.
15366       Vars.push_back(RefExpr);
15367       Privates.push_back(nullptr);
15368       Inits.push_back(nullptr);
15369     }
15370     ValueDecl *D = Res.first;
15371     if (!D)
15372       continue;
15373 
15374     QualType Type = D->getType();
15375     auto *VD = dyn_cast<VarDecl>(D);
15376 
15377     // OpenMP [2.14.3.7, linear clause]
15378     //  A list-item cannot appear in more than one linear clause.
15379     //  A list-item that appears in a linear clause cannot appear in any
15380     //  other data-sharing attribute clause.
15381     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15382     if (DVar.RefExpr) {
15383       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15384                                           << getOpenMPClauseName(OMPC_linear);
15385       reportOriginalDsa(*this, DSAStack, D, DVar);
15386       continue;
15387     }
15388 
15389     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
15390       continue;
15391     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15392 
15393     // Build private copy of original var.
15394     VarDecl *Private =
15395         buildVarDecl(*this, ELoc, Type, D->getName(),
15396                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15397                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15398     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
15399     // Build var to save initial value.
15400     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
15401     Expr *InitExpr;
15402     DeclRefExpr *Ref = nullptr;
15403     if (!VD && !CurContext->isDependentContext()) {
15404       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15405       if (!isOpenMPCapturedDecl(D)) {
15406         ExprCaptures.push_back(Ref->getDecl());
15407         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15408           ExprResult RefRes = DefaultLvalueConversion(Ref);
15409           if (!RefRes.isUsable())
15410             continue;
15411           ExprResult PostUpdateRes =
15412               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
15413                          SimpleRefExpr, RefRes.get());
15414           if (!PostUpdateRes.isUsable())
15415             continue;
15416           ExprPostUpdates.push_back(
15417               IgnoredValueConversions(PostUpdateRes.get()).get());
15418         }
15419       }
15420     }
15421     if (LinKind == OMPC_LINEAR_uval)
15422       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
15423     else
15424       InitExpr = VD ? SimpleRefExpr : Ref;
15425     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
15426                          /*DirectInit=*/false);
15427     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
15428 
15429     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
15430     Vars.push_back((VD || CurContext->isDependentContext())
15431                        ? RefExpr->IgnoreParens()
15432                        : Ref);
15433     Privates.push_back(PrivateRef);
15434     Inits.push_back(InitRef);
15435   }
15436 
15437   if (Vars.empty())
15438     return nullptr;
15439 
15440   Expr *StepExpr = Step;
15441   Expr *CalcStepExpr = nullptr;
15442   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
15443       !Step->isInstantiationDependent() &&
15444       !Step->containsUnexpandedParameterPack()) {
15445     SourceLocation StepLoc = Step->getBeginLoc();
15446     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
15447     if (Val.isInvalid())
15448       return nullptr;
15449     StepExpr = Val.get();
15450 
15451     // Build var to save the step value.
15452     VarDecl *SaveVar =
15453         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
15454     ExprResult SaveRef =
15455         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
15456     ExprResult CalcStep =
15457         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
15458     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
15459 
15460     // Warn about zero linear step (it would be probably better specified as
15461     // making corresponding variables 'const').
15462     llvm::APSInt Result;
15463     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
15464     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
15465       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
15466                                                      << (Vars.size() > 1);
15467     if (!IsConstant && CalcStep.isUsable()) {
15468       // Calculate the step beforehand instead of doing this on each iteration.
15469       // (This is not used if the number of iterations may be kfold-ed).
15470       CalcStepExpr = CalcStep.get();
15471     }
15472   }
15473 
15474   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
15475                                  ColonLoc, EndLoc, Vars, Privates, Inits,
15476                                  StepExpr, CalcStepExpr,
15477                                  buildPreInits(Context, ExprCaptures),
15478                                  buildPostUpdate(*this, ExprPostUpdates));
15479 }
15480 
15481 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
15482                                      Expr *NumIterations, Sema &SemaRef,
15483                                      Scope *S, DSAStackTy *Stack) {
15484   // Walk the vars and build update/final expressions for the CodeGen.
15485   SmallVector<Expr *, 8> Updates;
15486   SmallVector<Expr *, 8> Finals;
15487   SmallVector<Expr *, 8> UsedExprs;
15488   Expr *Step = Clause.getStep();
15489   Expr *CalcStep = Clause.getCalcStep();
15490   // OpenMP [2.14.3.7, linear clause]
15491   // If linear-step is not specified it is assumed to be 1.
15492   if (!Step)
15493     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
15494   else if (CalcStep)
15495     Step = cast<BinaryOperator>(CalcStep)->getLHS();
15496   bool HasErrors = false;
15497   auto CurInit = Clause.inits().begin();
15498   auto CurPrivate = Clause.privates().begin();
15499   OpenMPLinearClauseKind LinKind = Clause.getModifier();
15500   for (Expr *RefExpr : Clause.varlists()) {
15501     SourceLocation ELoc;
15502     SourceRange ERange;
15503     Expr *SimpleRefExpr = RefExpr;
15504     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
15505     ValueDecl *D = Res.first;
15506     if (Res.second || !D) {
15507       Updates.push_back(nullptr);
15508       Finals.push_back(nullptr);
15509       HasErrors = true;
15510       continue;
15511     }
15512     auto &&Info = Stack->isLoopControlVariable(D);
15513     // OpenMP [2.15.11, distribute simd Construct]
15514     // A list item may not appear in a linear clause, unless it is the loop
15515     // iteration variable.
15516     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
15517         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
15518       SemaRef.Diag(ELoc,
15519                    diag::err_omp_linear_distribute_var_non_loop_iteration);
15520       Updates.push_back(nullptr);
15521       Finals.push_back(nullptr);
15522       HasErrors = true;
15523       continue;
15524     }
15525     Expr *InitExpr = *CurInit;
15526 
15527     // Build privatized reference to the current linear var.
15528     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
15529     Expr *CapturedRef;
15530     if (LinKind == OMPC_LINEAR_uval)
15531       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
15532     else
15533       CapturedRef =
15534           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
15535                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
15536                            /*RefersToCapture=*/true);
15537 
15538     // Build update: Var = InitExpr + IV * Step
15539     ExprResult Update;
15540     if (!Info.first)
15541       Update = buildCounterUpdate(
15542           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
15543           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
15544     else
15545       Update = *CurPrivate;
15546     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
15547                                          /*DiscardedValue*/ false);
15548 
15549     // Build final: Var = InitExpr + NumIterations * Step
15550     ExprResult Final;
15551     if (!Info.first)
15552       Final =
15553           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
15554                              InitExpr, NumIterations, Step, /*Subtract=*/false,
15555                              /*IsNonRectangularLB=*/false);
15556     else
15557       Final = *CurPrivate;
15558     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
15559                                         /*DiscardedValue*/ false);
15560 
15561     if (!Update.isUsable() || !Final.isUsable()) {
15562       Updates.push_back(nullptr);
15563       Finals.push_back(nullptr);
15564       UsedExprs.push_back(nullptr);
15565       HasErrors = true;
15566     } else {
15567       Updates.push_back(Update.get());
15568       Finals.push_back(Final.get());
15569       if (!Info.first)
15570         UsedExprs.push_back(SimpleRefExpr);
15571     }
15572     ++CurInit;
15573     ++CurPrivate;
15574   }
15575   if (Expr *S = Clause.getStep())
15576     UsedExprs.push_back(S);
15577   // Fill the remaining part with the nullptr.
15578   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
15579   Clause.setUpdates(Updates);
15580   Clause.setFinals(Finals);
15581   Clause.setUsedExprs(UsedExprs);
15582   return HasErrors;
15583 }
15584 
15585 OMPClause *Sema::ActOnOpenMPAlignedClause(
15586     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
15587     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15588   SmallVector<Expr *, 8> Vars;
15589   for (Expr *RefExpr : VarList) {
15590     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15591     SourceLocation ELoc;
15592     SourceRange ERange;
15593     Expr *SimpleRefExpr = RefExpr;
15594     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15595     if (Res.second) {
15596       // It will be analyzed later.
15597       Vars.push_back(RefExpr);
15598     }
15599     ValueDecl *D = Res.first;
15600     if (!D)
15601       continue;
15602 
15603     QualType QType = D->getType();
15604     auto *VD = dyn_cast<VarDecl>(D);
15605 
15606     // OpenMP  [2.8.1, simd construct, Restrictions]
15607     // The type of list items appearing in the aligned clause must be
15608     // array, pointer, reference to array, or reference to pointer.
15609     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15610     const Type *Ty = QType.getTypePtrOrNull();
15611     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
15612       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
15613           << QType << getLangOpts().CPlusPlus << ERange;
15614       bool IsDecl =
15615           !VD ||
15616           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15617       Diag(D->getLocation(),
15618            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15619           << D;
15620       continue;
15621     }
15622 
15623     // OpenMP  [2.8.1, simd construct, Restrictions]
15624     // A list-item cannot appear in more than one aligned clause.
15625     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
15626       Diag(ELoc, diag::err_omp_used_in_clause_twice)
15627           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
15628       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
15629           << getOpenMPClauseName(OMPC_aligned);
15630       continue;
15631     }
15632 
15633     DeclRefExpr *Ref = nullptr;
15634     if (!VD && isOpenMPCapturedDecl(D))
15635       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15636     Vars.push_back(DefaultFunctionArrayConversion(
15637                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
15638                        .get());
15639   }
15640 
15641   // OpenMP [2.8.1, simd construct, Description]
15642   // The parameter of the aligned clause, alignment, must be a constant
15643   // positive integer expression.
15644   // If no optional parameter is specified, implementation-defined default
15645   // alignments for SIMD instructions on the target platforms are assumed.
15646   if (Alignment != nullptr) {
15647     ExprResult AlignResult =
15648         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
15649     if (AlignResult.isInvalid())
15650       return nullptr;
15651     Alignment = AlignResult.get();
15652   }
15653   if (Vars.empty())
15654     return nullptr;
15655 
15656   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
15657                                   EndLoc, Vars, Alignment);
15658 }
15659 
15660 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
15661                                          SourceLocation StartLoc,
15662                                          SourceLocation LParenLoc,
15663                                          SourceLocation EndLoc) {
15664   SmallVector<Expr *, 8> Vars;
15665   SmallVector<Expr *, 8> SrcExprs;
15666   SmallVector<Expr *, 8> DstExprs;
15667   SmallVector<Expr *, 8> AssignmentOps;
15668   for (Expr *RefExpr : VarList) {
15669     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
15670     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15671       // It will be analyzed later.
15672       Vars.push_back(RefExpr);
15673       SrcExprs.push_back(nullptr);
15674       DstExprs.push_back(nullptr);
15675       AssignmentOps.push_back(nullptr);
15676       continue;
15677     }
15678 
15679     SourceLocation ELoc = RefExpr->getExprLoc();
15680     // OpenMP [2.1, C/C++]
15681     //  A list item is a variable name.
15682     // OpenMP  [2.14.4.1, Restrictions, p.1]
15683     //  A list item that appears in a copyin clause must be threadprivate.
15684     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
15685     if (!DE || !isa<VarDecl>(DE->getDecl())) {
15686       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
15687           << 0 << RefExpr->getSourceRange();
15688       continue;
15689     }
15690 
15691     Decl *D = DE->getDecl();
15692     auto *VD = cast<VarDecl>(D);
15693 
15694     QualType Type = VD->getType();
15695     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
15696       // It will be analyzed later.
15697       Vars.push_back(DE);
15698       SrcExprs.push_back(nullptr);
15699       DstExprs.push_back(nullptr);
15700       AssignmentOps.push_back(nullptr);
15701       continue;
15702     }
15703 
15704     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
15705     //  A list item that appears in a copyin clause must be threadprivate.
15706     if (!DSAStack->isThreadPrivate(VD)) {
15707       Diag(ELoc, diag::err_omp_required_access)
15708           << getOpenMPClauseName(OMPC_copyin)
15709           << getOpenMPDirectiveName(OMPD_threadprivate);
15710       continue;
15711     }
15712 
15713     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
15714     //  A variable of class type (or array thereof) that appears in a
15715     //  copyin clause requires an accessible, unambiguous copy assignment
15716     //  operator for the class type.
15717     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15718     VarDecl *SrcVD =
15719         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
15720                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
15721     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
15722         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
15723     VarDecl *DstVD =
15724         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
15725                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
15726     DeclRefExpr *PseudoDstExpr =
15727         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
15728     // For arrays generate assignment operation for single element and replace
15729     // it by the original array element in CodeGen.
15730     ExprResult AssignmentOp =
15731         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
15732                    PseudoSrcExpr);
15733     if (AssignmentOp.isInvalid())
15734       continue;
15735     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
15736                                        /*DiscardedValue*/ false);
15737     if (AssignmentOp.isInvalid())
15738       continue;
15739 
15740     DSAStack->addDSA(VD, DE, OMPC_copyin);
15741     Vars.push_back(DE);
15742     SrcExprs.push_back(PseudoSrcExpr);
15743     DstExprs.push_back(PseudoDstExpr);
15744     AssignmentOps.push_back(AssignmentOp.get());
15745   }
15746 
15747   if (Vars.empty())
15748     return nullptr;
15749 
15750   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15751                                  SrcExprs, DstExprs, AssignmentOps);
15752 }
15753 
15754 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
15755                                               SourceLocation StartLoc,
15756                                               SourceLocation LParenLoc,
15757                                               SourceLocation EndLoc) {
15758   SmallVector<Expr *, 8> Vars;
15759   SmallVector<Expr *, 8> SrcExprs;
15760   SmallVector<Expr *, 8> DstExprs;
15761   SmallVector<Expr *, 8> AssignmentOps;
15762   for (Expr *RefExpr : VarList) {
15763     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15764     SourceLocation ELoc;
15765     SourceRange ERange;
15766     Expr *SimpleRefExpr = RefExpr;
15767     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15768     if (Res.second) {
15769       // It will be analyzed later.
15770       Vars.push_back(RefExpr);
15771       SrcExprs.push_back(nullptr);
15772       DstExprs.push_back(nullptr);
15773       AssignmentOps.push_back(nullptr);
15774     }
15775     ValueDecl *D = Res.first;
15776     if (!D)
15777       continue;
15778 
15779     QualType Type = D->getType();
15780     auto *VD = dyn_cast<VarDecl>(D);
15781 
15782     // OpenMP [2.14.4.2, Restrictions, p.2]
15783     //  A list item that appears in a copyprivate clause may not appear in a
15784     //  private or firstprivate clause on the single construct.
15785     if (!VD || !DSAStack->isThreadPrivate(VD)) {
15786       DSAStackTy::DSAVarData DVar =
15787           DSAStack->getTopDSA(D, /*FromParent=*/false);
15788       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
15789           DVar.RefExpr) {
15790         Diag(ELoc, diag::err_omp_wrong_dsa)
15791             << getOpenMPClauseName(DVar.CKind)
15792             << getOpenMPClauseName(OMPC_copyprivate);
15793         reportOriginalDsa(*this, DSAStack, D, DVar);
15794         continue;
15795       }
15796 
15797       // OpenMP [2.11.4.2, Restrictions, p.1]
15798       //  All list items that appear in a copyprivate clause must be either
15799       //  threadprivate or private in the enclosing context.
15800       if (DVar.CKind == OMPC_unknown) {
15801         DVar = DSAStack->getImplicitDSA(D, false);
15802         if (DVar.CKind == OMPC_shared) {
15803           Diag(ELoc, diag::err_omp_required_access)
15804               << getOpenMPClauseName(OMPC_copyprivate)
15805               << "threadprivate or private in the enclosing context";
15806           reportOriginalDsa(*this, DSAStack, D, DVar);
15807           continue;
15808         }
15809       }
15810     }
15811 
15812     // Variably modified types are not supported.
15813     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
15814       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15815           << getOpenMPClauseName(OMPC_copyprivate) << Type
15816           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15817       bool IsDecl =
15818           !VD ||
15819           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15820       Diag(D->getLocation(),
15821            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15822           << D;
15823       continue;
15824     }
15825 
15826     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
15827     //  A variable of class type (or array thereof) that appears in a
15828     //  copyin clause requires an accessible, unambiguous copy assignment
15829     //  operator for the class type.
15830     Type = Context.getBaseElementType(Type.getNonReferenceType())
15831                .getUnqualifiedType();
15832     VarDecl *SrcVD =
15833         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
15834                      D->hasAttrs() ? &D->getAttrs() : nullptr);
15835     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
15836     VarDecl *DstVD =
15837         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
15838                      D->hasAttrs() ? &D->getAttrs() : nullptr);
15839     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
15840     ExprResult AssignmentOp = BuildBinOp(
15841         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
15842     if (AssignmentOp.isInvalid())
15843       continue;
15844     AssignmentOp =
15845         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
15846     if (AssignmentOp.isInvalid())
15847       continue;
15848 
15849     // No need to mark vars as copyprivate, they are already threadprivate or
15850     // implicitly private.
15851     assert(VD || isOpenMPCapturedDecl(D));
15852     Vars.push_back(
15853         VD ? RefExpr->IgnoreParens()
15854            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
15855     SrcExprs.push_back(PseudoSrcExpr);
15856     DstExprs.push_back(PseudoDstExpr);
15857     AssignmentOps.push_back(AssignmentOp.get());
15858   }
15859 
15860   if (Vars.empty())
15861     return nullptr;
15862 
15863   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15864                                       Vars, SrcExprs, DstExprs, AssignmentOps);
15865 }
15866 
15867 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
15868                                         SourceLocation StartLoc,
15869                                         SourceLocation LParenLoc,
15870                                         SourceLocation EndLoc) {
15871   if (VarList.empty())
15872     return nullptr;
15873 
15874   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
15875 }
15876 
15877 /// Tries to find omp_depend_t. type.
15878 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
15879                            bool Diagnose = true) {
15880   QualType OMPDependT = Stack->getOMPDependT();
15881   if (!OMPDependT.isNull())
15882     return true;
15883   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
15884   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
15885   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
15886     if (Diagnose)
15887       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
15888     return false;
15889   }
15890   Stack->setOMPDependT(PT.get());
15891   return true;
15892 }
15893 
15894 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
15895                                          SourceLocation LParenLoc,
15896                                          SourceLocation EndLoc) {
15897   if (!Depobj)
15898     return nullptr;
15899 
15900   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
15901 
15902   // OpenMP 5.0, 2.17.10.1 depobj Construct
15903   // depobj is an lvalue expression of type omp_depend_t.
15904   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
15905       !Depobj->isInstantiationDependent() &&
15906       !Depobj->containsUnexpandedParameterPack() &&
15907       (OMPDependTFound &&
15908        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
15909                                    /*CompareUnqualified=*/true))) {
15910     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
15911         << 0 << Depobj->getType() << Depobj->getSourceRange();
15912   }
15913 
15914   if (!Depobj->isLValue()) {
15915     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
15916         << 1 << Depobj->getSourceRange();
15917   }
15918 
15919   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
15920 }
15921 
15922 OMPClause *
15923 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
15924                               SourceLocation DepLoc, SourceLocation ColonLoc,
15925                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15926                               SourceLocation LParenLoc, SourceLocation EndLoc) {
15927   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
15928       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
15929     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
15930         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
15931     return nullptr;
15932   }
15933   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
15934        DSAStack->getCurrentDirective() == OMPD_depobj) &&
15935       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
15936        DepKind == OMPC_DEPEND_sink ||
15937        ((LangOpts.OpenMP < 50 ||
15938          DSAStack->getCurrentDirective() == OMPD_depobj) &&
15939         DepKind == OMPC_DEPEND_depobj))) {
15940     SmallVector<unsigned, 3> Except;
15941     Except.push_back(OMPC_DEPEND_source);
15942     Except.push_back(OMPC_DEPEND_sink);
15943     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
15944       Except.push_back(OMPC_DEPEND_depobj);
15945     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
15946                                ? "depend modifier(iterator) or "
15947                                : "";
15948     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
15949         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
15950                                               /*Last=*/OMPC_DEPEND_unknown,
15951                                               Except)
15952         << getOpenMPClauseName(OMPC_depend);
15953     return nullptr;
15954   }
15955   if (DepModifier &&
15956       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
15957     Diag(DepModifier->getExprLoc(),
15958          diag::err_omp_depend_sink_source_with_modifier);
15959     return nullptr;
15960   }
15961   if (DepModifier &&
15962       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
15963     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
15964 
15965   SmallVector<Expr *, 8> Vars;
15966   DSAStackTy::OperatorOffsetTy OpsOffs;
15967   llvm::APSInt DepCounter(/*BitWidth=*/32);
15968   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
15969   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
15970     if (const Expr *OrderedCountExpr =
15971             DSAStack->getParentOrderedRegionParam().first) {
15972       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
15973       TotalDepCount.setIsUnsigned(/*Val=*/true);
15974     }
15975   }
15976   for (Expr *RefExpr : VarList) {
15977     assert(RefExpr && "NULL expr in OpenMP shared clause.");
15978     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15979       // It will be analyzed later.
15980       Vars.push_back(RefExpr);
15981       continue;
15982     }
15983 
15984     SourceLocation ELoc = RefExpr->getExprLoc();
15985     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
15986     if (DepKind == OMPC_DEPEND_sink) {
15987       if (DSAStack->getParentOrderedRegionParam().first &&
15988           DepCounter >= TotalDepCount) {
15989         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
15990         continue;
15991       }
15992       ++DepCounter;
15993       // OpenMP  [2.13.9, Summary]
15994       // depend(dependence-type : vec), where dependence-type is:
15995       // 'sink' and where vec is the iteration vector, which has the form:
15996       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
15997       // where n is the value specified by the ordered clause in the loop
15998       // directive, xi denotes the loop iteration variable of the i-th nested
15999       // loop associated with the loop directive, and di is a constant
16000       // non-negative integer.
16001       if (CurContext->isDependentContext()) {
16002         // It will be analyzed later.
16003         Vars.push_back(RefExpr);
16004         continue;
16005       }
16006       SimpleExpr = SimpleExpr->IgnoreImplicit();
16007       OverloadedOperatorKind OOK = OO_None;
16008       SourceLocation OOLoc;
16009       Expr *LHS = SimpleExpr;
16010       Expr *RHS = nullptr;
16011       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
16012         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
16013         OOLoc = BO->getOperatorLoc();
16014         LHS = BO->getLHS()->IgnoreParenImpCasts();
16015         RHS = BO->getRHS()->IgnoreParenImpCasts();
16016       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
16017         OOK = OCE->getOperator();
16018         OOLoc = OCE->getOperatorLoc();
16019         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16020         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
16021       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
16022         OOK = MCE->getMethodDecl()
16023                   ->getNameInfo()
16024                   .getName()
16025                   .getCXXOverloadedOperator();
16026         OOLoc = MCE->getCallee()->getExprLoc();
16027         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
16028         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16029       }
16030       SourceLocation ELoc;
16031       SourceRange ERange;
16032       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
16033       if (Res.second) {
16034         // It will be analyzed later.
16035         Vars.push_back(RefExpr);
16036       }
16037       ValueDecl *D = Res.first;
16038       if (!D)
16039         continue;
16040 
16041       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
16042         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
16043         continue;
16044       }
16045       if (RHS) {
16046         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
16047             RHS, OMPC_depend, /*StrictlyPositive=*/false);
16048         if (RHSRes.isInvalid())
16049           continue;
16050       }
16051       if (!CurContext->isDependentContext() &&
16052           DSAStack->getParentOrderedRegionParam().first &&
16053           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
16054         const ValueDecl *VD =
16055             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
16056         if (VD)
16057           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
16058               << 1 << VD;
16059         else
16060           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
16061         continue;
16062       }
16063       OpsOffs.emplace_back(RHS, OOK);
16064     } else {
16065       bool OMPDependTFound = LangOpts.OpenMP >= 50;
16066       if (OMPDependTFound)
16067         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
16068                                          DepKind == OMPC_DEPEND_depobj);
16069       if (DepKind == OMPC_DEPEND_depobj) {
16070         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16071         // List items used in depend clauses with the depobj dependence type
16072         // must be expressions of the omp_depend_t type.
16073         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16074             !RefExpr->isInstantiationDependent() &&
16075             !RefExpr->containsUnexpandedParameterPack() &&
16076             (OMPDependTFound &&
16077              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
16078                                              RefExpr->getType()))) {
16079           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16080               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
16081           continue;
16082         }
16083         if (!RefExpr->isLValue()) {
16084           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16085               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
16086           continue;
16087         }
16088       } else {
16089         // OpenMP 5.0 [2.17.11, Restrictions]
16090         // List items used in depend clauses cannot be zero-length array
16091         // sections.
16092         QualType ExprTy = RefExpr->getType().getNonReferenceType();
16093         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
16094         if (OASE) {
16095           QualType BaseType =
16096               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16097           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16098             ExprTy = ATy->getElementType();
16099           else
16100             ExprTy = BaseType->getPointeeType();
16101           ExprTy = ExprTy.getNonReferenceType();
16102           const Expr *Length = OASE->getLength();
16103           Expr::EvalResult Result;
16104           if (Length && !Length->isValueDependent() &&
16105               Length->EvaluateAsInt(Result, Context) &&
16106               Result.Val.getInt().isNullValue()) {
16107             Diag(ELoc,
16108                  diag::err_omp_depend_zero_length_array_section_not_allowed)
16109                 << SimpleExpr->getSourceRange();
16110             continue;
16111           }
16112         }
16113 
16114         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16115         // List items used in depend clauses with the in, out, inout or
16116         // mutexinoutset dependence types cannot be expressions of the
16117         // omp_depend_t type.
16118         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16119             !RefExpr->isInstantiationDependent() &&
16120             !RefExpr->containsUnexpandedParameterPack() &&
16121             (OMPDependTFound &&
16122              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
16123           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16124               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
16125               << RefExpr->getSourceRange();
16126           continue;
16127         }
16128 
16129         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
16130         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
16131             (ASE &&
16132              !ASE->getBase()
16133                   ->getType()
16134                   .getNonReferenceType()
16135                   ->isPointerType() &&
16136              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
16137           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16138               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16139               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16140           continue;
16141         }
16142 
16143         ExprResult Res;
16144         {
16145           Sema::TentativeAnalysisScope Trap(*this);
16146           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
16147                                      RefExpr->IgnoreParenImpCasts());
16148         }
16149         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
16150             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
16151           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16152               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16153               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16154           continue;
16155         }
16156       }
16157     }
16158     Vars.push_back(RefExpr->IgnoreParenImpCasts());
16159   }
16160 
16161   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
16162       TotalDepCount > VarList.size() &&
16163       DSAStack->getParentOrderedRegionParam().first &&
16164       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
16165     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
16166         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
16167   }
16168   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
16169       Vars.empty())
16170     return nullptr;
16171 
16172   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16173                                     DepModifier, DepKind, DepLoc, ColonLoc,
16174                                     Vars, TotalDepCount.getZExtValue());
16175   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
16176       DSAStack->isParentOrderedRegion())
16177     DSAStack->addDoacrossDependClause(C, OpsOffs);
16178   return C;
16179 }
16180 
16181 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
16182                                          Expr *Device, SourceLocation StartLoc,
16183                                          SourceLocation LParenLoc,
16184                                          SourceLocation ModifierLoc,
16185                                          SourceLocation EndLoc) {
16186   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
16187          "Unexpected device modifier in OpenMP < 50.");
16188 
16189   bool ErrorFound = false;
16190   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
16191     std::string Values =
16192         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
16193     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
16194         << Values << getOpenMPClauseName(OMPC_device);
16195     ErrorFound = true;
16196   }
16197 
16198   Expr *ValExpr = Device;
16199   Stmt *HelperValStmt = nullptr;
16200 
16201   // OpenMP [2.9.1, Restrictions]
16202   // The device expression must evaluate to a non-negative integer value.
16203   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
16204                                           /*StrictlyPositive=*/false) ||
16205                ErrorFound;
16206   if (ErrorFound)
16207     return nullptr;
16208 
16209   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16210   OpenMPDirectiveKind CaptureRegion =
16211       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
16212   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16213     ValExpr = MakeFullExpr(ValExpr).get();
16214     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16215     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16216     HelperValStmt = buildPreInits(Context, Captures);
16217   }
16218 
16219   return new (Context)
16220       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
16221                       LParenLoc, ModifierLoc, EndLoc);
16222 }
16223 
16224 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
16225                               DSAStackTy *Stack, QualType QTy,
16226                               bool FullCheck = true) {
16227   NamedDecl *ND;
16228   if (QTy->isIncompleteType(&ND)) {
16229     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
16230     return false;
16231   }
16232   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
16233       !QTy.isTriviallyCopyableType(SemaRef.Context))
16234     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
16235   return true;
16236 }
16237 
16238 /// Return true if it can be proven that the provided array expression
16239 /// (array section or array subscript) does NOT specify the whole size of the
16240 /// array whose base type is \a BaseQTy.
16241 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
16242                                                         const Expr *E,
16243                                                         QualType BaseQTy) {
16244   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16245 
16246   // If this is an array subscript, it refers to the whole size if the size of
16247   // the dimension is constant and equals 1. Also, an array section assumes the
16248   // format of an array subscript if no colon is used.
16249   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
16250     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16251       return ATy->getSize().getSExtValue() != 1;
16252     // Size can't be evaluated statically.
16253     return false;
16254   }
16255 
16256   assert(OASE && "Expecting array section if not an array subscript.");
16257   const Expr *LowerBound = OASE->getLowerBound();
16258   const Expr *Length = OASE->getLength();
16259 
16260   // If there is a lower bound that does not evaluates to zero, we are not
16261   // covering the whole dimension.
16262   if (LowerBound) {
16263     Expr::EvalResult Result;
16264     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
16265       return false; // Can't get the integer value as a constant.
16266 
16267     llvm::APSInt ConstLowerBound = Result.Val.getInt();
16268     if (ConstLowerBound.getSExtValue())
16269       return true;
16270   }
16271 
16272   // If we don't have a length we covering the whole dimension.
16273   if (!Length)
16274     return false;
16275 
16276   // If the base is a pointer, we don't have a way to get the size of the
16277   // pointee.
16278   if (BaseQTy->isPointerType())
16279     return false;
16280 
16281   // We can only check if the length is the same as the size of the dimension
16282   // if we have a constant array.
16283   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
16284   if (!CATy)
16285     return false;
16286 
16287   Expr::EvalResult Result;
16288   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16289     return false; // Can't get the integer value as a constant.
16290 
16291   llvm::APSInt ConstLength = Result.Val.getInt();
16292   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
16293 }
16294 
16295 // Return true if it can be proven that the provided array expression (array
16296 // section or array subscript) does NOT specify a single element of the array
16297 // whose base type is \a BaseQTy.
16298 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
16299                                                         const Expr *E,
16300                                                         QualType BaseQTy) {
16301   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16302 
16303   // An array subscript always refer to a single element. Also, an array section
16304   // assumes the format of an array subscript if no colon is used.
16305   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
16306     return false;
16307 
16308   assert(OASE && "Expecting array section if not an array subscript.");
16309   const Expr *Length = OASE->getLength();
16310 
16311   // If we don't have a length we have to check if the array has unitary size
16312   // for this dimension. Also, we should always expect a length if the base type
16313   // is pointer.
16314   if (!Length) {
16315     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16316       return ATy->getSize().getSExtValue() != 1;
16317     // We cannot assume anything.
16318     return false;
16319   }
16320 
16321   // Check if the length evaluates to 1.
16322   Expr::EvalResult Result;
16323   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16324     return false; // Can't get the integer value as a constant.
16325 
16326   llvm::APSInt ConstLength = Result.Val.getInt();
16327   return ConstLength.getSExtValue() != 1;
16328 }
16329 
16330 // The base of elements of list in a map clause have to be either:
16331 //  - a reference to variable or field.
16332 //  - a member expression.
16333 //  - an array expression.
16334 //
16335 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
16336 // reference to 'r'.
16337 //
16338 // If we have:
16339 //
16340 // struct SS {
16341 //   Bla S;
16342 //   foo() {
16343 //     #pragma omp target map (S.Arr[:12]);
16344 //   }
16345 // }
16346 //
16347 // We want to retrieve the member expression 'this->S';
16348 
16349 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
16350 //  If a list item is an array section, it must specify contiguous storage.
16351 //
16352 // For this restriction it is sufficient that we make sure only references
16353 // to variables or fields and array expressions, and that no array sections
16354 // exist except in the rightmost expression (unless they cover the whole
16355 // dimension of the array). E.g. these would be invalid:
16356 //
16357 //   r.ArrS[3:5].Arr[6:7]
16358 //
16359 //   r.ArrS[3:5].x
16360 //
16361 // but these would be valid:
16362 //   r.ArrS[3].Arr[6:7]
16363 //
16364 //   r.ArrS[3].x
16365 namespace {
16366 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
16367   Sema &SemaRef;
16368   OpenMPClauseKind CKind = OMPC_unknown;
16369   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
16370   bool NoDiagnose = false;
16371   const Expr *RelevantExpr = nullptr;
16372   bool AllowUnitySizeArraySection = true;
16373   bool AllowWholeSizeArraySection = true;
16374   SourceLocation ELoc;
16375   SourceRange ERange;
16376 
16377   void emitErrorMsg() {
16378     // If nothing else worked, this is not a valid map clause expression.
16379     if (SemaRef.getLangOpts().OpenMP < 50) {
16380       SemaRef.Diag(ELoc,
16381                    diag::err_omp_expected_named_var_member_or_array_expression)
16382           << ERange;
16383     } else {
16384       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
16385           << getOpenMPClauseName(CKind) << ERange;
16386     }
16387   }
16388 
16389 public:
16390   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
16391     if (!isa<VarDecl>(DRE->getDecl())) {
16392       emitErrorMsg();
16393       return false;
16394     }
16395     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16396     RelevantExpr = DRE;
16397     // Record the component.
16398     Components.emplace_back(DRE, DRE->getDecl());
16399     return true;
16400   }
16401 
16402   bool VisitMemberExpr(MemberExpr *ME) {
16403     Expr *E = ME;
16404     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
16405 
16406     if (isa<CXXThisExpr>(BaseE)) {
16407       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16408       // We found a base expression: this->Val.
16409       RelevantExpr = ME;
16410     } else {
16411       E = BaseE;
16412     }
16413 
16414     if (!isa<FieldDecl>(ME->getMemberDecl())) {
16415       if (!NoDiagnose) {
16416         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
16417           << ME->getSourceRange();
16418         return false;
16419       }
16420       if (RelevantExpr)
16421         return false;
16422       return Visit(E);
16423     }
16424 
16425     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
16426 
16427     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
16428     //  A bit-field cannot appear in a map clause.
16429     //
16430     if (FD->isBitField()) {
16431       if (!NoDiagnose) {
16432         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
16433           << ME->getSourceRange() << getOpenMPClauseName(CKind);
16434         return false;
16435       }
16436       if (RelevantExpr)
16437         return false;
16438       return Visit(E);
16439     }
16440 
16441     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16442     //  If the type of a list item is a reference to a type T then the type
16443     //  will be considered to be T for all purposes of this clause.
16444     QualType CurType = BaseE->getType().getNonReferenceType();
16445 
16446     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
16447     //  A list item cannot be a variable that is a member of a structure with
16448     //  a union type.
16449     //
16450     if (CurType->isUnionType()) {
16451       if (!NoDiagnose) {
16452         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
16453           << ME->getSourceRange();
16454         return false;
16455       }
16456       return RelevantExpr || Visit(E);
16457     }
16458 
16459     // If we got a member expression, we should not expect any array section
16460     // before that:
16461     //
16462     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
16463     //  If a list item is an element of a structure, only the rightmost symbol
16464     //  of the variable reference can be an array section.
16465     //
16466     AllowUnitySizeArraySection = false;
16467     AllowWholeSizeArraySection = false;
16468 
16469     // Record the component.
16470     Components.emplace_back(ME, FD);
16471     return RelevantExpr || Visit(E);
16472   }
16473 
16474   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
16475     Expr *E = AE->getBase()->IgnoreParenImpCasts();
16476 
16477     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
16478       if (!NoDiagnose) {
16479         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
16480           << 0 << AE->getSourceRange();
16481         return false;
16482       }
16483       return RelevantExpr || Visit(E);
16484     }
16485 
16486     // If we got an array subscript that express the whole dimension we
16487     // can have any array expressions before. If it only expressing part of
16488     // the dimension, we can only have unitary-size array expressions.
16489     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
16490                                                     E->getType()))
16491       AllowWholeSizeArraySection = false;
16492 
16493     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
16494       Expr::EvalResult Result;
16495       if (!AE->getIdx()->isValueDependent() &&
16496           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
16497           !Result.Val.getInt().isNullValue()) {
16498         SemaRef.Diag(AE->getIdx()->getExprLoc(),
16499                      diag::err_omp_invalid_map_this_expr);
16500         SemaRef.Diag(AE->getIdx()->getExprLoc(),
16501                      diag::note_omp_invalid_subscript_on_this_ptr_map);
16502       }
16503       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16504       RelevantExpr = TE;
16505     }
16506 
16507     // Record the component - we don't have any declaration associated.
16508     Components.emplace_back(AE, nullptr);
16509 
16510     return RelevantExpr || Visit(E);
16511   }
16512 
16513   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
16514     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
16515     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
16516     QualType CurType =
16517       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
16518 
16519     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16520     //  If the type of a list item is a reference to a type T then the type
16521     //  will be considered to be T for all purposes of this clause.
16522     if (CurType->isReferenceType())
16523       CurType = CurType->getPointeeType();
16524 
16525     bool IsPointer = CurType->isAnyPointerType();
16526 
16527     if (!IsPointer && !CurType->isArrayType()) {
16528       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
16529         << 0 << OASE->getSourceRange();
16530       return false;
16531     }
16532 
16533     bool NotWhole =
16534       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
16535     bool NotUnity =
16536       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
16537 
16538     if (AllowWholeSizeArraySection) {
16539       // Any array section is currently allowed. Allowing a whole size array
16540       // section implies allowing a unity array section as well.
16541       //
16542       // If this array section refers to the whole dimension we can still
16543       // accept other array sections before this one, except if the base is a
16544       // pointer. Otherwise, only unitary sections are accepted.
16545       if (NotWhole || IsPointer)
16546         AllowWholeSizeArraySection = false;
16547     } else if (AllowUnitySizeArraySection && NotUnity) {
16548       // A unity or whole array section is not allowed and that is not
16549       // compatible with the properties of the current array section.
16550       SemaRef.Diag(
16551         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
16552         << OASE->getSourceRange();
16553       return false;
16554     }
16555 
16556     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
16557       Expr::EvalResult ResultR;
16558       Expr::EvalResult ResultL;
16559       if (!OASE->getLength()->isValueDependent() &&
16560           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
16561           !ResultR.Val.getInt().isOneValue()) {
16562         SemaRef.Diag(OASE->getLength()->getExprLoc(),
16563                      diag::err_omp_invalid_map_this_expr);
16564         SemaRef.Diag(OASE->getLength()->getExprLoc(),
16565                      diag::note_omp_invalid_length_on_this_ptr_mapping);
16566       }
16567       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
16568           OASE->getLowerBound()->EvaluateAsInt(ResultL,
16569                                                SemaRef.getASTContext()) &&
16570           !ResultL.Val.getInt().isNullValue()) {
16571         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
16572                      diag::err_omp_invalid_map_this_expr);
16573         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
16574                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
16575       }
16576       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16577       RelevantExpr = TE;
16578     }
16579 
16580     // Record the component - we don't have any declaration associated.
16581     Components.emplace_back(OASE, nullptr);
16582     return RelevantExpr || Visit(E);
16583   }
16584   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
16585     Expr *Base = E->getBase();
16586 
16587     // Record the component - we don't have any declaration associated.
16588     Components.emplace_back(E, nullptr);
16589 
16590     return Visit(Base->IgnoreParenImpCasts());
16591   }
16592 
16593   bool VisitUnaryOperator(UnaryOperator *UO) {
16594     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
16595         UO->getOpcode() != UO_Deref) {
16596       emitErrorMsg();
16597       return false;
16598     }
16599     if (!RelevantExpr) {
16600       // Record the component if haven't found base decl.
16601       Components.emplace_back(UO, nullptr);
16602     }
16603     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
16604   }
16605   bool VisitBinaryOperator(BinaryOperator *BO) {
16606     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
16607       emitErrorMsg();
16608       return false;
16609     }
16610 
16611     // Pointer arithmetic is the only thing we expect to happen here so after we
16612     // make sure the binary operator is a pointer type, the we only thing need
16613     // to to is to visit the subtree that has the same type as root (so that we
16614     // know the other subtree is just an offset)
16615     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
16616     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
16617     Components.emplace_back(BO, nullptr);
16618     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
16619             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
16620            "Either LHS or RHS have base decl inside");
16621     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
16622       return RelevantExpr || Visit(LE);
16623     return RelevantExpr || Visit(RE);
16624   }
16625   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
16626     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16627     RelevantExpr = CTE;
16628     Components.emplace_back(CTE, nullptr);
16629     return true;
16630   }
16631   bool VisitStmt(Stmt *) {
16632     emitErrorMsg();
16633     return false;
16634   }
16635   const Expr *getFoundBase() const {
16636     return RelevantExpr;
16637   }
16638   explicit MapBaseChecker(
16639       Sema &SemaRef, OpenMPClauseKind CKind,
16640       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
16641       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
16642       : SemaRef(SemaRef), CKind(CKind), Components(Components),
16643         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
16644 };
16645 } // namespace
16646 
16647 /// Return the expression of the base of the mappable expression or null if it
16648 /// cannot be determined and do all the necessary checks to see if the expression
16649 /// is valid as a standalone mappable expression. In the process, record all the
16650 /// components of the expression.
16651 static const Expr *checkMapClauseExpressionBase(
16652     Sema &SemaRef, Expr *E,
16653     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
16654     OpenMPClauseKind CKind, bool NoDiagnose) {
16655   SourceLocation ELoc = E->getExprLoc();
16656   SourceRange ERange = E->getSourceRange();
16657   MapBaseChecker Checker(SemaRef, CKind, CurComponents, NoDiagnose, ELoc,
16658                          ERange);
16659   if (Checker.Visit(E->IgnoreParens()))
16660     return Checker.getFoundBase();
16661   return nullptr;
16662 }
16663 
16664 // Return true if expression E associated with value VD has conflicts with other
16665 // map information.
16666 static bool checkMapConflicts(
16667     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
16668     bool CurrentRegionOnly,
16669     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
16670     OpenMPClauseKind CKind) {
16671   assert(VD && E);
16672   SourceLocation ELoc = E->getExprLoc();
16673   SourceRange ERange = E->getSourceRange();
16674 
16675   // In order to easily check the conflicts we need to match each component of
16676   // the expression under test with the components of the expressions that are
16677   // already in the stack.
16678 
16679   assert(!CurComponents.empty() && "Map clause expression with no components!");
16680   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
16681          "Map clause expression with unexpected base!");
16682 
16683   // Variables to help detecting enclosing problems in data environment nests.
16684   bool IsEnclosedByDataEnvironmentExpr = false;
16685   const Expr *EnclosingExpr = nullptr;
16686 
16687   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
16688       VD, CurrentRegionOnly,
16689       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
16690        ERange, CKind, &EnclosingExpr,
16691        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
16692                           StackComponents,
16693                       OpenMPClauseKind) {
16694         assert(!StackComponents.empty() &&
16695                "Map clause expression with no components!");
16696         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
16697                "Map clause expression with unexpected base!");
16698         (void)VD;
16699 
16700         // The whole expression in the stack.
16701         const Expr *RE = StackComponents.front().getAssociatedExpression();
16702 
16703         // Expressions must start from the same base. Here we detect at which
16704         // point both expressions diverge from each other and see if we can
16705         // detect if the memory referred to both expressions is contiguous and
16706         // do not overlap.
16707         auto CI = CurComponents.rbegin();
16708         auto CE = CurComponents.rend();
16709         auto SI = StackComponents.rbegin();
16710         auto SE = StackComponents.rend();
16711         for (; CI != CE && SI != SE; ++CI, ++SI) {
16712 
16713           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
16714           //  At most one list item can be an array item derived from a given
16715           //  variable in map clauses of the same construct.
16716           if (CurrentRegionOnly &&
16717               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
16718                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
16719                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
16720               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
16721                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
16722                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
16723             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
16724                          diag::err_omp_multiple_array_items_in_map_clause)
16725                 << CI->getAssociatedExpression()->getSourceRange();
16726             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
16727                          diag::note_used_here)
16728                 << SI->getAssociatedExpression()->getSourceRange();
16729             return true;
16730           }
16731 
16732           // Do both expressions have the same kind?
16733           if (CI->getAssociatedExpression()->getStmtClass() !=
16734               SI->getAssociatedExpression()->getStmtClass())
16735             break;
16736 
16737           // Are we dealing with different variables/fields?
16738           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
16739             break;
16740         }
16741         // Check if the extra components of the expressions in the enclosing
16742         // data environment are redundant for the current base declaration.
16743         // If they are, the maps completely overlap, which is legal.
16744         for (; SI != SE; ++SI) {
16745           QualType Type;
16746           if (const auto *ASE =
16747                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
16748             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
16749           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
16750                          SI->getAssociatedExpression())) {
16751             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
16752             Type =
16753                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
16754           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
16755                          SI->getAssociatedExpression())) {
16756             Type = OASE->getBase()->getType()->getPointeeType();
16757           }
16758           if (Type.isNull() || Type->isAnyPointerType() ||
16759               checkArrayExpressionDoesNotReferToWholeSize(
16760                   SemaRef, SI->getAssociatedExpression(), Type))
16761             break;
16762         }
16763 
16764         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
16765         //  List items of map clauses in the same construct must not share
16766         //  original storage.
16767         //
16768         // If the expressions are exactly the same or one is a subset of the
16769         // other, it means they are sharing storage.
16770         if (CI == CE && SI == SE) {
16771           if (CurrentRegionOnly) {
16772             if (CKind == OMPC_map) {
16773               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
16774             } else {
16775               assert(CKind == OMPC_to || CKind == OMPC_from);
16776               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
16777                   << ERange;
16778             }
16779             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
16780                 << RE->getSourceRange();
16781             return true;
16782           }
16783           // If we find the same expression in the enclosing data environment,
16784           // that is legal.
16785           IsEnclosedByDataEnvironmentExpr = true;
16786           return false;
16787         }
16788 
16789         QualType DerivedType =
16790             std::prev(CI)->getAssociatedDeclaration()->getType();
16791         SourceLocation DerivedLoc =
16792             std::prev(CI)->getAssociatedExpression()->getExprLoc();
16793 
16794         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16795         //  If the type of a list item is a reference to a type T then the type
16796         //  will be considered to be T for all purposes of this clause.
16797         DerivedType = DerivedType.getNonReferenceType();
16798 
16799         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
16800         //  A variable for which the type is pointer and an array section
16801         //  derived from that variable must not appear as list items of map
16802         //  clauses of the same construct.
16803         //
16804         // Also, cover one of the cases in:
16805         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
16806         //  If any part of the original storage of a list item has corresponding
16807         //  storage in the device data environment, all of the original storage
16808         //  must have corresponding storage in the device data environment.
16809         //
16810         if (DerivedType->isAnyPointerType()) {
16811           if (CI == CE || SI == SE) {
16812             SemaRef.Diag(
16813                 DerivedLoc,
16814                 diag::err_omp_pointer_mapped_along_with_derived_section)
16815                 << DerivedLoc;
16816             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
16817                 << RE->getSourceRange();
16818             return true;
16819           }
16820           if (CI->getAssociatedExpression()->getStmtClass() !=
16821                          SI->getAssociatedExpression()->getStmtClass() ||
16822                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
16823                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
16824             assert(CI != CE && SI != SE);
16825             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
16826                 << DerivedLoc;
16827             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
16828                 << RE->getSourceRange();
16829             return true;
16830           }
16831         }
16832 
16833         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
16834         //  List items of map clauses in the same construct must not share
16835         //  original storage.
16836         //
16837         // An expression is a subset of the other.
16838         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
16839           if (CKind == OMPC_map) {
16840             if (CI != CE || SI != SE) {
16841               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
16842               // a pointer.
16843               auto Begin =
16844                   CI != CE ? CurComponents.begin() : StackComponents.begin();
16845               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
16846               auto It = Begin;
16847               while (It != End && !It->getAssociatedDeclaration())
16848                 std::advance(It, 1);
16849               assert(It != End &&
16850                      "Expected at least one component with the declaration.");
16851               if (It != Begin && It->getAssociatedDeclaration()
16852                                      ->getType()
16853                                      .getCanonicalType()
16854                                      ->isAnyPointerType()) {
16855                 IsEnclosedByDataEnvironmentExpr = false;
16856                 EnclosingExpr = nullptr;
16857                 return false;
16858               }
16859             }
16860             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
16861           } else {
16862             assert(CKind == OMPC_to || CKind == OMPC_from);
16863             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
16864                 << ERange;
16865           }
16866           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
16867               << RE->getSourceRange();
16868           return true;
16869         }
16870 
16871         // The current expression uses the same base as other expression in the
16872         // data environment but does not contain it completely.
16873         if (!CurrentRegionOnly && SI != SE)
16874           EnclosingExpr = RE;
16875 
16876         // The current expression is a subset of the expression in the data
16877         // environment.
16878         IsEnclosedByDataEnvironmentExpr |=
16879             (!CurrentRegionOnly && CI != CE && SI == SE);
16880 
16881         return false;
16882       });
16883 
16884   if (CurrentRegionOnly)
16885     return FoundError;
16886 
16887   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
16888   //  If any part of the original storage of a list item has corresponding
16889   //  storage in the device data environment, all of the original storage must
16890   //  have corresponding storage in the device data environment.
16891   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
16892   //  If a list item is an element of a structure, and a different element of
16893   //  the structure has a corresponding list item in the device data environment
16894   //  prior to a task encountering the construct associated with the map clause,
16895   //  then the list item must also have a corresponding list item in the device
16896   //  data environment prior to the task encountering the construct.
16897   //
16898   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
16899     SemaRef.Diag(ELoc,
16900                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
16901         << ERange;
16902     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
16903         << EnclosingExpr->getSourceRange();
16904     return true;
16905   }
16906 
16907   return FoundError;
16908 }
16909 
16910 // Look up the user-defined mapper given the mapper name and mapped type, and
16911 // build a reference to it.
16912 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
16913                                             CXXScopeSpec &MapperIdScopeSpec,
16914                                             const DeclarationNameInfo &MapperId,
16915                                             QualType Type,
16916                                             Expr *UnresolvedMapper) {
16917   if (MapperIdScopeSpec.isInvalid())
16918     return ExprError();
16919   // Get the actual type for the array type.
16920   if (Type->isArrayType()) {
16921     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
16922     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
16923   }
16924   // Find all user-defined mappers with the given MapperId.
16925   SmallVector<UnresolvedSet<8>, 4> Lookups;
16926   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
16927   Lookup.suppressDiagnostics();
16928   if (S) {
16929     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
16930       NamedDecl *D = Lookup.getRepresentativeDecl();
16931       while (S && !S->isDeclScope(D))
16932         S = S->getParent();
16933       if (S)
16934         S = S->getParent();
16935       Lookups.emplace_back();
16936       Lookups.back().append(Lookup.begin(), Lookup.end());
16937       Lookup.clear();
16938     }
16939   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
16940     // Extract the user-defined mappers with the given MapperId.
16941     Lookups.push_back(UnresolvedSet<8>());
16942     for (NamedDecl *D : ULE->decls()) {
16943       auto *DMD = cast<OMPDeclareMapperDecl>(D);
16944       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
16945       Lookups.back().addDecl(DMD);
16946     }
16947   }
16948   // Defer the lookup for dependent types. The results will be passed through
16949   // UnresolvedMapper on instantiation.
16950   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
16951       Type->isInstantiationDependentType() ||
16952       Type->containsUnexpandedParameterPack() ||
16953       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16954         return !D->isInvalidDecl() &&
16955                (D->getType()->isDependentType() ||
16956                 D->getType()->isInstantiationDependentType() ||
16957                 D->getType()->containsUnexpandedParameterPack());
16958       })) {
16959     UnresolvedSet<8> URS;
16960     for (const UnresolvedSet<8> &Set : Lookups) {
16961       if (Set.empty())
16962         continue;
16963       URS.append(Set.begin(), Set.end());
16964     }
16965     return UnresolvedLookupExpr::Create(
16966         SemaRef.Context, /*NamingClass=*/nullptr,
16967         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
16968         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
16969   }
16970   SourceLocation Loc = MapperId.getLoc();
16971   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16972   //  The type must be of struct, union or class type in C and C++
16973   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
16974       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
16975     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
16976     return ExprError();
16977   }
16978   // Perform argument dependent lookup.
16979   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
16980     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
16981   // Return the first user-defined mapper with the desired type.
16982   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16983           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
16984             if (!D->isInvalidDecl() &&
16985                 SemaRef.Context.hasSameType(D->getType(), Type))
16986               return D;
16987             return nullptr;
16988           }))
16989     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
16990   // Find the first user-defined mapper with a type derived from the desired
16991   // type.
16992   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16993           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
16994             if (!D->isInvalidDecl() &&
16995                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
16996                 !Type.isMoreQualifiedThan(D->getType()))
16997               return D;
16998             return nullptr;
16999           })) {
17000     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
17001                        /*DetectVirtual=*/false);
17002     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
17003       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
17004               VD->getType().getUnqualifiedType()))) {
17005         if (SemaRef.CheckBaseClassAccess(
17006                 Loc, VD->getType(), Type, Paths.front(),
17007                 /*DiagID=*/0) != Sema::AR_inaccessible) {
17008           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17009         }
17010       }
17011     }
17012   }
17013   // Report error if a mapper is specified, but cannot be found.
17014   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
17015     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
17016         << Type << MapperId.getName();
17017     return ExprError();
17018   }
17019   return ExprEmpty();
17020 }
17021 
17022 namespace {
17023 // Utility struct that gathers all the related lists associated with a mappable
17024 // expression.
17025 struct MappableVarListInfo {
17026   // The list of expressions.
17027   ArrayRef<Expr *> VarList;
17028   // The list of processed expressions.
17029   SmallVector<Expr *, 16> ProcessedVarList;
17030   // The mappble components for each expression.
17031   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
17032   // The base declaration of the variable.
17033   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
17034   // The reference to the user-defined mapper associated with every expression.
17035   SmallVector<Expr *, 16> UDMapperList;
17036 
17037   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
17038     // We have a list of components and base declarations for each entry in the
17039     // variable list.
17040     VarComponents.reserve(VarList.size());
17041     VarBaseDeclarations.reserve(VarList.size());
17042   }
17043 };
17044 }
17045 
17046 // Check the validity of the provided variable list for the provided clause kind
17047 // \a CKind. In the check process the valid expressions, mappable expression
17048 // components, variables, and user-defined mappers are extracted and used to
17049 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
17050 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
17051 // and \a MapperId are expected to be valid if the clause kind is 'map'.
17052 static void checkMappableExpressionList(
17053     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
17054     MappableVarListInfo &MVLI, SourceLocation StartLoc,
17055     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
17056     ArrayRef<Expr *> UnresolvedMappers,
17057     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
17058     bool IsMapTypeImplicit = false) {
17059   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
17060   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
17061          "Unexpected clause kind with mappable expressions!");
17062 
17063   // If the identifier of user-defined mapper is not specified, it is "default".
17064   // We do not change the actual name in this clause to distinguish whether a
17065   // mapper is specified explicitly, i.e., it is not explicitly specified when
17066   // MapperId.getName() is empty.
17067   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
17068     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
17069     MapperId.setName(DeclNames.getIdentifier(
17070         &SemaRef.getASTContext().Idents.get("default")));
17071   }
17072 
17073   // Iterators to find the current unresolved mapper expression.
17074   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
17075   bool UpdateUMIt = false;
17076   Expr *UnresolvedMapper = nullptr;
17077 
17078   // Keep track of the mappable components and base declarations in this clause.
17079   // Each entry in the list is going to have a list of components associated. We
17080   // record each set of the components so that we can build the clause later on.
17081   // In the end we should have the same amount of declarations and component
17082   // lists.
17083 
17084   for (Expr *RE : MVLI.VarList) {
17085     assert(RE && "Null expr in omp to/from/map clause");
17086     SourceLocation ELoc = RE->getExprLoc();
17087 
17088     // Find the current unresolved mapper expression.
17089     if (UpdateUMIt && UMIt != UMEnd) {
17090       UMIt++;
17091       assert(
17092           UMIt != UMEnd &&
17093           "Expect the size of UnresolvedMappers to match with that of VarList");
17094     }
17095     UpdateUMIt = true;
17096     if (UMIt != UMEnd)
17097       UnresolvedMapper = *UMIt;
17098 
17099     const Expr *VE = RE->IgnoreParenLValueCasts();
17100 
17101     if (VE->isValueDependent() || VE->isTypeDependent() ||
17102         VE->isInstantiationDependent() ||
17103         VE->containsUnexpandedParameterPack()) {
17104       // Try to find the associated user-defined mapper.
17105       ExprResult ER = buildUserDefinedMapperRef(
17106           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17107           VE->getType().getCanonicalType(), UnresolvedMapper);
17108       if (ER.isInvalid())
17109         continue;
17110       MVLI.UDMapperList.push_back(ER.get());
17111       // We can only analyze this information once the missing information is
17112       // resolved.
17113       MVLI.ProcessedVarList.push_back(RE);
17114       continue;
17115     }
17116 
17117     Expr *SimpleExpr = RE->IgnoreParenCasts();
17118 
17119     if (!RE->isLValue()) {
17120       if (SemaRef.getLangOpts().OpenMP < 50) {
17121         SemaRef.Diag(
17122             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
17123             << RE->getSourceRange();
17124       } else {
17125         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
17126             << getOpenMPClauseName(CKind) << RE->getSourceRange();
17127       }
17128       continue;
17129     }
17130 
17131     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
17132     ValueDecl *CurDeclaration = nullptr;
17133 
17134     // Obtain the array or member expression bases if required. Also, fill the
17135     // components array with all the components identified in the process.
17136     const Expr *BE = checkMapClauseExpressionBase(
17137         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
17138     if (!BE)
17139       continue;
17140 
17141     assert(!CurComponents.empty() &&
17142            "Invalid mappable expression information.");
17143 
17144     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
17145       // Add store "this" pointer to class in DSAStackTy for future checking
17146       DSAS->addMappedClassesQualTypes(TE->getType());
17147       // Try to find the associated user-defined mapper.
17148       ExprResult ER = buildUserDefinedMapperRef(
17149           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17150           VE->getType().getCanonicalType(), UnresolvedMapper);
17151       if (ER.isInvalid())
17152         continue;
17153       MVLI.UDMapperList.push_back(ER.get());
17154       // Skip restriction checking for variable or field declarations
17155       MVLI.ProcessedVarList.push_back(RE);
17156       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17157       MVLI.VarComponents.back().append(CurComponents.begin(),
17158                                        CurComponents.end());
17159       MVLI.VarBaseDeclarations.push_back(nullptr);
17160       continue;
17161     }
17162 
17163     // For the following checks, we rely on the base declaration which is
17164     // expected to be associated with the last component. The declaration is
17165     // expected to be a variable or a field (if 'this' is being mapped).
17166     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
17167     assert(CurDeclaration && "Null decl on map clause.");
17168     assert(
17169         CurDeclaration->isCanonicalDecl() &&
17170         "Expecting components to have associated only canonical declarations.");
17171 
17172     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
17173     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
17174 
17175     assert((VD || FD) && "Only variables or fields are expected here!");
17176     (void)FD;
17177 
17178     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
17179     // threadprivate variables cannot appear in a map clause.
17180     // OpenMP 4.5 [2.10.5, target update Construct]
17181     // threadprivate variables cannot appear in a from clause.
17182     if (VD && DSAS->isThreadPrivate(VD)) {
17183       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17184       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
17185           << getOpenMPClauseName(CKind);
17186       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
17187       continue;
17188     }
17189 
17190     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17191     //  A list item cannot appear in both a map clause and a data-sharing
17192     //  attribute clause on the same construct.
17193 
17194     // Check conflicts with other map clause expressions. We check the conflicts
17195     // with the current construct separately from the enclosing data
17196     // environment, because the restrictions are different. We only have to
17197     // check conflicts across regions for the map clauses.
17198     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17199                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
17200       break;
17201     if (CKind == OMPC_map &&
17202         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17203                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
17204       break;
17205 
17206     // OpenMP 4.5 [2.10.5, target update Construct]
17207     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17208     //  If the type of a list item is a reference to a type T then the type will
17209     //  be considered to be T for all purposes of this clause.
17210     auto I = llvm::find_if(
17211         CurComponents,
17212         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
17213           return MC.getAssociatedDeclaration();
17214         });
17215     assert(I != CurComponents.end() && "Null decl on map clause.");
17216     QualType Type;
17217     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
17218     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
17219     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
17220     if (ASE) {
17221       Type = ASE->getType().getNonReferenceType();
17222     } else if (OASE) {
17223       QualType BaseType =
17224           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17225       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17226         Type = ATy->getElementType();
17227       else
17228         Type = BaseType->getPointeeType();
17229       Type = Type.getNonReferenceType();
17230     } else if (OAShE) {
17231       Type = OAShE->getBase()->getType()->getPointeeType();
17232     } else {
17233       Type = VE->getType();
17234     }
17235 
17236     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
17237     // A list item in a to or from clause must have a mappable type.
17238     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17239     //  A list item must have a mappable type.
17240     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
17241                            DSAS, Type))
17242       continue;
17243 
17244     Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
17245 
17246     if (CKind == OMPC_map) {
17247       // target enter data
17248       // OpenMP [2.10.2, Restrictions, p. 99]
17249       // A map-type must be specified in all map clauses and must be either
17250       // to or alloc.
17251       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
17252       if (DKind == OMPD_target_enter_data &&
17253           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
17254         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17255             << (IsMapTypeImplicit ? 1 : 0)
17256             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17257             << getOpenMPDirectiveName(DKind);
17258         continue;
17259       }
17260 
17261       // target exit_data
17262       // OpenMP [2.10.3, Restrictions, p. 102]
17263       // A map-type must be specified in all map clauses and must be either
17264       // from, release, or delete.
17265       if (DKind == OMPD_target_exit_data &&
17266           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
17267             MapType == OMPC_MAP_delete)) {
17268         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17269             << (IsMapTypeImplicit ? 1 : 0)
17270             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17271             << getOpenMPDirectiveName(DKind);
17272         continue;
17273       }
17274 
17275       // target, target data
17276       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
17277       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
17278       // A map-type in a map clause must be to, from, tofrom or alloc
17279       if ((DKind == OMPD_target_data ||
17280            isOpenMPTargetExecutionDirective(DKind)) &&
17281           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
17282             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
17283         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17284             << (IsMapTypeImplicit ? 1 : 0)
17285             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17286             << getOpenMPDirectiveName(DKind);
17287         continue;
17288       }
17289 
17290       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17291       // A list item cannot appear in both a map clause and a data-sharing
17292       // attribute clause on the same construct
17293       //
17294       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17295       // A list item cannot appear in both a map clause and a data-sharing
17296       // attribute clause on the same construct unless the construct is a
17297       // combined construct.
17298       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
17299                   isOpenMPTargetExecutionDirective(DKind)) ||
17300                  DKind == OMPD_target)) {
17301         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17302         if (isOpenMPPrivate(DVar.CKind)) {
17303           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17304               << getOpenMPClauseName(DVar.CKind)
17305               << getOpenMPClauseName(OMPC_map)
17306               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
17307           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
17308           continue;
17309         }
17310       }
17311     }
17312 
17313     // Try to find the associated user-defined mapper.
17314     ExprResult ER = buildUserDefinedMapperRef(
17315         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17316         Type.getCanonicalType(), UnresolvedMapper);
17317     if (ER.isInvalid())
17318       continue;
17319     MVLI.UDMapperList.push_back(ER.get());
17320 
17321     // Save the current expression.
17322     MVLI.ProcessedVarList.push_back(RE);
17323 
17324     // Store the components in the stack so that they can be used to check
17325     // against other clauses later on.
17326     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
17327                                           /*WhereFoundClauseKind=*/OMPC_map);
17328 
17329     // Save the components and declaration to create the clause. For purposes of
17330     // the clause creation, any component list that has has base 'this' uses
17331     // null as base declaration.
17332     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17333     MVLI.VarComponents.back().append(CurComponents.begin(),
17334                                      CurComponents.end());
17335     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
17336                                                            : CurDeclaration);
17337   }
17338 }
17339 
17340 OMPClause *Sema::ActOnOpenMPMapClause(
17341     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
17342     ArrayRef<SourceLocation> MapTypeModifiersLoc,
17343     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
17344     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
17345     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
17346     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
17347   OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
17348                                        OMPC_MAP_MODIFIER_unknown,
17349                                        OMPC_MAP_MODIFIER_unknown};
17350   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
17351 
17352   // Process map-type-modifiers, flag errors for duplicate modifiers.
17353   unsigned Count = 0;
17354   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
17355     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
17356         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
17357       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
17358       continue;
17359     }
17360     assert(Count < NumberOfOMPMapClauseModifiers &&
17361            "Modifiers exceed the allowed number of map type modifiers");
17362     Modifiers[Count] = MapTypeModifiers[I];
17363     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
17364     ++Count;
17365   }
17366 
17367   MappableVarListInfo MVLI(VarList);
17368   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
17369                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
17370                               MapType, IsMapTypeImplicit);
17371 
17372   // We need to produce a map clause even if we don't have variables so that
17373   // other diagnostics related with non-existing map clauses are accurate.
17374   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
17375                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
17376                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
17377                               MapperIdScopeSpec.getWithLocInContext(Context),
17378                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
17379 }
17380 
17381 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
17382                                                TypeResult ParsedType) {
17383   assert(ParsedType.isUsable());
17384 
17385   QualType ReductionType = GetTypeFromParser(ParsedType.get());
17386   if (ReductionType.isNull())
17387     return QualType();
17388 
17389   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
17390   // A type name in a declare reduction directive cannot be a function type, an
17391   // array type, a reference type, or a type qualified with const, volatile or
17392   // restrict.
17393   if (ReductionType.hasQualifiers()) {
17394     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
17395     return QualType();
17396   }
17397 
17398   if (ReductionType->isFunctionType()) {
17399     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
17400     return QualType();
17401   }
17402   if (ReductionType->isReferenceType()) {
17403     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
17404     return QualType();
17405   }
17406   if (ReductionType->isArrayType()) {
17407     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
17408     return QualType();
17409   }
17410   return ReductionType;
17411 }
17412 
17413 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
17414     Scope *S, DeclContext *DC, DeclarationName Name,
17415     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
17416     AccessSpecifier AS, Decl *PrevDeclInScope) {
17417   SmallVector<Decl *, 8> Decls;
17418   Decls.reserve(ReductionTypes.size());
17419 
17420   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
17421                       forRedeclarationInCurContext());
17422   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
17423   // A reduction-identifier may not be re-declared in the current scope for the
17424   // same type or for a type that is compatible according to the base language
17425   // rules.
17426   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
17427   OMPDeclareReductionDecl *PrevDRD = nullptr;
17428   bool InCompoundScope = true;
17429   if (S != nullptr) {
17430     // Find previous declaration with the same name not referenced in other
17431     // declarations.
17432     FunctionScopeInfo *ParentFn = getEnclosingFunction();
17433     InCompoundScope =
17434         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
17435     LookupName(Lookup, S);
17436     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
17437                          /*AllowInlineNamespace=*/false);
17438     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
17439     LookupResult::Filter Filter = Lookup.makeFilter();
17440     while (Filter.hasNext()) {
17441       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
17442       if (InCompoundScope) {
17443         auto I = UsedAsPrevious.find(PrevDecl);
17444         if (I == UsedAsPrevious.end())
17445           UsedAsPrevious[PrevDecl] = false;
17446         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
17447           UsedAsPrevious[D] = true;
17448       }
17449       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
17450           PrevDecl->getLocation();
17451     }
17452     Filter.done();
17453     if (InCompoundScope) {
17454       for (const auto &PrevData : UsedAsPrevious) {
17455         if (!PrevData.second) {
17456           PrevDRD = PrevData.first;
17457           break;
17458         }
17459       }
17460     }
17461   } else if (PrevDeclInScope != nullptr) {
17462     auto *PrevDRDInScope = PrevDRD =
17463         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
17464     do {
17465       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
17466           PrevDRDInScope->getLocation();
17467       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
17468     } while (PrevDRDInScope != nullptr);
17469   }
17470   for (const auto &TyData : ReductionTypes) {
17471     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
17472     bool Invalid = false;
17473     if (I != PreviousRedeclTypes.end()) {
17474       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
17475           << TyData.first;
17476       Diag(I->second, diag::note_previous_definition);
17477       Invalid = true;
17478     }
17479     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
17480     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
17481                                                 Name, TyData.first, PrevDRD);
17482     DC->addDecl(DRD);
17483     DRD->setAccess(AS);
17484     Decls.push_back(DRD);
17485     if (Invalid)
17486       DRD->setInvalidDecl();
17487     else
17488       PrevDRD = DRD;
17489   }
17490 
17491   return DeclGroupPtrTy::make(
17492       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
17493 }
17494 
17495 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
17496   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17497 
17498   // Enter new function scope.
17499   PushFunctionScope();
17500   setFunctionHasBranchProtectedScope();
17501   getCurFunction()->setHasOMPDeclareReductionCombiner();
17502 
17503   if (S != nullptr)
17504     PushDeclContext(S, DRD);
17505   else
17506     CurContext = DRD;
17507 
17508   PushExpressionEvaluationContext(
17509       ExpressionEvaluationContext::PotentiallyEvaluated);
17510 
17511   QualType ReductionType = DRD->getType();
17512   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
17513   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
17514   // uses semantics of argument handles by value, but it should be passed by
17515   // reference. C lang does not support references, so pass all parameters as
17516   // pointers.
17517   // Create 'T omp_in;' variable.
17518   VarDecl *OmpInParm =
17519       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
17520   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
17521   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
17522   // uses semantics of argument handles by value, but it should be passed by
17523   // reference. C lang does not support references, so pass all parameters as
17524   // pointers.
17525   // Create 'T omp_out;' variable.
17526   VarDecl *OmpOutParm =
17527       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
17528   if (S != nullptr) {
17529     PushOnScopeChains(OmpInParm, S);
17530     PushOnScopeChains(OmpOutParm, S);
17531   } else {
17532     DRD->addDecl(OmpInParm);
17533     DRD->addDecl(OmpOutParm);
17534   }
17535   Expr *InE =
17536       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
17537   Expr *OutE =
17538       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
17539   DRD->setCombinerData(InE, OutE);
17540 }
17541 
17542 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
17543   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17544   DiscardCleanupsInEvaluationContext();
17545   PopExpressionEvaluationContext();
17546 
17547   PopDeclContext();
17548   PopFunctionScopeInfo();
17549 
17550   if (Combiner != nullptr)
17551     DRD->setCombiner(Combiner);
17552   else
17553     DRD->setInvalidDecl();
17554 }
17555 
17556 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
17557   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17558 
17559   // Enter new function scope.
17560   PushFunctionScope();
17561   setFunctionHasBranchProtectedScope();
17562 
17563   if (S != nullptr)
17564     PushDeclContext(S, DRD);
17565   else
17566     CurContext = DRD;
17567 
17568   PushExpressionEvaluationContext(
17569       ExpressionEvaluationContext::PotentiallyEvaluated);
17570 
17571   QualType ReductionType = DRD->getType();
17572   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
17573   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
17574   // uses semantics of argument handles by value, but it should be passed by
17575   // reference. C lang does not support references, so pass all parameters as
17576   // pointers.
17577   // Create 'T omp_priv;' variable.
17578   VarDecl *OmpPrivParm =
17579       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
17580   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
17581   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
17582   // uses semantics of argument handles by value, but it should be passed by
17583   // reference. C lang does not support references, so pass all parameters as
17584   // pointers.
17585   // Create 'T omp_orig;' variable.
17586   VarDecl *OmpOrigParm =
17587       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
17588   if (S != nullptr) {
17589     PushOnScopeChains(OmpPrivParm, S);
17590     PushOnScopeChains(OmpOrigParm, S);
17591   } else {
17592     DRD->addDecl(OmpPrivParm);
17593     DRD->addDecl(OmpOrigParm);
17594   }
17595   Expr *OrigE =
17596       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
17597   Expr *PrivE =
17598       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
17599   DRD->setInitializerData(OrigE, PrivE);
17600   return OmpPrivParm;
17601 }
17602 
17603 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
17604                                                      VarDecl *OmpPrivParm) {
17605   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17606   DiscardCleanupsInEvaluationContext();
17607   PopExpressionEvaluationContext();
17608 
17609   PopDeclContext();
17610   PopFunctionScopeInfo();
17611 
17612   if (Initializer != nullptr) {
17613     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
17614   } else if (OmpPrivParm->hasInit()) {
17615     DRD->setInitializer(OmpPrivParm->getInit(),
17616                         OmpPrivParm->isDirectInit()
17617                             ? OMPDeclareReductionDecl::DirectInit
17618                             : OMPDeclareReductionDecl::CopyInit);
17619   } else {
17620     DRD->setInvalidDecl();
17621   }
17622 }
17623 
17624 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
17625     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
17626   for (Decl *D : DeclReductions.get()) {
17627     if (IsValid) {
17628       if (S)
17629         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
17630                           /*AddToContext=*/false);
17631     } else {
17632       D->setInvalidDecl();
17633     }
17634   }
17635   return DeclReductions;
17636 }
17637 
17638 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
17639   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17640   QualType T = TInfo->getType();
17641   if (D.isInvalidType())
17642     return true;
17643 
17644   if (getLangOpts().CPlusPlus) {
17645     // Check that there are no default arguments (C++ only).
17646     CheckExtraCXXDefaultArguments(D);
17647   }
17648 
17649   return CreateParsedType(T, TInfo);
17650 }
17651 
17652 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
17653                                             TypeResult ParsedType) {
17654   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
17655 
17656   QualType MapperType = GetTypeFromParser(ParsedType.get());
17657   assert(!MapperType.isNull() && "Expect valid mapper type");
17658 
17659   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17660   //  The type must be of struct, union or class type in C and C++
17661   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
17662     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
17663     return QualType();
17664   }
17665   return MapperType;
17666 }
17667 
17668 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
17669     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
17670     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
17671     Decl *PrevDeclInScope) {
17672   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
17673                       forRedeclarationInCurContext());
17674   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17675   //  A mapper-identifier may not be redeclared in the current scope for the
17676   //  same type or for a type that is compatible according to the base language
17677   //  rules.
17678   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
17679   OMPDeclareMapperDecl *PrevDMD = nullptr;
17680   bool InCompoundScope = true;
17681   if (S != nullptr) {
17682     // Find previous declaration with the same name not referenced in other
17683     // declarations.
17684     FunctionScopeInfo *ParentFn = getEnclosingFunction();
17685     InCompoundScope =
17686         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
17687     LookupName(Lookup, S);
17688     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
17689                          /*AllowInlineNamespace=*/false);
17690     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
17691     LookupResult::Filter Filter = Lookup.makeFilter();
17692     while (Filter.hasNext()) {
17693       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
17694       if (InCompoundScope) {
17695         auto I = UsedAsPrevious.find(PrevDecl);
17696         if (I == UsedAsPrevious.end())
17697           UsedAsPrevious[PrevDecl] = false;
17698         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
17699           UsedAsPrevious[D] = true;
17700       }
17701       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
17702           PrevDecl->getLocation();
17703     }
17704     Filter.done();
17705     if (InCompoundScope) {
17706       for (const auto &PrevData : UsedAsPrevious) {
17707         if (!PrevData.second) {
17708           PrevDMD = PrevData.first;
17709           break;
17710         }
17711       }
17712     }
17713   } else if (PrevDeclInScope) {
17714     auto *PrevDMDInScope = PrevDMD =
17715         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
17716     do {
17717       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
17718           PrevDMDInScope->getLocation();
17719       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
17720     } while (PrevDMDInScope != nullptr);
17721   }
17722   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
17723   bool Invalid = false;
17724   if (I != PreviousRedeclTypes.end()) {
17725     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
17726         << MapperType << Name;
17727     Diag(I->second, diag::note_previous_definition);
17728     Invalid = true;
17729   }
17730   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
17731                                            MapperType, VN, PrevDMD);
17732   DC->addDecl(DMD);
17733   DMD->setAccess(AS);
17734   if (Invalid)
17735     DMD->setInvalidDecl();
17736 
17737   // Enter new function scope.
17738   PushFunctionScope();
17739   setFunctionHasBranchProtectedScope();
17740 
17741   CurContext = DMD;
17742 
17743   return DMD;
17744 }
17745 
17746 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
17747                                                     Scope *S,
17748                                                     QualType MapperType,
17749                                                     SourceLocation StartLoc,
17750                                                     DeclarationName VN) {
17751   VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
17752   if (S)
17753     PushOnScopeChains(VD, S);
17754   else
17755     DMD->addDecl(VD);
17756   Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
17757   DMD->setMapperVarRef(MapperVarRefExpr);
17758 }
17759 
17760 Sema::DeclGroupPtrTy
17761 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
17762                                            ArrayRef<OMPClause *> ClauseList) {
17763   PopDeclContext();
17764   PopFunctionScopeInfo();
17765 
17766   if (D) {
17767     if (S)
17768       PushOnScopeChains(D, S, /*AddToContext=*/false);
17769     D->CreateClauses(Context, ClauseList);
17770   }
17771 
17772   return DeclGroupPtrTy::make(DeclGroupRef(D));
17773 }
17774 
17775 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
17776                                            SourceLocation StartLoc,
17777                                            SourceLocation LParenLoc,
17778                                            SourceLocation EndLoc) {
17779   Expr *ValExpr = NumTeams;
17780   Stmt *HelperValStmt = nullptr;
17781 
17782   // OpenMP [teams Constrcut, Restrictions]
17783   // The num_teams expression must evaluate to a positive integer value.
17784   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
17785                                  /*StrictlyPositive=*/true))
17786     return nullptr;
17787 
17788   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
17789   OpenMPDirectiveKind CaptureRegion =
17790       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
17791   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
17792     ValExpr = MakeFullExpr(ValExpr).get();
17793     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
17794     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
17795     HelperValStmt = buildPreInits(Context, Captures);
17796   }
17797 
17798   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
17799                                          StartLoc, LParenLoc, EndLoc);
17800 }
17801 
17802 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
17803                                               SourceLocation StartLoc,
17804                                               SourceLocation LParenLoc,
17805                                               SourceLocation EndLoc) {
17806   Expr *ValExpr = ThreadLimit;
17807   Stmt *HelperValStmt = nullptr;
17808 
17809   // OpenMP [teams Constrcut, Restrictions]
17810   // The thread_limit expression must evaluate to a positive integer value.
17811   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
17812                                  /*StrictlyPositive=*/true))
17813     return nullptr;
17814 
17815   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
17816   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
17817       DKind, OMPC_thread_limit, LangOpts.OpenMP);
17818   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
17819     ValExpr = MakeFullExpr(ValExpr).get();
17820     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
17821     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
17822     HelperValStmt = buildPreInits(Context, Captures);
17823   }
17824 
17825   return new (Context) OMPThreadLimitClause(
17826       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
17827 }
17828 
17829 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
17830                                            SourceLocation StartLoc,
17831                                            SourceLocation LParenLoc,
17832                                            SourceLocation EndLoc) {
17833   Expr *ValExpr = Priority;
17834   Stmt *HelperValStmt = nullptr;
17835   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
17836 
17837   // OpenMP [2.9.1, task Constrcut]
17838   // The priority-value is a non-negative numerical scalar expression.
17839   if (!isNonNegativeIntegerValue(
17840           ValExpr, *this, OMPC_priority,
17841           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
17842           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
17843     return nullptr;
17844 
17845   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
17846                                          StartLoc, LParenLoc, EndLoc);
17847 }
17848 
17849 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
17850                                             SourceLocation StartLoc,
17851                                             SourceLocation LParenLoc,
17852                                             SourceLocation EndLoc) {
17853   Expr *ValExpr = Grainsize;
17854   Stmt *HelperValStmt = nullptr;
17855   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
17856 
17857   // OpenMP [2.9.2, taskloop Constrcut]
17858   // The parameter of the grainsize clause must be a positive integer
17859   // expression.
17860   if (!isNonNegativeIntegerValue(
17861           ValExpr, *this, OMPC_grainsize,
17862           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
17863           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
17864     return nullptr;
17865 
17866   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
17867                                           StartLoc, LParenLoc, EndLoc);
17868 }
17869 
17870 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
17871                                            SourceLocation StartLoc,
17872                                            SourceLocation LParenLoc,
17873                                            SourceLocation EndLoc) {
17874   Expr *ValExpr = NumTasks;
17875   Stmt *HelperValStmt = nullptr;
17876   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
17877 
17878   // OpenMP [2.9.2, taskloop Constrcut]
17879   // The parameter of the num_tasks clause must be a positive integer
17880   // expression.
17881   if (!isNonNegativeIntegerValue(
17882           ValExpr, *this, OMPC_num_tasks,
17883           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
17884           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
17885     return nullptr;
17886 
17887   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
17888                                          StartLoc, LParenLoc, EndLoc);
17889 }
17890 
17891 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
17892                                        SourceLocation LParenLoc,
17893                                        SourceLocation EndLoc) {
17894   // OpenMP [2.13.2, critical construct, Description]
17895   // ... where hint-expression is an integer constant expression that evaluates
17896   // to a valid lock hint.
17897   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
17898   if (HintExpr.isInvalid())
17899     return nullptr;
17900   return new (Context)
17901       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
17902 }
17903 
17904 /// Tries to find omp_event_handle_t type.
17905 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
17906                                 DSAStackTy *Stack) {
17907   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
17908   if (!OMPEventHandleT.isNull())
17909     return true;
17910   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
17911   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
17912   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
17913     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
17914     return false;
17915   }
17916   Stack->setOMPEventHandleT(PT.get());
17917   return true;
17918 }
17919 
17920 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
17921                                          SourceLocation LParenLoc,
17922                                          SourceLocation EndLoc) {
17923   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
17924       !Evt->isInstantiationDependent() &&
17925       !Evt->containsUnexpandedParameterPack()) {
17926     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
17927       return nullptr;
17928     // OpenMP 5.0, 2.10.1 task Construct.
17929     // event-handle is a variable of the omp_event_handle_t type.
17930     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
17931     if (!Ref) {
17932       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
17933           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
17934       return nullptr;
17935     }
17936     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
17937     if (!VD) {
17938       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
17939           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
17940       return nullptr;
17941     }
17942     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
17943                                         VD->getType()) ||
17944         VD->getType().isConstant(Context)) {
17945       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
17946           << "omp_event_handle_t" << 1 << VD->getType()
17947           << Evt->getSourceRange();
17948       return nullptr;
17949     }
17950     // OpenMP 5.0, 2.10.1 task Construct
17951     // [detach clause]... The event-handle will be considered as if it was
17952     // specified on a firstprivate clause.
17953     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
17954     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
17955         DVar.RefExpr) {
17956       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
17957           << getOpenMPClauseName(DVar.CKind)
17958           << getOpenMPClauseName(OMPC_firstprivate);
17959       reportOriginalDsa(*this, DSAStack, VD, DVar);
17960       return nullptr;
17961     }
17962   }
17963 
17964   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
17965 }
17966 
17967 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
17968     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
17969     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
17970     SourceLocation EndLoc) {
17971   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
17972     std::string Values;
17973     Values += "'";
17974     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
17975     Values += "'";
17976     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
17977         << Values << getOpenMPClauseName(OMPC_dist_schedule);
17978     return nullptr;
17979   }
17980   Expr *ValExpr = ChunkSize;
17981   Stmt *HelperValStmt = nullptr;
17982   if (ChunkSize) {
17983     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
17984         !ChunkSize->isInstantiationDependent() &&
17985         !ChunkSize->containsUnexpandedParameterPack()) {
17986       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
17987       ExprResult Val =
17988           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
17989       if (Val.isInvalid())
17990         return nullptr;
17991 
17992       ValExpr = Val.get();
17993 
17994       // OpenMP [2.7.1, Restrictions]
17995       //  chunk_size must be a loop invariant integer expression with a positive
17996       //  value.
17997       llvm::APSInt Result;
17998       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
17999         if (Result.isSigned() && !Result.isStrictlyPositive()) {
18000           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
18001               << "dist_schedule" << ChunkSize->getSourceRange();
18002           return nullptr;
18003         }
18004       } else if (getOpenMPCaptureRegionForClause(
18005                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
18006                      LangOpts.OpenMP) != OMPD_unknown &&
18007                  !CurContext->isDependentContext()) {
18008         ValExpr = MakeFullExpr(ValExpr).get();
18009         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18010         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18011         HelperValStmt = buildPreInits(Context, Captures);
18012       }
18013     }
18014   }
18015 
18016   return new (Context)
18017       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
18018                             Kind, ValExpr, HelperValStmt);
18019 }
18020 
18021 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
18022     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
18023     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
18024     SourceLocation KindLoc, SourceLocation EndLoc) {
18025   if (getLangOpts().OpenMP < 50) {
18026     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
18027         Kind != OMPC_DEFAULTMAP_scalar) {
18028       std::string Value;
18029       SourceLocation Loc;
18030       Value += "'";
18031       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
18032         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18033                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
18034         Loc = MLoc;
18035       } else {
18036         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18037                                                OMPC_DEFAULTMAP_scalar);
18038         Loc = KindLoc;
18039       }
18040       Value += "'";
18041       Diag(Loc, diag::err_omp_unexpected_clause_value)
18042           << Value << getOpenMPClauseName(OMPC_defaultmap);
18043       return nullptr;
18044     }
18045   } else {
18046     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
18047     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
18048                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
18049     if (!isDefaultmapKind || !isDefaultmapModifier) {
18050       std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
18051                                   "'firstprivate', 'none', 'default'";
18052       std::string KindValue = "'scalar', 'aggregate', 'pointer'";
18053       if (!isDefaultmapKind && isDefaultmapModifier) {
18054         Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18055             << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18056       } else if (isDefaultmapKind && !isDefaultmapModifier) {
18057         Diag(MLoc, diag::err_omp_unexpected_clause_value)
18058             << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18059       } else {
18060         Diag(MLoc, diag::err_omp_unexpected_clause_value)
18061             << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18062         Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18063             << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18064       }
18065       return nullptr;
18066     }
18067 
18068     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
18069     //  At most one defaultmap clause for each category can appear on the
18070     //  directive.
18071     if (DSAStack->checkDefaultmapCategory(Kind)) {
18072       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
18073       return nullptr;
18074     }
18075   }
18076   if (Kind == OMPC_DEFAULTMAP_unknown) {
18077     // Variable category is not specified - mark all categories.
18078     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
18079     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
18080     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
18081   } else {
18082     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
18083   }
18084 
18085   return new (Context)
18086       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
18087 }
18088 
18089 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
18090   DeclContext *CurLexicalContext = getCurLexicalContext();
18091   if (!CurLexicalContext->isFileContext() &&
18092       !CurLexicalContext->isExternCContext() &&
18093       !CurLexicalContext->isExternCXXContext() &&
18094       !isa<CXXRecordDecl>(CurLexicalContext) &&
18095       !isa<ClassTemplateDecl>(CurLexicalContext) &&
18096       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
18097       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
18098     Diag(Loc, diag::err_omp_region_not_file_context);
18099     return false;
18100   }
18101   ++DeclareTargetNestingLevel;
18102   return true;
18103 }
18104 
18105 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
18106   assert(DeclareTargetNestingLevel > 0 &&
18107          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
18108   --DeclareTargetNestingLevel;
18109 }
18110 
18111 NamedDecl *
18112 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
18113                                     const DeclarationNameInfo &Id,
18114                                     NamedDeclSetType &SameDirectiveDecls) {
18115   LookupResult Lookup(*this, Id, LookupOrdinaryName);
18116   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
18117 
18118   if (Lookup.isAmbiguous())
18119     return nullptr;
18120   Lookup.suppressDiagnostics();
18121 
18122   if (!Lookup.isSingleResult()) {
18123     VarOrFuncDeclFilterCCC CCC(*this);
18124     if (TypoCorrection Corrected =
18125             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
18126                         CTK_ErrorRecovery)) {
18127       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
18128                                   << Id.getName());
18129       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
18130       return nullptr;
18131     }
18132 
18133     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
18134     return nullptr;
18135   }
18136 
18137   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
18138   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
18139       !isa<FunctionTemplateDecl>(ND)) {
18140     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
18141     return nullptr;
18142   }
18143   if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
18144     Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
18145   return ND;
18146 }
18147 
18148 void Sema::ActOnOpenMPDeclareTargetName(
18149     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
18150     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
18151   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
18152           isa<FunctionTemplateDecl>(ND)) &&
18153          "Expected variable, function or function template.");
18154 
18155   // Diagnose marking after use as it may lead to incorrect diagnosis and
18156   // codegen.
18157   if (LangOpts.OpenMP >= 50 &&
18158       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
18159     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
18160 
18161   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18162       OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
18163   if (DevTy.hasValue() && *DevTy != DT) {
18164     Diag(Loc, diag::err_omp_device_type_mismatch)
18165         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
18166         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
18167     return;
18168   }
18169   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18170       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
18171   if (!Res) {
18172     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
18173                                                        SourceRange(Loc, Loc));
18174     ND->addAttr(A);
18175     if (ASTMutationListener *ML = Context.getASTMutationListener())
18176       ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
18177     checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
18178   } else if (*Res != MT) {
18179     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
18180   }
18181 }
18182 
18183 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
18184                                      Sema &SemaRef, Decl *D) {
18185   if (!D || !isa<VarDecl>(D))
18186     return;
18187   auto *VD = cast<VarDecl>(D);
18188   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18189       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18190   if (SemaRef.LangOpts.OpenMP >= 50 &&
18191       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
18192        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
18193       VD->hasGlobalStorage()) {
18194     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18195         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18196     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
18197       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
18198       // If a lambda declaration and definition appears between a
18199       // declare target directive and the matching end declare target
18200       // directive, all variables that are captured by the lambda
18201       // expression must also appear in a to clause.
18202       SemaRef.Diag(VD->getLocation(),
18203                    diag::err_omp_lambda_capture_in_declare_target_not_to);
18204       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
18205           << VD << 0 << SR;
18206       return;
18207     }
18208   }
18209   if (MapTy.hasValue())
18210     return;
18211   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
18212   SemaRef.Diag(SL, diag::note_used_here) << SR;
18213 }
18214 
18215 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
18216                                    Sema &SemaRef, DSAStackTy *Stack,
18217                                    ValueDecl *VD) {
18218   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
18219          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
18220                            /*FullCheck=*/false);
18221 }
18222 
18223 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
18224                                             SourceLocation IdLoc) {
18225   if (!D || D->isInvalidDecl())
18226     return;
18227   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
18228   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
18229   if (auto *VD = dyn_cast<VarDecl>(D)) {
18230     // Only global variables can be marked as declare target.
18231     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
18232         !VD->isStaticDataMember())
18233       return;
18234     // 2.10.6: threadprivate variable cannot appear in a declare target
18235     // directive.
18236     if (DSAStack->isThreadPrivate(VD)) {
18237       Diag(SL, diag::err_omp_threadprivate_in_target);
18238       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
18239       return;
18240     }
18241   }
18242   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
18243     D = FTD->getTemplatedDecl();
18244   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18245     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18246         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
18247     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
18248       Diag(IdLoc, diag::err_omp_function_in_link_clause);
18249       Diag(FD->getLocation(), diag::note_defined_here) << FD;
18250       return;
18251     }
18252   }
18253   if (auto *VD = dyn_cast<ValueDecl>(D)) {
18254     // Problem if any with var declared with incomplete type will be reported
18255     // as normal, so no need to check it here.
18256     if ((E || !VD->getType()->isIncompleteType()) &&
18257         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
18258       return;
18259     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
18260       // Checking declaration inside declare target region.
18261       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
18262           isa<FunctionTemplateDecl>(D)) {
18263         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
18264             Context, OMPDeclareTargetDeclAttr::MT_To,
18265             OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
18266         D->addAttr(A);
18267         if (ASTMutationListener *ML = Context.getASTMutationListener())
18268           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
18269       }
18270       return;
18271     }
18272   }
18273   if (!E)
18274     return;
18275   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
18276 }
18277 
18278 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
18279                                      CXXScopeSpec &MapperIdScopeSpec,
18280                                      DeclarationNameInfo &MapperId,
18281                                      const OMPVarListLocTy &Locs,
18282                                      ArrayRef<Expr *> UnresolvedMappers) {
18283   MappableVarListInfo MVLI(VarList);
18284   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
18285                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18286   if (MVLI.ProcessedVarList.empty())
18287     return nullptr;
18288 
18289   return OMPToClause::Create(
18290       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18291       MVLI.VarComponents, MVLI.UDMapperList,
18292       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18293 }
18294 
18295 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
18296                                        CXXScopeSpec &MapperIdScopeSpec,
18297                                        DeclarationNameInfo &MapperId,
18298                                        const OMPVarListLocTy &Locs,
18299                                        ArrayRef<Expr *> UnresolvedMappers) {
18300   MappableVarListInfo MVLI(VarList);
18301   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
18302                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18303   if (MVLI.ProcessedVarList.empty())
18304     return nullptr;
18305 
18306   return OMPFromClause::Create(
18307       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18308       MVLI.VarComponents, MVLI.UDMapperList,
18309       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18310 }
18311 
18312 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
18313                                                const OMPVarListLocTy &Locs) {
18314   MappableVarListInfo MVLI(VarList);
18315   SmallVector<Expr *, 8> PrivateCopies;
18316   SmallVector<Expr *, 8> Inits;
18317 
18318   for (Expr *RefExpr : VarList) {
18319     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
18320     SourceLocation ELoc;
18321     SourceRange ERange;
18322     Expr *SimpleRefExpr = RefExpr;
18323     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18324     if (Res.second) {
18325       // It will be analyzed later.
18326       MVLI.ProcessedVarList.push_back(RefExpr);
18327       PrivateCopies.push_back(nullptr);
18328       Inits.push_back(nullptr);
18329     }
18330     ValueDecl *D = Res.first;
18331     if (!D)
18332       continue;
18333 
18334     QualType Type = D->getType();
18335     Type = Type.getNonReferenceType().getUnqualifiedType();
18336 
18337     auto *VD = dyn_cast<VarDecl>(D);
18338 
18339     // Item should be a pointer or reference to pointer.
18340     if (!Type->isPointerType()) {
18341       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
18342           << 0 << RefExpr->getSourceRange();
18343       continue;
18344     }
18345 
18346     // Build the private variable and the expression that refers to it.
18347     auto VDPrivate =
18348         buildVarDecl(*this, ELoc, Type, D->getName(),
18349                      D->hasAttrs() ? &D->getAttrs() : nullptr,
18350                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
18351     if (VDPrivate->isInvalidDecl())
18352       continue;
18353 
18354     CurContext->addDecl(VDPrivate);
18355     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
18356         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
18357 
18358     // Add temporary variable to initialize the private copy of the pointer.
18359     VarDecl *VDInit =
18360         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
18361     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
18362         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
18363     AddInitializerToDecl(VDPrivate,
18364                          DefaultLvalueConversion(VDInitRefExpr).get(),
18365                          /*DirectInit=*/false);
18366 
18367     // If required, build a capture to implement the privatization initialized
18368     // with the current list item value.
18369     DeclRefExpr *Ref = nullptr;
18370     if (!VD)
18371       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18372     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
18373     PrivateCopies.push_back(VDPrivateRefExpr);
18374     Inits.push_back(VDInitRefExpr);
18375 
18376     // We need to add a data sharing attribute for this variable to make sure it
18377     // is correctly captured. A variable that shows up in a use_device_ptr has
18378     // similar properties of a first private variable.
18379     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
18380 
18381     // Create a mappable component for the list item. List items in this clause
18382     // only need a component.
18383     MVLI.VarBaseDeclarations.push_back(D);
18384     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18385     MVLI.VarComponents.back().push_back(
18386         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
18387   }
18388 
18389   if (MVLI.ProcessedVarList.empty())
18390     return nullptr;
18391 
18392   return OMPUseDevicePtrClause::Create(
18393       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
18394       MVLI.VarBaseDeclarations, MVLI.VarComponents);
18395 }
18396 
18397 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
18398                                                 const OMPVarListLocTy &Locs) {
18399   MappableVarListInfo MVLI(VarList);
18400 
18401   for (Expr *RefExpr : VarList) {
18402     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
18403     SourceLocation ELoc;
18404     SourceRange ERange;
18405     Expr *SimpleRefExpr = RefExpr;
18406     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18407                               /*AllowArraySection=*/true);
18408     if (Res.second) {
18409       // It will be analyzed later.
18410       MVLI.ProcessedVarList.push_back(RefExpr);
18411     }
18412     ValueDecl *D = Res.first;
18413     if (!D)
18414       continue;
18415     auto *VD = dyn_cast<VarDecl>(D);
18416 
18417     // If required, build a capture to implement the privatization initialized
18418     // with the current list item value.
18419     DeclRefExpr *Ref = nullptr;
18420     if (!VD)
18421       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18422     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
18423 
18424     // We need to add a data sharing attribute for this variable to make sure it
18425     // is correctly captured. A variable that shows up in a use_device_addr has
18426     // similar properties of a first private variable.
18427     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
18428 
18429     // Create a mappable component for the list item. List items in this clause
18430     // only need a component.
18431     MVLI.VarBaseDeclarations.push_back(D);
18432     MVLI.VarComponents.emplace_back();
18433     MVLI.VarComponents.back().push_back(
18434         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
18435   }
18436 
18437   if (MVLI.ProcessedVarList.empty())
18438     return nullptr;
18439 
18440   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
18441                                         MVLI.VarBaseDeclarations,
18442                                         MVLI.VarComponents);
18443 }
18444 
18445 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
18446                                               const OMPVarListLocTy &Locs) {
18447   MappableVarListInfo MVLI(VarList);
18448   for (Expr *RefExpr : VarList) {
18449     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
18450     SourceLocation ELoc;
18451     SourceRange ERange;
18452     Expr *SimpleRefExpr = RefExpr;
18453     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18454     if (Res.second) {
18455       // It will be analyzed later.
18456       MVLI.ProcessedVarList.push_back(RefExpr);
18457     }
18458     ValueDecl *D = Res.first;
18459     if (!D)
18460       continue;
18461 
18462     QualType Type = D->getType();
18463     // item should be a pointer or array or reference to pointer or array
18464     if (!Type.getNonReferenceType()->isPointerType() &&
18465         !Type.getNonReferenceType()->isArrayType()) {
18466       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
18467           << 0 << RefExpr->getSourceRange();
18468       continue;
18469     }
18470 
18471     // Check if the declaration in the clause does not show up in any data
18472     // sharing attribute.
18473     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
18474     if (isOpenMPPrivate(DVar.CKind)) {
18475       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
18476           << getOpenMPClauseName(DVar.CKind)
18477           << getOpenMPClauseName(OMPC_is_device_ptr)
18478           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18479       reportOriginalDsa(*this, DSAStack, D, DVar);
18480       continue;
18481     }
18482 
18483     const Expr *ConflictExpr;
18484     if (DSAStack->checkMappableExprComponentListsForDecl(
18485             D, /*CurrentRegionOnly=*/true,
18486             [&ConflictExpr](
18487                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
18488                 OpenMPClauseKind) -> bool {
18489               ConflictExpr = R.front().getAssociatedExpression();
18490               return true;
18491             })) {
18492       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
18493       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
18494           << ConflictExpr->getSourceRange();
18495       continue;
18496     }
18497 
18498     // Store the components in the stack so that they can be used to check
18499     // against other clauses later on.
18500     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
18501     DSAStack->addMappableExpressionComponents(
18502         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
18503 
18504     // Record the expression we've just processed.
18505     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
18506 
18507     // Create a mappable component for the list item. List items in this clause
18508     // only need a component. We use a null declaration to signal fields in
18509     // 'this'.
18510     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
18511             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
18512            "Unexpected device pointer expression!");
18513     MVLI.VarBaseDeclarations.push_back(
18514         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
18515     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18516     MVLI.VarComponents.back().push_back(MC);
18517   }
18518 
18519   if (MVLI.ProcessedVarList.empty())
18520     return nullptr;
18521 
18522   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
18523                                       MVLI.VarBaseDeclarations,
18524                                       MVLI.VarComponents);
18525 }
18526 
18527 OMPClause *Sema::ActOnOpenMPAllocateClause(
18528     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18529     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
18530   if (Allocator) {
18531     // OpenMP [2.11.4 allocate Clause, Description]
18532     // allocator is an expression of omp_allocator_handle_t type.
18533     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
18534       return nullptr;
18535 
18536     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
18537     if (AllocatorRes.isInvalid())
18538       return nullptr;
18539     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
18540                                              DSAStack->getOMPAllocatorHandleT(),
18541                                              Sema::AA_Initializing,
18542                                              /*AllowExplicit=*/true);
18543     if (AllocatorRes.isInvalid())
18544       return nullptr;
18545     Allocator = AllocatorRes.get();
18546   } else {
18547     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
18548     // allocate clauses that appear on a target construct or on constructs in a
18549     // target region must specify an allocator expression unless a requires
18550     // directive with the dynamic_allocators clause is present in the same
18551     // compilation unit.
18552     if (LangOpts.OpenMPIsDevice &&
18553         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
18554       targetDiag(StartLoc, diag::err_expected_allocator_expression);
18555   }
18556   // Analyze and build list of variables.
18557   SmallVector<Expr *, 8> Vars;
18558   for (Expr *RefExpr : VarList) {
18559     assert(RefExpr && "NULL expr in OpenMP private clause.");
18560     SourceLocation ELoc;
18561     SourceRange ERange;
18562     Expr *SimpleRefExpr = RefExpr;
18563     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18564     if (Res.second) {
18565       // It will be analyzed later.
18566       Vars.push_back(RefExpr);
18567     }
18568     ValueDecl *D = Res.first;
18569     if (!D)
18570       continue;
18571 
18572     auto *VD = dyn_cast<VarDecl>(D);
18573     DeclRefExpr *Ref = nullptr;
18574     if (!VD && !CurContext->isDependentContext())
18575       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
18576     Vars.push_back((VD || CurContext->isDependentContext())
18577                        ? RefExpr->IgnoreParens()
18578                        : Ref);
18579   }
18580 
18581   if (Vars.empty())
18582     return nullptr;
18583 
18584   if (Allocator)
18585     DSAStack->addInnerAllocatorExpr(Allocator);
18586   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
18587                                    ColonLoc, EndLoc, Vars);
18588 }
18589 
18590 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
18591                                               SourceLocation StartLoc,
18592                                               SourceLocation LParenLoc,
18593                                               SourceLocation EndLoc) {
18594   SmallVector<Expr *, 8> Vars;
18595   for (Expr *RefExpr : VarList) {
18596     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18597     SourceLocation ELoc;
18598     SourceRange ERange;
18599     Expr *SimpleRefExpr = RefExpr;
18600     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18601     if (Res.second)
18602       // It will be analyzed later.
18603       Vars.push_back(RefExpr);
18604     ValueDecl *D = Res.first;
18605     if (!D)
18606       continue;
18607 
18608     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
18609     // A list-item cannot appear in more than one nontemporal clause.
18610     if (const Expr *PrevRef =
18611             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
18612       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18613           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
18614       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18615           << getOpenMPClauseName(OMPC_nontemporal);
18616       continue;
18617     }
18618 
18619     Vars.push_back(RefExpr);
18620   }
18621 
18622   if (Vars.empty())
18623     return nullptr;
18624 
18625   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18626                                       Vars);
18627 }
18628 
18629 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
18630                                             SourceLocation StartLoc,
18631                                             SourceLocation LParenLoc,
18632                                             SourceLocation EndLoc) {
18633   SmallVector<Expr *, 8> Vars;
18634   for (Expr *RefExpr : VarList) {
18635     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18636     SourceLocation ELoc;
18637     SourceRange ERange;
18638     Expr *SimpleRefExpr = RefExpr;
18639     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18640                               /*AllowArraySection=*/true);
18641     if (Res.second)
18642       // It will be analyzed later.
18643       Vars.push_back(RefExpr);
18644     ValueDecl *D = Res.first;
18645     if (!D)
18646       continue;
18647 
18648     const DSAStackTy::DSAVarData DVar =
18649         DSAStack->getTopDSA(D, /*FromParent=*/true);
18650     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
18651     // A list item that appears in the inclusive or exclusive clause must appear
18652     // in a reduction clause with the inscan modifier on the enclosing
18653     // worksharing-loop, worksharing-loop SIMD, or simd construct.
18654     if (DVar.CKind != OMPC_reduction ||
18655         DVar.Modifier != OMPC_REDUCTION_inscan)
18656       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
18657           << RefExpr->getSourceRange();
18658 
18659     if (DSAStack->getParentDirective() != OMPD_unknown)
18660       DSAStack->markDeclAsUsedInScanDirective(D);
18661     Vars.push_back(RefExpr);
18662   }
18663 
18664   if (Vars.empty())
18665     return nullptr;
18666 
18667   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
18668 }
18669 
18670 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
18671                                             SourceLocation StartLoc,
18672                                             SourceLocation LParenLoc,
18673                                             SourceLocation EndLoc) {
18674   SmallVector<Expr *, 8> Vars;
18675   for (Expr *RefExpr : VarList) {
18676     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18677     SourceLocation ELoc;
18678     SourceRange ERange;
18679     Expr *SimpleRefExpr = RefExpr;
18680     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18681                               /*AllowArraySection=*/true);
18682     if (Res.second)
18683       // It will be analyzed later.
18684       Vars.push_back(RefExpr);
18685     ValueDecl *D = Res.first;
18686     if (!D)
18687       continue;
18688 
18689     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
18690     DSAStackTy::DSAVarData DVar;
18691     if (ParentDirective != OMPD_unknown)
18692       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
18693     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
18694     // A list item that appears in the inclusive or exclusive clause must appear
18695     // in a reduction clause with the inscan modifier on the enclosing
18696     // worksharing-loop, worksharing-loop SIMD, or simd construct.
18697     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
18698         DVar.Modifier != OMPC_REDUCTION_inscan) {
18699       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
18700           << RefExpr->getSourceRange();
18701     } else {
18702       DSAStack->markDeclAsUsedInScanDirective(D);
18703     }
18704     Vars.push_back(RefExpr);
18705   }
18706 
18707   if (Vars.empty())
18708     return nullptr;
18709 
18710   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
18711 }
18712 
18713 /// Tries to find omp_alloctrait_t type.
18714 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
18715   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
18716   if (!OMPAlloctraitT.isNull())
18717     return true;
18718   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
18719   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
18720   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18721     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
18722     return false;
18723   }
18724   Stack->setOMPAlloctraitT(PT.get());
18725   return true;
18726 }
18727 
18728 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
18729     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
18730     ArrayRef<UsesAllocatorsData> Data) {
18731   // OpenMP [2.12.5, target Construct]
18732   // allocator is an identifier of omp_allocator_handle_t type.
18733   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
18734     return nullptr;
18735   // OpenMP [2.12.5, target Construct]
18736   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
18737   if (llvm::any_of(
18738           Data,
18739           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
18740       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
18741     return nullptr;
18742   llvm::SmallSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
18743   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
18744     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
18745     StringRef Allocator =
18746         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
18747     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
18748     PredefinedAllocators.insert(LookupSingleName(
18749         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
18750   }
18751 
18752   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
18753   for (const UsesAllocatorsData &D : Data) {
18754     Expr *AllocatorExpr = nullptr;
18755     // Check allocator expression.
18756     if (D.Allocator->isTypeDependent()) {
18757       AllocatorExpr = D.Allocator;
18758     } else {
18759       // Traits were specified - need to assign new allocator to the specified
18760       // allocator, so it must be an lvalue.
18761       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
18762       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
18763       bool IsPredefinedAllocator = false;
18764       if (DRE)
18765         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
18766       if (!DRE ||
18767           !(Context.hasSameUnqualifiedType(
18768                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
18769             Context.typesAreCompatible(AllocatorExpr->getType(),
18770                                        DSAStack->getOMPAllocatorHandleT(),
18771                                        /*CompareUnqualified=*/true)) ||
18772           (!IsPredefinedAllocator &&
18773            (AllocatorExpr->getType().isConstant(Context) ||
18774             !AllocatorExpr->isLValue()))) {
18775         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
18776             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
18777             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
18778         continue;
18779       }
18780       // OpenMP [2.12.5, target Construct]
18781       // Predefined allocators appearing in a uses_allocators clause cannot have
18782       // traits specified.
18783       if (IsPredefinedAllocator && D.AllocatorTraits) {
18784         Diag(D.AllocatorTraits->getExprLoc(),
18785              diag::err_omp_predefined_allocator_with_traits)
18786             << D.AllocatorTraits->getSourceRange();
18787         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
18788             << cast<NamedDecl>(DRE->getDecl())->getName()
18789             << D.Allocator->getSourceRange();
18790         continue;
18791       }
18792       // OpenMP [2.12.5, target Construct]
18793       // Non-predefined allocators appearing in a uses_allocators clause must
18794       // have traits specified.
18795       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
18796         Diag(D.Allocator->getExprLoc(),
18797              diag::err_omp_nonpredefined_allocator_without_traits);
18798         continue;
18799       }
18800       // No allocator traits - just convert it to rvalue.
18801       if (!D.AllocatorTraits)
18802         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
18803       DSAStack->addUsesAllocatorsDecl(
18804           DRE->getDecl(),
18805           IsPredefinedAllocator
18806               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
18807               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
18808     }
18809     Expr *AllocatorTraitsExpr = nullptr;
18810     if (D.AllocatorTraits) {
18811       if (D.AllocatorTraits->isTypeDependent()) {
18812         AllocatorTraitsExpr = D.AllocatorTraits;
18813       } else {
18814         // OpenMP [2.12.5, target Construct]
18815         // Arrays that contain allocator traits that appear in a uses_allocators
18816         // clause must be constant arrays, have constant values and be defined
18817         // in the same scope as the construct in which the clause appears.
18818         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
18819         // Check that traits expr is a constant array.
18820         QualType TraitTy;
18821         if (const ArrayType *Ty =
18822                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
18823           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
18824             TraitTy = ConstArrayTy->getElementType();
18825         if (TraitTy.isNull() ||
18826             !(Context.hasSameUnqualifiedType(TraitTy,
18827                                              DSAStack->getOMPAlloctraitT()) ||
18828               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
18829                                          /*CompareUnqualified=*/true))) {
18830           Diag(D.AllocatorTraits->getExprLoc(),
18831                diag::err_omp_expected_array_alloctraits)
18832               << AllocatorTraitsExpr->getType();
18833           continue;
18834         }
18835         // Do not map by default allocator traits if it is a standalone
18836         // variable.
18837         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
18838           DSAStack->addUsesAllocatorsDecl(
18839               DRE->getDecl(),
18840               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
18841       }
18842     }
18843     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
18844     NewD.Allocator = AllocatorExpr;
18845     NewD.AllocatorTraits = AllocatorTraitsExpr;
18846     NewD.LParenLoc = D.LParenLoc;
18847     NewD.RParenLoc = D.RParenLoc;
18848   }
18849   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18850                                          NewData);
18851 }
18852 
18853 OMPClause *Sema::ActOnOpenMPAffinityClause(
18854     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
18855     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
18856   SmallVector<Expr *, 8> Vars;
18857   for (Expr *RefExpr : Locators) {
18858     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18859     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
18860       // It will be analyzed later.
18861       Vars.push_back(RefExpr);
18862       continue;
18863     }
18864 
18865     SourceLocation ELoc = RefExpr->getExprLoc();
18866     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
18867 
18868     if (!SimpleExpr->isLValue()) {
18869       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18870           << 1 << 0 << RefExpr->getSourceRange();
18871       continue;
18872     }
18873 
18874     ExprResult Res;
18875     {
18876       Sema::TentativeAnalysisScope Trap(*this);
18877       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
18878     }
18879     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18880         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18881       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18882           << 1 << 0 << RefExpr->getSourceRange();
18883       continue;
18884     }
18885     Vars.push_back(SimpleExpr);
18886   }
18887 
18888   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
18889                                    EndLoc, Modifier, Vars);
18890 }
18891