1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements semantic analysis for OpenMP directives and
10 /// clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/OpenMPClause.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/DiagnosticSema.h"
27 #include "clang/Basic/OpenMPKinds.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/PointerEmbeddedInt.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Frontend/OpenMP/OMPConstants.h"
40 #include <set>
41 
42 using namespace clang;
43 using namespace llvm::omp;
44 
45 //===----------------------------------------------------------------------===//
46 // Stack of data-sharing attributes for variables
47 //===----------------------------------------------------------------------===//
48 
49 static const Expr *checkMapClauseExpressionBase(
50     Sema &SemaRef, Expr *E,
51     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
52     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
53 
54 namespace {
55 /// Default data sharing attributes, which can be applied to directive.
56 enum DefaultDataSharingAttributes {
57   DSA_unspecified = 0,       /// Data sharing attribute not specified.
58   DSA_none = 1 << 0,         /// Default data sharing attribute 'none'.
59   DSA_shared = 1 << 1,       /// Default data sharing attribute 'shared'.
60   DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
61 };
62 
63 /// Stack for tracking declarations used in OpenMP directives and
64 /// clauses and their data-sharing attributes.
65 class DSAStackTy {
66 public:
67   struct DSAVarData {
68     OpenMPDirectiveKind DKind = OMPD_unknown;
69     OpenMPClauseKind CKind = OMPC_unknown;
70     unsigned Modifier = 0;
71     const Expr *RefExpr = nullptr;
72     DeclRefExpr *PrivateCopy = nullptr;
73     SourceLocation ImplicitDSALoc;
74     bool AppliedToPointee = false;
75     DSAVarData() = default;
76     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
77                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
78                SourceLocation ImplicitDSALoc, unsigned Modifier,
79                bool AppliedToPointee)
80         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
81           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
82           AppliedToPointee(AppliedToPointee) {}
83   };
84   using OperatorOffsetTy =
85       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
86   using DoacrossDependMapTy =
87       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
88   /// Kind of the declaration used in the uses_allocators clauses.
89   enum class UsesAllocatorsDeclKind {
90     /// Predefined allocator
91     PredefinedAllocator,
92     /// User-defined allocator
93     UserDefinedAllocator,
94     /// The declaration that represent allocator trait
95     AllocatorTrait,
96   };
97 
98 private:
99   struct DSAInfo {
100     OpenMPClauseKind Attributes = OMPC_unknown;
101     unsigned Modifier = 0;
102     /// Pointer to a reference expression and a flag which shows that the
103     /// variable is marked as lastprivate(true) or not (false).
104     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
105     DeclRefExpr *PrivateCopy = nullptr;
106     /// true if the attribute is applied to the pointee, not the variable
107     /// itself.
108     bool AppliedToPointee = false;
109   };
110   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
111   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
112   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
113   using LoopControlVariablesMapTy =
114       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
115   /// Struct that associates a component with the clause kind where they are
116   /// found.
117   struct MappedExprComponentTy {
118     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
119     OpenMPClauseKind Kind = OMPC_unknown;
120   };
121   using MappedExprComponentsTy =
122       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
123   using CriticalsWithHintsTy =
124       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
125   struct ReductionData {
126     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
127     SourceRange ReductionRange;
128     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
129     ReductionData() = default;
130     void set(BinaryOperatorKind BO, SourceRange RR) {
131       ReductionRange = RR;
132       ReductionOp = BO;
133     }
134     void set(const Expr *RefExpr, SourceRange RR) {
135       ReductionRange = RR;
136       ReductionOp = RefExpr;
137     }
138   };
139   using DeclReductionMapTy =
140       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
141   struct DefaultmapInfo {
142     OpenMPDefaultmapClauseModifier ImplicitBehavior =
143         OMPC_DEFAULTMAP_MODIFIER_unknown;
144     SourceLocation SLoc;
145     DefaultmapInfo() = default;
146     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
147         : ImplicitBehavior(M), SLoc(Loc) {}
148   };
149 
150   struct SharingMapTy {
151     DeclSAMapTy SharingMap;
152     DeclReductionMapTy ReductionMap;
153     UsedRefMapTy AlignedMap;
154     UsedRefMapTy NontemporalMap;
155     MappedExprComponentsTy MappedExprComponents;
156     LoopControlVariablesMapTy LCVMap;
157     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
158     SourceLocation DefaultAttrLoc;
159     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
160     OpenMPDirectiveKind Directive = OMPD_unknown;
161     DeclarationNameInfo DirectiveName;
162     Scope *CurScope = nullptr;
163     DeclContext *Context = nullptr;
164     SourceLocation ConstructLoc;
165     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
166     /// get the data (loop counters etc.) about enclosing loop-based construct.
167     /// This data is required during codegen.
168     DoacrossDependMapTy DoacrossDepends;
169     /// First argument (Expr *) contains optional argument of the
170     /// 'ordered' clause, the second one is true if the regions has 'ordered'
171     /// clause, false otherwise.
172     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
173     unsigned AssociatedLoops = 1;
174     bool HasMutipleLoops = false;
175     const Decl *PossiblyLoopCounter = nullptr;
176     bool NowaitRegion = false;
177     bool CancelRegion = false;
178     bool LoopStart = false;
179     bool BodyComplete = false;
180     SourceLocation PrevScanLocation;
181     SourceLocation PrevOrderedLocation;
182     SourceLocation InnerTeamsRegionLoc;
183     /// Reference to the taskgroup task_reduction reference expression.
184     Expr *TaskgroupReductionRef = nullptr;
185     llvm::DenseSet<QualType> MappedClassesQualTypes;
186     SmallVector<Expr *, 4> InnerUsedAllocators;
187     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
188     /// List of globals marked as declare target link in this target region
189     /// (isOpenMPTargetExecutionDirective(Directive) == true).
190     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
191     /// List of decls used in inclusive/exclusive clauses of the scan directive.
192     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
193     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
194         UsesAllocatorsDecls;
195     Expr *DeclareMapperVar = nullptr;
196     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
197                  Scope *CurScope, SourceLocation Loc)
198         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
199           ConstructLoc(Loc) {}
200     SharingMapTy() = default;
201   };
202 
203   using StackTy = SmallVector<SharingMapTy, 4>;
204 
205   /// Stack of used declaration and their data-sharing attributes.
206   DeclSAMapTy Threadprivates;
207   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
208   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
209   /// true, if check for DSA must be from parent directive, false, if
210   /// from current directive.
211   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
212   Sema &SemaRef;
213   bool ForceCapturing = false;
214   /// true if all the variables in the target executable directives must be
215   /// captured by reference.
216   bool ForceCaptureByReferenceInTargetExecutable = false;
217   CriticalsWithHintsTy Criticals;
218   unsigned IgnoredStackElements = 0;
219 
220   /// Iterators over the stack iterate in order from innermost to outermost
221   /// directive.
222   using const_iterator = StackTy::const_reverse_iterator;
223   const_iterator begin() const {
224     return Stack.empty() ? const_iterator()
225                          : Stack.back().first.rbegin() + IgnoredStackElements;
226   }
227   const_iterator end() const {
228     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
229   }
230   using iterator = StackTy::reverse_iterator;
231   iterator begin() {
232     return Stack.empty() ? iterator()
233                          : Stack.back().first.rbegin() + IgnoredStackElements;
234   }
235   iterator end() {
236     return Stack.empty() ? iterator() : Stack.back().first.rend();
237   }
238 
239   // Convenience operations to get at the elements of the stack.
240 
241   bool isStackEmpty() const {
242     return Stack.empty() ||
243            Stack.back().second != CurrentNonCapturingFunctionScope ||
244            Stack.back().first.size() <= IgnoredStackElements;
245   }
246   size_t getStackSize() const {
247     return isStackEmpty() ? 0
248                           : Stack.back().first.size() - IgnoredStackElements;
249   }
250 
251   SharingMapTy *getTopOfStackOrNull() {
252     size_t Size = getStackSize();
253     if (Size == 0)
254       return nullptr;
255     return &Stack.back().first[Size - 1];
256   }
257   const SharingMapTy *getTopOfStackOrNull() const {
258     return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
259   }
260   SharingMapTy &getTopOfStack() {
261     assert(!isStackEmpty() && "no current directive");
262     return *getTopOfStackOrNull();
263   }
264   const SharingMapTy &getTopOfStack() const {
265     return const_cast<DSAStackTy &>(*this).getTopOfStack();
266   }
267 
268   SharingMapTy *getSecondOnStackOrNull() {
269     size_t Size = getStackSize();
270     if (Size <= 1)
271       return nullptr;
272     return &Stack.back().first[Size - 2];
273   }
274   const SharingMapTy *getSecondOnStackOrNull() const {
275     return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
276   }
277 
278   /// Get the stack element at a certain level (previously returned by
279   /// \c getNestingLevel).
280   ///
281   /// Note that nesting levels count from outermost to innermost, and this is
282   /// the reverse of our iteration order where new inner levels are pushed at
283   /// the front of the stack.
284   SharingMapTy &getStackElemAtLevel(unsigned Level) {
285     assert(Level < getStackSize() && "no such stack element");
286     return Stack.back().first[Level];
287   }
288   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
289     return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
290   }
291 
292   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
293 
294   /// Checks if the variable is a local for OpenMP region.
295   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
296 
297   /// Vector of previously declared requires directives
298   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
299   /// omp_allocator_handle_t type.
300   QualType OMPAllocatorHandleT;
301   /// omp_depend_t type.
302   QualType OMPDependT;
303   /// omp_event_handle_t type.
304   QualType OMPEventHandleT;
305   /// omp_alloctrait_t type.
306   QualType OMPAlloctraitT;
307   /// Expression for the predefined allocators.
308   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
309       nullptr};
310   /// Vector of previously encountered target directives
311   SmallVector<SourceLocation, 2> TargetLocations;
312   SourceLocation AtomicLocation;
313   /// Vector of declare variant construct traits.
314   SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
315 
316 public:
317   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
318 
319   /// Sets omp_allocator_handle_t type.
320   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
321   /// Gets omp_allocator_handle_t type.
322   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
323   /// Sets omp_alloctrait_t type.
324   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
325   /// Gets omp_alloctrait_t type.
326   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
327   /// Sets the given default allocator.
328   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
329                     Expr *Allocator) {
330     OMPPredefinedAllocators[AllocatorKind] = Allocator;
331   }
332   /// Returns the specified default allocator.
333   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
334     return OMPPredefinedAllocators[AllocatorKind];
335   }
336   /// Sets omp_depend_t type.
337   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
338   /// Gets omp_depend_t type.
339   QualType getOMPDependT() const { return OMPDependT; }
340 
341   /// Sets omp_event_handle_t type.
342   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
343   /// Gets omp_event_handle_t type.
344   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
345 
346   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
347   OpenMPClauseKind getClauseParsingMode() const {
348     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
349     return ClauseKindMode;
350   }
351   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
352 
353   bool isBodyComplete() const {
354     const SharingMapTy *Top = getTopOfStackOrNull();
355     return Top && Top->BodyComplete;
356   }
357   void setBodyComplete() { getTopOfStack().BodyComplete = true; }
358 
359   bool isForceVarCapturing() const { return ForceCapturing; }
360   void setForceVarCapturing(bool V) { ForceCapturing = V; }
361 
362   void setForceCaptureByReferenceInTargetExecutable(bool V) {
363     ForceCaptureByReferenceInTargetExecutable = V;
364   }
365   bool isForceCaptureByReferenceInTargetExecutable() const {
366     return ForceCaptureByReferenceInTargetExecutable;
367   }
368 
369   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
370             Scope *CurScope, SourceLocation Loc) {
371     assert(!IgnoredStackElements &&
372            "cannot change stack while ignoring elements");
373     if (Stack.empty() ||
374         Stack.back().second != CurrentNonCapturingFunctionScope)
375       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
376     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
377     Stack.back().first.back().DefaultAttrLoc = Loc;
378   }
379 
380   void pop() {
381     assert(!IgnoredStackElements &&
382            "cannot change stack while ignoring elements");
383     assert(!Stack.back().first.empty() &&
384            "Data-sharing attributes stack is empty!");
385     Stack.back().first.pop_back();
386   }
387 
388   /// RAII object to temporarily leave the scope of a directive when we want to
389   /// logically operate in its parent.
390   class ParentDirectiveScope {
391     DSAStackTy &Self;
392     bool Active;
393 
394   public:
395     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
396         : Self(Self), Active(false) {
397       if (Activate)
398         enable();
399     }
400     ~ParentDirectiveScope() { disable(); }
401     void disable() {
402       if (Active) {
403         --Self.IgnoredStackElements;
404         Active = false;
405       }
406     }
407     void enable() {
408       if (!Active) {
409         ++Self.IgnoredStackElements;
410         Active = true;
411       }
412     }
413   };
414 
415   /// Marks that we're started loop parsing.
416   void loopInit() {
417     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
418            "Expected loop-based directive.");
419     getTopOfStack().LoopStart = true;
420   }
421   /// Start capturing of the variables in the loop context.
422   void loopStart() {
423     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
424            "Expected loop-based directive.");
425     getTopOfStack().LoopStart = false;
426   }
427   /// true, if variables are captured, false otherwise.
428   bool isLoopStarted() const {
429     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
430            "Expected loop-based directive.");
431     return !getTopOfStack().LoopStart;
432   }
433   /// Marks (or clears) declaration as possibly loop counter.
434   void resetPossibleLoopCounter(const Decl *D = nullptr) {
435     getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
436   }
437   /// Gets the possible loop counter decl.
438   const Decl *getPossiblyLoopCunter() const {
439     return getTopOfStack().PossiblyLoopCounter;
440   }
441   /// Start new OpenMP region stack in new non-capturing function.
442   void pushFunction() {
443     assert(!IgnoredStackElements &&
444            "cannot change stack while ignoring elements");
445     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
446     assert(!isa<CapturingScopeInfo>(CurFnScope));
447     CurrentNonCapturingFunctionScope = CurFnScope;
448   }
449   /// Pop region stack for non-capturing function.
450   void popFunction(const FunctionScopeInfo *OldFSI) {
451     assert(!IgnoredStackElements &&
452            "cannot change stack while ignoring elements");
453     if (!Stack.empty() && Stack.back().second == OldFSI) {
454       assert(Stack.back().first.empty());
455       Stack.pop_back();
456     }
457     CurrentNonCapturingFunctionScope = nullptr;
458     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
459       if (!isa<CapturingScopeInfo>(FSI)) {
460         CurrentNonCapturingFunctionScope = FSI;
461         break;
462       }
463     }
464   }
465 
466   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
467     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
468   }
469   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
470   getCriticalWithHint(const DeclarationNameInfo &Name) const {
471     auto I = Criticals.find(Name.getAsString());
472     if (I != Criticals.end())
473       return I->second;
474     return std::make_pair(nullptr, llvm::APSInt());
475   }
476   /// If 'aligned' declaration for given variable \a D was not seen yet,
477   /// add it and return NULL; otherwise return previous occurrence's expression
478   /// for diagnostics.
479   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
480   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
481   /// add it and return NULL; otherwise return previous occurrence's expression
482   /// for diagnostics.
483   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
484 
485   /// Register specified variable as loop control variable.
486   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
487   /// Check if the specified variable is a loop control variable for
488   /// current region.
489   /// \return The index of the loop control variable in the list of associated
490   /// for-loops (from outer to inner).
491   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
492   /// Check if the specified variable is a loop control variable for
493   /// parent region.
494   /// \return The index of the loop control variable in the list of associated
495   /// for-loops (from outer to inner).
496   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
497   /// Check if the specified variable is a loop control variable for
498   /// current region.
499   /// \return The index of the loop control variable in the list of associated
500   /// for-loops (from outer to inner).
501   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
502                                          unsigned Level) const;
503   /// Get the loop control variable for the I-th loop (or nullptr) in
504   /// parent directive.
505   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
506 
507   /// Marks the specified decl \p D as used in scan directive.
508   void markDeclAsUsedInScanDirective(ValueDecl *D) {
509     if (SharingMapTy *Stack = getSecondOnStackOrNull())
510       Stack->UsedInScanDirective.insert(D);
511   }
512 
513   /// Checks if the specified declaration was used in the inner scan directive.
514   bool isUsedInScanDirective(ValueDecl *D) const {
515     if (const SharingMapTy *Stack = getTopOfStackOrNull())
516       return Stack->UsedInScanDirective.contains(D);
517     return false;
518   }
519 
520   /// Adds explicit data sharing attribute to the specified declaration.
521   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
522               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
523               bool AppliedToPointee = false);
524 
525   /// Adds additional information for the reduction items with the reduction id
526   /// represented as an operator.
527   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
528                                  BinaryOperatorKind BOK);
529   /// Adds additional information for the reduction items with the reduction id
530   /// represented as reduction identifier.
531   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
532                                  const Expr *ReductionRef);
533   /// Returns the location and reduction operation from the innermost parent
534   /// region for the given \p D.
535   const DSAVarData
536   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
537                                    BinaryOperatorKind &BOK,
538                                    Expr *&TaskgroupDescriptor) const;
539   /// Returns the location and reduction operation from the innermost parent
540   /// region for the given \p D.
541   const DSAVarData
542   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
543                                    const Expr *&ReductionRef,
544                                    Expr *&TaskgroupDescriptor) const;
545   /// Return reduction reference expression for the current taskgroup or
546   /// parallel/worksharing directives with task reductions.
547   Expr *getTaskgroupReductionRef() const {
548     assert((getTopOfStack().Directive == OMPD_taskgroup ||
549             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
550               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
551              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
552            "taskgroup reference expression requested for non taskgroup or "
553            "parallel/worksharing directive.");
554     return getTopOfStack().TaskgroupReductionRef;
555   }
556   /// Checks if the given \p VD declaration is actually a taskgroup reduction
557   /// descriptor variable at the \p Level of OpenMP regions.
558   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
559     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
560            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
561                    ->getDecl() == VD;
562   }
563 
564   /// Returns data sharing attributes from top of the stack for the
565   /// specified declaration.
566   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
567   /// Returns data-sharing attributes for the specified declaration.
568   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
569   /// Returns data-sharing attributes for the specified declaration.
570   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
571   /// Checks if the specified variables has data-sharing attributes which
572   /// match specified \a CPred predicate in any directive which matches \a DPred
573   /// predicate.
574   const DSAVarData
575   hasDSA(ValueDecl *D,
576          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
577          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
578          bool FromParent) const;
579   /// Checks if the specified variables has data-sharing attributes which
580   /// match specified \a CPred predicate in any innermost directive which
581   /// matches \a DPred predicate.
582   const DSAVarData
583   hasInnermostDSA(ValueDecl *D,
584                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
585                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
586                   bool FromParent) const;
587   /// Checks if the specified variables has explicit data-sharing
588   /// attributes which match specified \a CPred predicate at the specified
589   /// OpenMP region.
590   bool
591   hasExplicitDSA(const ValueDecl *D,
592                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
593                  unsigned Level, bool NotLastprivate = false) const;
594 
595   /// Returns true if the directive at level \Level matches in the
596   /// specified \a DPred predicate.
597   bool hasExplicitDirective(
598       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
599       unsigned Level) const;
600 
601   /// Finds a directive which matches specified \a DPred predicate.
602   bool hasDirective(
603       const llvm::function_ref<bool(
604           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
605           DPred,
606       bool FromParent) const;
607 
608   /// Returns currently analyzed directive.
609   OpenMPDirectiveKind getCurrentDirective() const {
610     const SharingMapTy *Top = getTopOfStackOrNull();
611     return Top ? Top->Directive : OMPD_unknown;
612   }
613   /// Returns directive kind at specified level.
614   OpenMPDirectiveKind getDirective(unsigned Level) const {
615     assert(!isStackEmpty() && "No directive at specified level.");
616     return getStackElemAtLevel(Level).Directive;
617   }
618   /// Returns the capture region at the specified level.
619   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
620                                        unsigned OpenMPCaptureLevel) const {
621     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
622     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
623     return CaptureRegions[OpenMPCaptureLevel];
624   }
625   /// Returns parent directive.
626   OpenMPDirectiveKind getParentDirective() const {
627     const SharingMapTy *Parent = getSecondOnStackOrNull();
628     return Parent ? Parent->Directive : OMPD_unknown;
629   }
630 
631   /// Add requires decl to internal vector
632   void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
633 
634   /// Checks if the defined 'requires' directive has specified type of clause.
635   template <typename ClauseType> bool hasRequiresDeclWithClause() const {
636     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
637       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
638         return isa<ClauseType>(C);
639       });
640     });
641   }
642 
643   /// Checks for a duplicate clause amongst previously declared requires
644   /// directives
645   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
646     bool IsDuplicate = false;
647     for (OMPClause *CNew : ClauseList) {
648       for (const OMPRequiresDecl *D : RequiresDecls) {
649         for (const OMPClause *CPrev : D->clauselists()) {
650           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
651             SemaRef.Diag(CNew->getBeginLoc(),
652                          diag::err_omp_requires_clause_redeclaration)
653                 << getOpenMPClauseName(CNew->getClauseKind());
654             SemaRef.Diag(CPrev->getBeginLoc(),
655                          diag::note_omp_requires_previous_clause)
656                 << getOpenMPClauseName(CPrev->getClauseKind());
657             IsDuplicate = true;
658           }
659         }
660       }
661     }
662     return IsDuplicate;
663   }
664 
665   /// Add location of previously encountered target to internal vector
666   void addTargetDirLocation(SourceLocation LocStart) {
667     TargetLocations.push_back(LocStart);
668   }
669 
670   /// Add location for the first encountered atomicc directive.
671   void addAtomicDirectiveLoc(SourceLocation Loc) {
672     if (AtomicLocation.isInvalid())
673       AtomicLocation = Loc;
674   }
675 
676   /// Returns the location of the first encountered atomic directive in the
677   /// module.
678   SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
679 
680   // Return previously encountered target region locations.
681   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
682     return TargetLocations;
683   }
684 
685   /// Set default data sharing attribute to none.
686   void setDefaultDSANone(SourceLocation Loc) {
687     getTopOfStack().DefaultAttr = DSA_none;
688     getTopOfStack().DefaultAttrLoc = Loc;
689   }
690   /// Set default data sharing attribute to shared.
691   void setDefaultDSAShared(SourceLocation Loc) {
692     getTopOfStack().DefaultAttr = DSA_shared;
693     getTopOfStack().DefaultAttrLoc = Loc;
694   }
695   /// Set default data sharing attribute to firstprivate.
696   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
697     getTopOfStack().DefaultAttr = DSA_firstprivate;
698     getTopOfStack().DefaultAttrLoc = Loc;
699   }
700   /// Set default data mapping attribute to Modifier:Kind
701   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
702                          OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
703     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
704     DMI.ImplicitBehavior = M;
705     DMI.SLoc = Loc;
706   }
707   /// Check whether the implicit-behavior has been set in defaultmap
708   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
709     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
710       return getTopOfStack()
711                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
712                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
713              getTopOfStack()
714                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
715                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
716              getTopOfStack()
717                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
718                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
719     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
720            OMPC_DEFAULTMAP_MODIFIER_unknown;
721   }
722 
723   ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
724     return ConstructTraits;
725   }
726   void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
727                             bool ScopeEntry) {
728     if (ScopeEntry)
729       ConstructTraits.append(Traits.begin(), Traits.end());
730     else
731       for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
732         llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
733         assert(Top == Trait && "Something left a trait on the stack!");
734         (void)Trait;
735         (void)Top;
736       }
737   }
738 
739   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
740     return getStackSize() <= Level ? DSA_unspecified
741                                    : getStackElemAtLevel(Level).DefaultAttr;
742   }
743   DefaultDataSharingAttributes getDefaultDSA() const {
744     return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
745   }
746   SourceLocation getDefaultDSALocation() const {
747     return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
748   }
749   OpenMPDefaultmapClauseModifier
750   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
751     return isStackEmpty()
752                ? OMPC_DEFAULTMAP_MODIFIER_unknown
753                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
754   }
755   OpenMPDefaultmapClauseModifier
756   getDefaultmapModifierAtLevel(unsigned Level,
757                                OpenMPDefaultmapClauseKind Kind) const {
758     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
759   }
760   bool isDefaultmapCapturedByRef(unsigned Level,
761                                  OpenMPDefaultmapClauseKind Kind) const {
762     OpenMPDefaultmapClauseModifier M =
763         getDefaultmapModifierAtLevel(Level, Kind);
764     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
765       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
766              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
767              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
768              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
769     }
770     return true;
771   }
772   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
773                                      OpenMPDefaultmapClauseKind Kind) {
774     switch (Kind) {
775     case OMPC_DEFAULTMAP_scalar:
776     case OMPC_DEFAULTMAP_pointer:
777       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
778              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
779              (M == OMPC_DEFAULTMAP_MODIFIER_default);
780     case OMPC_DEFAULTMAP_aggregate:
781       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
782     default:
783       break;
784     }
785     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
786   }
787   bool mustBeFirstprivateAtLevel(unsigned Level,
788                                  OpenMPDefaultmapClauseKind Kind) const {
789     OpenMPDefaultmapClauseModifier M =
790         getDefaultmapModifierAtLevel(Level, Kind);
791     return mustBeFirstprivateBase(M, Kind);
792   }
793   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
794     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
795     return mustBeFirstprivateBase(M, Kind);
796   }
797 
798   /// Checks if the specified variable is a threadprivate.
799   bool isThreadPrivate(VarDecl *D) {
800     const DSAVarData DVar = getTopDSA(D, false);
801     return isOpenMPThreadPrivate(DVar.CKind);
802   }
803 
804   /// Marks current region as ordered (it has an 'ordered' clause).
805   void setOrderedRegion(bool IsOrdered, const Expr *Param,
806                         OMPOrderedClause *Clause) {
807     if (IsOrdered)
808       getTopOfStack().OrderedRegion.emplace(Param, Clause);
809     else
810       getTopOfStack().OrderedRegion.reset();
811   }
812   /// Returns true, if region is ordered (has associated 'ordered' clause),
813   /// false - otherwise.
814   bool isOrderedRegion() const {
815     if (const SharingMapTy *Top = getTopOfStackOrNull())
816       return Top->OrderedRegion.hasValue();
817     return false;
818   }
819   /// Returns optional parameter for the ordered region.
820   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
821     if (const SharingMapTy *Top = getTopOfStackOrNull())
822       if (Top->OrderedRegion.hasValue())
823         return Top->OrderedRegion.getValue();
824     return std::make_pair(nullptr, nullptr);
825   }
826   /// Returns true, if parent region is ordered (has associated
827   /// 'ordered' clause), false - otherwise.
828   bool isParentOrderedRegion() const {
829     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
830       return Parent->OrderedRegion.hasValue();
831     return false;
832   }
833   /// Returns optional parameter for the ordered region.
834   std::pair<const Expr *, OMPOrderedClause *>
835   getParentOrderedRegionParam() const {
836     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
837       if (Parent->OrderedRegion.hasValue())
838         return Parent->OrderedRegion.getValue();
839     return std::make_pair(nullptr, nullptr);
840   }
841   /// Marks current region as nowait (it has a 'nowait' clause).
842   void setNowaitRegion(bool IsNowait = true) {
843     getTopOfStack().NowaitRegion = IsNowait;
844   }
845   /// Returns true, if parent region is nowait (has associated
846   /// 'nowait' clause), false - otherwise.
847   bool isParentNowaitRegion() const {
848     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
849       return Parent->NowaitRegion;
850     return false;
851   }
852   /// Marks parent region as cancel region.
853   void setParentCancelRegion(bool Cancel = true) {
854     if (SharingMapTy *Parent = getSecondOnStackOrNull())
855       Parent->CancelRegion |= Cancel;
856   }
857   /// Return true if current region has inner cancel construct.
858   bool isCancelRegion() const {
859     const SharingMapTy *Top = getTopOfStackOrNull();
860     return Top ? Top->CancelRegion : false;
861   }
862 
863   /// Mark that parent region already has scan directive.
864   void setParentHasScanDirective(SourceLocation Loc) {
865     if (SharingMapTy *Parent = getSecondOnStackOrNull())
866       Parent->PrevScanLocation = Loc;
867   }
868   /// Return true if current region has inner cancel construct.
869   bool doesParentHasScanDirective() const {
870     const SharingMapTy *Top = getSecondOnStackOrNull();
871     return Top ? Top->PrevScanLocation.isValid() : false;
872   }
873   /// Return true if current region has inner cancel construct.
874   SourceLocation getParentScanDirectiveLoc() const {
875     const SharingMapTy *Top = getSecondOnStackOrNull();
876     return Top ? Top->PrevScanLocation : SourceLocation();
877   }
878   /// Mark that parent region already has ordered directive.
879   void setParentHasOrderedDirective(SourceLocation Loc) {
880     if (SharingMapTy *Parent = getSecondOnStackOrNull())
881       Parent->PrevOrderedLocation = Loc;
882   }
883   /// Return true if current region has inner ordered construct.
884   bool doesParentHasOrderedDirective() const {
885     const SharingMapTy *Top = getSecondOnStackOrNull();
886     return Top ? Top->PrevOrderedLocation.isValid() : false;
887   }
888   /// Returns the location of the previously specified ordered directive.
889   SourceLocation getParentOrderedDirectiveLoc() const {
890     const SharingMapTy *Top = getSecondOnStackOrNull();
891     return Top ? Top->PrevOrderedLocation : SourceLocation();
892   }
893 
894   /// Set collapse value for the region.
895   void setAssociatedLoops(unsigned Val) {
896     getTopOfStack().AssociatedLoops = Val;
897     if (Val > 1)
898       getTopOfStack().HasMutipleLoops = true;
899   }
900   /// Return collapse value for region.
901   unsigned getAssociatedLoops() const {
902     const SharingMapTy *Top = getTopOfStackOrNull();
903     return Top ? Top->AssociatedLoops : 0;
904   }
905   /// Returns true if the construct is associated with multiple loops.
906   bool hasMutipleLoops() const {
907     const SharingMapTy *Top = getTopOfStackOrNull();
908     return Top ? Top->HasMutipleLoops : false;
909   }
910 
911   /// Marks current target region as one with closely nested teams
912   /// region.
913   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
914     if (SharingMapTy *Parent = getSecondOnStackOrNull())
915       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
916   }
917   /// Returns true, if current region has closely nested teams region.
918   bool hasInnerTeamsRegion() const {
919     return getInnerTeamsRegionLoc().isValid();
920   }
921   /// Returns location of the nested teams region (if any).
922   SourceLocation getInnerTeamsRegionLoc() const {
923     const SharingMapTy *Top = getTopOfStackOrNull();
924     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
925   }
926 
927   Scope *getCurScope() const {
928     const SharingMapTy *Top = getTopOfStackOrNull();
929     return Top ? Top->CurScope : nullptr;
930   }
931   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
932   SourceLocation getConstructLoc() const {
933     const SharingMapTy *Top = getTopOfStackOrNull();
934     return Top ? Top->ConstructLoc : SourceLocation();
935   }
936 
937   /// Do the check specified in \a Check to all component lists and return true
938   /// if any issue is found.
939   bool checkMappableExprComponentListsForDecl(
940       const ValueDecl *VD, bool CurrentRegionOnly,
941       const llvm::function_ref<
942           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
943                OpenMPClauseKind)>
944           Check) const {
945     if (isStackEmpty())
946       return false;
947     auto SI = begin();
948     auto SE = end();
949 
950     if (SI == SE)
951       return false;
952 
953     if (CurrentRegionOnly)
954       SE = std::next(SI);
955     else
956       std::advance(SI, 1);
957 
958     for (; SI != SE; ++SI) {
959       auto MI = SI->MappedExprComponents.find(VD);
960       if (MI != SI->MappedExprComponents.end())
961         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
962              MI->second.Components)
963           if (Check(L, MI->second.Kind))
964             return true;
965     }
966     return false;
967   }
968 
969   /// Do the check specified in \a Check to all component lists at a given level
970   /// and return true if any issue is found.
971   bool checkMappableExprComponentListsForDeclAtLevel(
972       const ValueDecl *VD, unsigned Level,
973       const llvm::function_ref<
974           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
975                OpenMPClauseKind)>
976           Check) const {
977     if (getStackSize() <= Level)
978       return false;
979 
980     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
981     auto MI = StackElem.MappedExprComponents.find(VD);
982     if (MI != StackElem.MappedExprComponents.end())
983       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
984            MI->second.Components)
985         if (Check(L, MI->second.Kind))
986           return true;
987     return false;
988   }
989 
990   /// Create a new mappable expression component list associated with a given
991   /// declaration and initialize it with the provided list of components.
992   void addMappableExpressionComponents(
993       const ValueDecl *VD,
994       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
995       OpenMPClauseKind WhereFoundClauseKind) {
996     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
997     // Create new entry and append the new components there.
998     MEC.Components.resize(MEC.Components.size() + 1);
999     MEC.Components.back().append(Components.begin(), Components.end());
1000     MEC.Kind = WhereFoundClauseKind;
1001   }
1002 
1003   unsigned getNestingLevel() const {
1004     assert(!isStackEmpty());
1005     return getStackSize() - 1;
1006   }
1007   void addDoacrossDependClause(OMPDependClause *C,
1008                                const OperatorOffsetTy &OpsOffs) {
1009     SharingMapTy *Parent = getSecondOnStackOrNull();
1010     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1011     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1012   }
1013   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1014   getDoacrossDependClauses() const {
1015     const SharingMapTy &StackElem = getTopOfStack();
1016     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1017       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1018       return llvm::make_range(Ref.begin(), Ref.end());
1019     }
1020     return llvm::make_range(StackElem.DoacrossDepends.end(),
1021                             StackElem.DoacrossDepends.end());
1022   }
1023 
1024   // Store types of classes which have been explicitly mapped
1025   void addMappedClassesQualTypes(QualType QT) {
1026     SharingMapTy &StackElem = getTopOfStack();
1027     StackElem.MappedClassesQualTypes.insert(QT);
1028   }
1029 
1030   // Return set of mapped classes types
1031   bool isClassPreviouslyMapped(QualType QT) const {
1032     const SharingMapTy &StackElem = getTopOfStack();
1033     return StackElem.MappedClassesQualTypes.contains(QT);
1034   }
1035 
1036   /// Adds global declare target to the parent target region.
1037   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1038     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1039                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1040            "Expected declare target link global.");
1041     for (auto &Elem : *this) {
1042       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1043         Elem.DeclareTargetLinkVarDecls.push_back(E);
1044         return;
1045       }
1046     }
1047   }
1048 
1049   /// Returns the list of globals with declare target link if current directive
1050   /// is target.
1051   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1052     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1053            "Expected target executable directive.");
1054     return getTopOfStack().DeclareTargetLinkVarDecls;
1055   }
1056 
1057   /// Adds list of allocators expressions.
1058   void addInnerAllocatorExpr(Expr *E) {
1059     getTopOfStack().InnerUsedAllocators.push_back(E);
1060   }
1061   /// Return list of used allocators.
1062   ArrayRef<Expr *> getInnerAllocators() const {
1063     return getTopOfStack().InnerUsedAllocators;
1064   }
1065   /// Marks the declaration as implicitly firstprivate nin the task-based
1066   /// regions.
1067   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1068     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1069   }
1070   /// Checks if the decl is implicitly firstprivate in the task-based region.
1071   bool isImplicitTaskFirstprivate(Decl *D) const {
1072     return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1073   }
1074 
1075   /// Marks decl as used in uses_allocators clause as the allocator.
1076   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1077     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1078   }
1079   /// Checks if specified decl is used in uses allocator clause as the
1080   /// allocator.
1081   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1082                                                         const Decl *D) const {
1083     const SharingMapTy &StackElem = getTopOfStack();
1084     auto I = StackElem.UsesAllocatorsDecls.find(D);
1085     if (I == StackElem.UsesAllocatorsDecls.end())
1086       return None;
1087     return I->getSecond();
1088   }
1089   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1090     const SharingMapTy &StackElem = getTopOfStack();
1091     auto I = StackElem.UsesAllocatorsDecls.find(D);
1092     if (I == StackElem.UsesAllocatorsDecls.end())
1093       return None;
1094     return I->getSecond();
1095   }
1096 
1097   void addDeclareMapperVarRef(Expr *Ref) {
1098     SharingMapTy &StackElem = getTopOfStack();
1099     StackElem.DeclareMapperVar = Ref;
1100   }
1101   const Expr *getDeclareMapperVarRef() const {
1102     const SharingMapTy *Top = getTopOfStackOrNull();
1103     return Top ? Top->DeclareMapperVar : nullptr;
1104   }
1105 };
1106 
1107 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1108   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1109 }
1110 
1111 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1112   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1113          DKind == OMPD_unknown;
1114 }
1115 
1116 } // namespace
1117 
1118 static const Expr *getExprAsWritten(const Expr *E) {
1119   if (const auto *FE = dyn_cast<FullExpr>(E))
1120     E = FE->getSubExpr();
1121 
1122   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1123     E = MTE->getSubExpr();
1124 
1125   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1126     E = Binder->getSubExpr();
1127 
1128   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1129     E = ICE->getSubExprAsWritten();
1130   return E->IgnoreParens();
1131 }
1132 
1133 static Expr *getExprAsWritten(Expr *E) {
1134   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1135 }
1136 
1137 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1138   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1139     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1140       D = ME->getMemberDecl();
1141   const auto *VD = dyn_cast<VarDecl>(D);
1142   const auto *FD = dyn_cast<FieldDecl>(D);
1143   if (VD != nullptr) {
1144     VD = VD->getCanonicalDecl();
1145     D = VD;
1146   } else {
1147     assert(FD);
1148     FD = FD->getCanonicalDecl();
1149     D = FD;
1150   }
1151   return D;
1152 }
1153 
1154 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1155   return const_cast<ValueDecl *>(
1156       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1157 }
1158 
1159 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1160                                           ValueDecl *D) const {
1161   D = getCanonicalDecl(D);
1162   auto *VD = dyn_cast<VarDecl>(D);
1163   const auto *FD = dyn_cast<FieldDecl>(D);
1164   DSAVarData DVar;
1165   if (Iter == end()) {
1166     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1167     // in a region but not in construct]
1168     //  File-scope or namespace-scope variables referenced in called routines
1169     //  in the region are shared unless they appear in a threadprivate
1170     //  directive.
1171     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1172       DVar.CKind = OMPC_shared;
1173 
1174     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1175     // in a region but not in construct]
1176     //  Variables with static storage duration that are declared in called
1177     //  routines in the region are shared.
1178     if (VD && VD->hasGlobalStorage())
1179       DVar.CKind = OMPC_shared;
1180 
1181     // Non-static data members are shared by default.
1182     if (FD)
1183       DVar.CKind = OMPC_shared;
1184 
1185     return DVar;
1186   }
1187 
1188   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1189   // in a Construct, C/C++, predetermined, p.1]
1190   // Variables with automatic storage duration that are declared in a scope
1191   // inside the construct are private.
1192   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1193       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1194     DVar.CKind = OMPC_private;
1195     return DVar;
1196   }
1197 
1198   DVar.DKind = Iter->Directive;
1199   // Explicitly specified attributes and local variables with predetermined
1200   // attributes.
1201   if (Iter->SharingMap.count(D)) {
1202     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1203     DVar.RefExpr = Data.RefExpr.getPointer();
1204     DVar.PrivateCopy = Data.PrivateCopy;
1205     DVar.CKind = Data.Attributes;
1206     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1207     DVar.Modifier = Data.Modifier;
1208     DVar.AppliedToPointee = Data.AppliedToPointee;
1209     return DVar;
1210   }
1211 
1212   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1213   // in a Construct, C/C++, implicitly determined, p.1]
1214   //  In a parallel or task construct, the data-sharing attributes of these
1215   //  variables are determined by the default clause, if present.
1216   switch (Iter->DefaultAttr) {
1217   case DSA_shared:
1218     DVar.CKind = OMPC_shared;
1219     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1220     return DVar;
1221   case DSA_none:
1222     return DVar;
1223   case DSA_firstprivate:
1224     if (VD->getStorageDuration() == SD_Static &&
1225         VD->getDeclContext()->isFileContext()) {
1226       DVar.CKind = OMPC_unknown;
1227     } else {
1228       DVar.CKind = OMPC_firstprivate;
1229     }
1230     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1231     return DVar;
1232   case DSA_unspecified:
1233     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1234     // in a Construct, implicitly determined, p.2]
1235     //  In a parallel construct, if no default clause is present, these
1236     //  variables are shared.
1237     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1238     if ((isOpenMPParallelDirective(DVar.DKind) &&
1239          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1240         isOpenMPTeamsDirective(DVar.DKind)) {
1241       DVar.CKind = OMPC_shared;
1242       return DVar;
1243     }
1244 
1245     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1246     // in a Construct, implicitly determined, p.4]
1247     //  In a task construct, if no default clause is present, a variable that in
1248     //  the enclosing context is determined to be shared by all implicit tasks
1249     //  bound to the current team is shared.
1250     if (isOpenMPTaskingDirective(DVar.DKind)) {
1251       DSAVarData DVarTemp;
1252       const_iterator I = Iter, E = end();
1253       do {
1254         ++I;
1255         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1256         // Referenced in a Construct, implicitly determined, p.6]
1257         //  In a task construct, if no default clause is present, a variable
1258         //  whose data-sharing attribute is not determined by the rules above is
1259         //  firstprivate.
1260         DVarTemp = getDSA(I, D);
1261         if (DVarTemp.CKind != OMPC_shared) {
1262           DVar.RefExpr = nullptr;
1263           DVar.CKind = OMPC_firstprivate;
1264           return DVar;
1265         }
1266       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1267       DVar.CKind =
1268           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1269       return DVar;
1270     }
1271   }
1272   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1273   // in a Construct, implicitly determined, p.3]
1274   //  For constructs other than task, if no default clause is present, these
1275   //  variables inherit their data-sharing attributes from the enclosing
1276   //  context.
1277   return getDSA(++Iter, D);
1278 }
1279 
1280 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1281                                          const Expr *NewDE) {
1282   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1283   D = getCanonicalDecl(D);
1284   SharingMapTy &StackElem = getTopOfStack();
1285   auto It = StackElem.AlignedMap.find(D);
1286   if (It == StackElem.AlignedMap.end()) {
1287     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1288     StackElem.AlignedMap[D] = NewDE;
1289     return nullptr;
1290   }
1291   assert(It->second && "Unexpected nullptr expr in the aligned map");
1292   return It->second;
1293 }
1294 
1295 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1296                                              const Expr *NewDE) {
1297   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1298   D = getCanonicalDecl(D);
1299   SharingMapTy &StackElem = getTopOfStack();
1300   auto It = StackElem.NontemporalMap.find(D);
1301   if (It == StackElem.NontemporalMap.end()) {
1302     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1303     StackElem.NontemporalMap[D] = NewDE;
1304     return nullptr;
1305   }
1306   assert(It->second && "Unexpected nullptr expr in the aligned map");
1307   return It->second;
1308 }
1309 
1310 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1311   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1312   D = getCanonicalDecl(D);
1313   SharingMapTy &StackElem = getTopOfStack();
1314   StackElem.LCVMap.try_emplace(
1315       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1316 }
1317 
1318 const DSAStackTy::LCDeclInfo
1319 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1320   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1321   D = getCanonicalDecl(D);
1322   const SharingMapTy &StackElem = getTopOfStack();
1323   auto It = StackElem.LCVMap.find(D);
1324   if (It != StackElem.LCVMap.end())
1325     return It->second;
1326   return {0, nullptr};
1327 }
1328 
1329 const DSAStackTy::LCDeclInfo
1330 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1331   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1332   D = getCanonicalDecl(D);
1333   for (unsigned I = Level + 1; I > 0; --I) {
1334     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1335     auto It = StackElem.LCVMap.find(D);
1336     if (It != StackElem.LCVMap.end())
1337       return It->second;
1338   }
1339   return {0, nullptr};
1340 }
1341 
1342 const DSAStackTy::LCDeclInfo
1343 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1344   const SharingMapTy *Parent = getSecondOnStackOrNull();
1345   assert(Parent && "Data-sharing attributes stack is empty");
1346   D = getCanonicalDecl(D);
1347   auto It = Parent->LCVMap.find(D);
1348   if (It != Parent->LCVMap.end())
1349     return It->second;
1350   return {0, nullptr};
1351 }
1352 
1353 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1354   const SharingMapTy *Parent = getSecondOnStackOrNull();
1355   assert(Parent && "Data-sharing attributes stack is empty");
1356   if (Parent->LCVMap.size() < I)
1357     return nullptr;
1358   for (const auto &Pair : Parent->LCVMap)
1359     if (Pair.second.first == I)
1360       return Pair.first;
1361   return nullptr;
1362 }
1363 
1364 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1365                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1366                         bool AppliedToPointee) {
1367   D = getCanonicalDecl(D);
1368   if (A == OMPC_threadprivate) {
1369     DSAInfo &Data = Threadprivates[D];
1370     Data.Attributes = A;
1371     Data.RefExpr.setPointer(E);
1372     Data.PrivateCopy = nullptr;
1373     Data.Modifier = Modifier;
1374   } else {
1375     DSAInfo &Data = getTopOfStack().SharingMap[D];
1376     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1377            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1378            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1379            (isLoopControlVariable(D).first && A == OMPC_private));
1380     Data.Modifier = Modifier;
1381     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1382       Data.RefExpr.setInt(/*IntVal=*/true);
1383       return;
1384     }
1385     const bool IsLastprivate =
1386         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1387     Data.Attributes = A;
1388     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1389     Data.PrivateCopy = PrivateCopy;
1390     Data.AppliedToPointee = AppliedToPointee;
1391     if (PrivateCopy) {
1392       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1393       Data.Modifier = Modifier;
1394       Data.Attributes = A;
1395       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1396       Data.PrivateCopy = nullptr;
1397       Data.AppliedToPointee = AppliedToPointee;
1398     }
1399   }
1400 }
1401 
1402 /// Build a variable declaration for OpenMP loop iteration variable.
1403 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1404                              StringRef Name, const AttrVec *Attrs = nullptr,
1405                              DeclRefExpr *OrigRef = nullptr) {
1406   DeclContext *DC = SemaRef.CurContext;
1407   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1408   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1409   auto *Decl =
1410       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1411   if (Attrs) {
1412     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1413          I != E; ++I)
1414       Decl->addAttr(*I);
1415   }
1416   Decl->setImplicit();
1417   if (OrigRef) {
1418     Decl->addAttr(
1419         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1420   }
1421   return Decl;
1422 }
1423 
1424 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1425                                      SourceLocation Loc,
1426                                      bool RefersToCapture = false) {
1427   D->setReferenced();
1428   D->markUsed(S.Context);
1429   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1430                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1431                              VK_LValue);
1432 }
1433 
1434 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1435                                            BinaryOperatorKind BOK) {
1436   D = getCanonicalDecl(D);
1437   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1438   assert(
1439       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1440       "Additional reduction info may be specified only for reduction items.");
1441   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1442   assert(ReductionData.ReductionRange.isInvalid() &&
1443          (getTopOfStack().Directive == OMPD_taskgroup ||
1444           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1445             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1446            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1447          "Additional reduction info may be specified only once for reduction "
1448          "items.");
1449   ReductionData.set(BOK, SR);
1450   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1451   if (!TaskgroupReductionRef) {
1452     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1453                                SemaRef.Context.VoidPtrTy, ".task_red.");
1454     TaskgroupReductionRef =
1455         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1456   }
1457 }
1458 
1459 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1460                                            const Expr *ReductionRef) {
1461   D = getCanonicalDecl(D);
1462   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1463   assert(
1464       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1465       "Additional reduction info may be specified only for reduction items.");
1466   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1467   assert(ReductionData.ReductionRange.isInvalid() &&
1468          (getTopOfStack().Directive == OMPD_taskgroup ||
1469           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1470             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1471            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1472          "Additional reduction info may be specified only once for reduction "
1473          "items.");
1474   ReductionData.set(ReductionRef, SR);
1475   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1476   if (!TaskgroupReductionRef) {
1477     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1478                                SemaRef.Context.VoidPtrTy, ".task_red.");
1479     TaskgroupReductionRef =
1480         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1481   }
1482 }
1483 
1484 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1485     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1486     Expr *&TaskgroupDescriptor) const {
1487   D = getCanonicalDecl(D);
1488   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1489   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1490     const DSAInfo &Data = I->SharingMap.lookup(D);
1491     if (Data.Attributes != OMPC_reduction ||
1492         Data.Modifier != OMPC_REDUCTION_task)
1493       continue;
1494     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1495     if (!ReductionData.ReductionOp ||
1496         ReductionData.ReductionOp.is<const Expr *>())
1497       return DSAVarData();
1498     SR = ReductionData.ReductionRange;
1499     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1500     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1501                                        "expression for the descriptor is not "
1502                                        "set.");
1503     TaskgroupDescriptor = I->TaskgroupReductionRef;
1504     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1505                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1506                       /*AppliedToPointee=*/false);
1507   }
1508   return DSAVarData();
1509 }
1510 
1511 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1512     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1513     Expr *&TaskgroupDescriptor) const {
1514   D = getCanonicalDecl(D);
1515   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1516   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1517     const DSAInfo &Data = I->SharingMap.lookup(D);
1518     if (Data.Attributes != OMPC_reduction ||
1519         Data.Modifier != OMPC_REDUCTION_task)
1520       continue;
1521     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1522     if (!ReductionData.ReductionOp ||
1523         !ReductionData.ReductionOp.is<const Expr *>())
1524       return DSAVarData();
1525     SR = ReductionData.ReductionRange;
1526     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1527     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1528                                        "expression for the descriptor is not "
1529                                        "set.");
1530     TaskgroupDescriptor = I->TaskgroupReductionRef;
1531     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1532                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1533                       /*AppliedToPointee=*/false);
1534   }
1535   return DSAVarData();
1536 }
1537 
1538 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1539   D = D->getCanonicalDecl();
1540   for (const_iterator E = end(); I != E; ++I) {
1541     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1542         isOpenMPTargetExecutionDirective(I->Directive)) {
1543       if (I->CurScope) {
1544         Scope *TopScope = I->CurScope->getParent();
1545         Scope *CurScope = getCurScope();
1546         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1547           CurScope = CurScope->getParent();
1548         return CurScope != TopScope;
1549       }
1550       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1551         if (I->Context == DC)
1552           return true;
1553       return false;
1554     }
1555   }
1556   return false;
1557 }
1558 
1559 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1560                                   bool AcceptIfMutable = true,
1561                                   bool *IsClassType = nullptr) {
1562   ASTContext &Context = SemaRef.getASTContext();
1563   Type = Type.getNonReferenceType().getCanonicalType();
1564   bool IsConstant = Type.isConstant(Context);
1565   Type = Context.getBaseElementType(Type);
1566   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1567                                 ? Type->getAsCXXRecordDecl()
1568                                 : nullptr;
1569   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1570     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1571       RD = CTD->getTemplatedDecl();
1572   if (IsClassType)
1573     *IsClassType = RD;
1574   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1575                          RD->hasDefinition() && RD->hasMutableFields());
1576 }
1577 
1578 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1579                                       QualType Type, OpenMPClauseKind CKind,
1580                                       SourceLocation ELoc,
1581                                       bool AcceptIfMutable = true,
1582                                       bool ListItemNotVar = false) {
1583   ASTContext &Context = SemaRef.getASTContext();
1584   bool IsClassType;
1585   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1586     unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1587                     : IsClassType  ? diag::err_omp_const_not_mutable_variable
1588                                    : diag::err_omp_const_variable;
1589     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1590     if (!ListItemNotVar && D) {
1591       const VarDecl *VD = dyn_cast<VarDecl>(D);
1592       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1593                                VarDecl::DeclarationOnly;
1594       SemaRef.Diag(D->getLocation(),
1595                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1596           << D;
1597     }
1598     return true;
1599   }
1600   return false;
1601 }
1602 
1603 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1604                                                    bool FromParent) {
1605   D = getCanonicalDecl(D);
1606   DSAVarData DVar;
1607 
1608   auto *VD = dyn_cast<VarDecl>(D);
1609   auto TI = Threadprivates.find(D);
1610   if (TI != Threadprivates.end()) {
1611     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1612     DVar.CKind = OMPC_threadprivate;
1613     DVar.Modifier = TI->getSecond().Modifier;
1614     return DVar;
1615   }
1616   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1617     DVar.RefExpr = buildDeclRefExpr(
1618         SemaRef, VD, D->getType().getNonReferenceType(),
1619         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1620     DVar.CKind = OMPC_threadprivate;
1621     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1622     return DVar;
1623   }
1624   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1625   // in a Construct, C/C++, predetermined, p.1]
1626   //  Variables appearing in threadprivate directives are threadprivate.
1627   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1628        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1629          SemaRef.getLangOpts().OpenMPUseTLS &&
1630          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1631       (VD && VD->getStorageClass() == SC_Register &&
1632        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1633     DVar.RefExpr = buildDeclRefExpr(
1634         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1635     DVar.CKind = OMPC_threadprivate;
1636     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1637     return DVar;
1638   }
1639   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1640       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1641       !isLoopControlVariable(D).first) {
1642     const_iterator IterTarget =
1643         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1644           return isOpenMPTargetExecutionDirective(Data.Directive);
1645         });
1646     if (IterTarget != end()) {
1647       const_iterator ParentIterTarget = IterTarget + 1;
1648       for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1649         if (isOpenMPLocal(VD, Iter)) {
1650           DVar.RefExpr =
1651               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1652                                D->getLocation());
1653           DVar.CKind = OMPC_threadprivate;
1654           return DVar;
1655         }
1656       }
1657       if (!isClauseParsingMode() || IterTarget != begin()) {
1658         auto DSAIter = IterTarget->SharingMap.find(D);
1659         if (DSAIter != IterTarget->SharingMap.end() &&
1660             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1661           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1662           DVar.CKind = OMPC_threadprivate;
1663           return DVar;
1664         }
1665         const_iterator End = end();
1666         if (!SemaRef.isOpenMPCapturedByRef(D,
1667                                            std::distance(ParentIterTarget, End),
1668                                            /*OpenMPCaptureLevel=*/0)) {
1669           DVar.RefExpr =
1670               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1671                                IterTarget->ConstructLoc);
1672           DVar.CKind = OMPC_threadprivate;
1673           return DVar;
1674         }
1675       }
1676     }
1677   }
1678 
1679   if (isStackEmpty())
1680     // Not in OpenMP execution region and top scope was already checked.
1681     return DVar;
1682 
1683   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1684   // in a Construct, C/C++, predetermined, p.4]
1685   //  Static data members are shared.
1686   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1687   // in a Construct, C/C++, predetermined, p.7]
1688   //  Variables with static storage duration that are declared in a scope
1689   //  inside the construct are shared.
1690   if (VD && VD->isStaticDataMember()) {
1691     // Check for explicitly specified attributes.
1692     const_iterator I = begin();
1693     const_iterator EndI = end();
1694     if (FromParent && I != EndI)
1695       ++I;
1696     if (I != EndI) {
1697       auto It = I->SharingMap.find(D);
1698       if (It != I->SharingMap.end()) {
1699         const DSAInfo &Data = It->getSecond();
1700         DVar.RefExpr = Data.RefExpr.getPointer();
1701         DVar.PrivateCopy = Data.PrivateCopy;
1702         DVar.CKind = Data.Attributes;
1703         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1704         DVar.DKind = I->Directive;
1705         DVar.Modifier = Data.Modifier;
1706         DVar.AppliedToPointee = Data.AppliedToPointee;
1707         return DVar;
1708       }
1709     }
1710 
1711     DVar.CKind = OMPC_shared;
1712     return DVar;
1713   }
1714 
1715   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1716   // The predetermined shared attribute for const-qualified types having no
1717   // mutable members was removed after OpenMP 3.1.
1718   if (SemaRef.LangOpts.OpenMP <= 31) {
1719     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1720     // in a Construct, C/C++, predetermined, p.6]
1721     //  Variables with const qualified type having no mutable member are
1722     //  shared.
1723     if (isConstNotMutableType(SemaRef, D->getType())) {
1724       // Variables with const-qualified type having no mutable member may be
1725       // listed in a firstprivate clause, even if they are static data members.
1726       DSAVarData DVarTemp = hasInnermostDSA(
1727           D,
1728           [](OpenMPClauseKind C, bool) {
1729             return C == OMPC_firstprivate || C == OMPC_shared;
1730           },
1731           MatchesAlways, FromParent);
1732       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1733         return DVarTemp;
1734 
1735       DVar.CKind = OMPC_shared;
1736       return DVar;
1737     }
1738   }
1739 
1740   // Explicitly specified attributes and local variables with predetermined
1741   // attributes.
1742   const_iterator I = begin();
1743   const_iterator EndI = end();
1744   if (FromParent && I != EndI)
1745     ++I;
1746   if (I == EndI)
1747     return DVar;
1748   auto It = I->SharingMap.find(D);
1749   if (It != I->SharingMap.end()) {
1750     const DSAInfo &Data = It->getSecond();
1751     DVar.RefExpr = Data.RefExpr.getPointer();
1752     DVar.PrivateCopy = Data.PrivateCopy;
1753     DVar.CKind = Data.Attributes;
1754     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1755     DVar.DKind = I->Directive;
1756     DVar.Modifier = Data.Modifier;
1757     DVar.AppliedToPointee = Data.AppliedToPointee;
1758   }
1759 
1760   return DVar;
1761 }
1762 
1763 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1764                                                         bool FromParent) const {
1765   if (isStackEmpty()) {
1766     const_iterator I;
1767     return getDSA(I, D);
1768   }
1769   D = getCanonicalDecl(D);
1770   const_iterator StartI = begin();
1771   const_iterator EndI = end();
1772   if (FromParent && StartI != EndI)
1773     ++StartI;
1774   return getDSA(StartI, D);
1775 }
1776 
1777 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1778                                                         unsigned Level) const {
1779   if (getStackSize() <= Level)
1780     return DSAVarData();
1781   D = getCanonicalDecl(D);
1782   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1783   return getDSA(StartI, D);
1784 }
1785 
1786 const DSAStackTy::DSAVarData
1787 DSAStackTy::hasDSA(ValueDecl *D,
1788                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1789                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1790                    bool FromParent) const {
1791   if (isStackEmpty())
1792     return {};
1793   D = getCanonicalDecl(D);
1794   const_iterator I = begin();
1795   const_iterator EndI = end();
1796   if (FromParent && I != EndI)
1797     ++I;
1798   for (; I != EndI; ++I) {
1799     if (!DPred(I->Directive) &&
1800         !isImplicitOrExplicitTaskingRegion(I->Directive))
1801       continue;
1802     const_iterator NewI = I;
1803     DSAVarData DVar = getDSA(NewI, D);
1804     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1805       return DVar;
1806   }
1807   return {};
1808 }
1809 
1810 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1811     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1812     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1813     bool FromParent) const {
1814   if (isStackEmpty())
1815     return {};
1816   D = getCanonicalDecl(D);
1817   const_iterator StartI = begin();
1818   const_iterator EndI = end();
1819   if (FromParent && StartI != EndI)
1820     ++StartI;
1821   if (StartI == EndI || !DPred(StartI->Directive))
1822     return {};
1823   const_iterator NewI = StartI;
1824   DSAVarData DVar = getDSA(NewI, D);
1825   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1826              ? DVar
1827              : DSAVarData();
1828 }
1829 
1830 bool DSAStackTy::hasExplicitDSA(
1831     const ValueDecl *D,
1832     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1833     unsigned Level, bool NotLastprivate) const {
1834   if (getStackSize() <= Level)
1835     return false;
1836   D = getCanonicalDecl(D);
1837   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1838   auto I = StackElem.SharingMap.find(D);
1839   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1840       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1841       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1842     return true;
1843   // Check predetermined rules for the loop control variables.
1844   auto LI = StackElem.LCVMap.find(D);
1845   if (LI != StackElem.LCVMap.end())
1846     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1847   return false;
1848 }
1849 
1850 bool DSAStackTy::hasExplicitDirective(
1851     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1852     unsigned Level) const {
1853   if (getStackSize() <= Level)
1854     return false;
1855   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1856   return DPred(StackElem.Directive);
1857 }
1858 
1859 bool DSAStackTy::hasDirective(
1860     const llvm::function_ref<bool(OpenMPDirectiveKind,
1861                                   const DeclarationNameInfo &, SourceLocation)>
1862         DPred,
1863     bool FromParent) const {
1864   // We look only in the enclosing region.
1865   size_t Skip = FromParent ? 2 : 1;
1866   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1867        I != E; ++I) {
1868     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1869       return true;
1870   }
1871   return false;
1872 }
1873 
1874 void Sema::InitDataSharingAttributesStack() {
1875   VarDataSharingAttributesStack = new DSAStackTy(*this);
1876 }
1877 
1878 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1879 
1880 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
1881 
1882 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1883   DSAStack->popFunction(OldFSI);
1884 }
1885 
1886 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1887   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1888          "Expected OpenMP device compilation.");
1889   return !S.isInOpenMPTargetExecutionDirective();
1890 }
1891 
1892 namespace {
1893 /// Status of the function emission on the host/device.
1894 enum class FunctionEmissionStatus {
1895   Emitted,
1896   Discarded,
1897   Unknown,
1898 };
1899 } // anonymous namespace
1900 
1901 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1902                                                          unsigned DiagID,
1903                                                          FunctionDecl *FD) {
1904   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1905          "Expected OpenMP device compilation.");
1906 
1907   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1908   if (FD) {
1909     FunctionEmissionStatus FES = getEmissionStatus(FD);
1910     switch (FES) {
1911     case FunctionEmissionStatus::Emitted:
1912       Kind = SemaDiagnosticBuilder::K_Immediate;
1913       break;
1914     case FunctionEmissionStatus::Unknown:
1915       // TODO: We should always delay diagnostics here in case a target
1916       //       region is in a function we do not emit. However, as the
1917       //       current diagnostics are associated with the function containing
1918       //       the target region and we do not emit that one, we would miss out
1919       //       on diagnostics for the target region itself. We need to anchor
1920       //       the diagnostics with the new generated function *or* ensure we
1921       //       emit diagnostics associated with the surrounding function.
1922       Kind = isOpenMPDeviceDelayedContext(*this)
1923                  ? SemaDiagnosticBuilder::K_Deferred
1924                  : SemaDiagnosticBuilder::K_Immediate;
1925       break;
1926     case FunctionEmissionStatus::TemplateDiscarded:
1927     case FunctionEmissionStatus::OMPDiscarded:
1928       Kind = SemaDiagnosticBuilder::K_Nop;
1929       break;
1930     case FunctionEmissionStatus::CUDADiscarded:
1931       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1932       break;
1933     }
1934   }
1935 
1936   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1937 }
1938 
1939 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1940                                                        unsigned DiagID,
1941                                                        FunctionDecl *FD) {
1942   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1943          "Expected OpenMP host compilation.");
1944 
1945   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1946   if (FD) {
1947     FunctionEmissionStatus FES = getEmissionStatus(FD);
1948     switch (FES) {
1949     case FunctionEmissionStatus::Emitted:
1950       Kind = SemaDiagnosticBuilder::K_Immediate;
1951       break;
1952     case FunctionEmissionStatus::Unknown:
1953       Kind = SemaDiagnosticBuilder::K_Deferred;
1954       break;
1955     case FunctionEmissionStatus::TemplateDiscarded:
1956     case FunctionEmissionStatus::OMPDiscarded:
1957     case FunctionEmissionStatus::CUDADiscarded:
1958       Kind = SemaDiagnosticBuilder::K_Nop;
1959       break;
1960     }
1961   }
1962 
1963   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1964 }
1965 
1966 static OpenMPDefaultmapClauseKind
1967 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1968   if (LO.OpenMP <= 45) {
1969     if (VD->getType().getNonReferenceType()->isScalarType())
1970       return OMPC_DEFAULTMAP_scalar;
1971     return OMPC_DEFAULTMAP_aggregate;
1972   }
1973   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1974     return OMPC_DEFAULTMAP_pointer;
1975   if (VD->getType().getNonReferenceType()->isScalarType())
1976     return OMPC_DEFAULTMAP_scalar;
1977   return OMPC_DEFAULTMAP_aggregate;
1978 }
1979 
1980 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1981                                  unsigned OpenMPCaptureLevel) const {
1982   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1983 
1984   ASTContext &Ctx = getASTContext();
1985   bool IsByRef = true;
1986 
1987   // Find the directive that is associated with the provided scope.
1988   D = cast<ValueDecl>(D->getCanonicalDecl());
1989   QualType Ty = D->getType();
1990 
1991   bool IsVariableUsedInMapClause = false;
1992   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1993     // This table summarizes how a given variable should be passed to the device
1994     // given its type and the clauses where it appears. This table is based on
1995     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1996     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1997     //
1998     // =========================================================================
1999     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
2000     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
2001     // =========================================================================
2002     // | scl  |               |     |       |       -       |          | bycopy|
2003     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2004     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2005     // | scl  |       x       |     |       |       -       |          | byref |
2006     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2007     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2008     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2009     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2010     //
2011     // | agg  |      n.a.     |     |       |       -       |          | byref |
2012     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2013     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2014     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2015     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2016     //
2017     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2018     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2019     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2020     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2021     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2022     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2023     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2024     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2025     // =========================================================================
2026     // Legend:
2027     //  scl - scalar
2028     //  ptr - pointer
2029     //  agg - aggregate
2030     //  x - applies
2031     //  - - invalid in this combination
2032     //  [] - mapped with an array section
2033     //  byref - should be mapped by reference
2034     //  byval - should be mapped by value
2035     //  null - initialize a local variable to null on the device
2036     //
2037     // Observations:
2038     //  - All scalar declarations that show up in a map clause have to be passed
2039     //    by reference, because they may have been mapped in the enclosing data
2040     //    environment.
2041     //  - If the scalar value does not fit the size of uintptr, it has to be
2042     //    passed by reference, regardless the result in the table above.
2043     //  - For pointers mapped by value that have either an implicit map or an
2044     //    array section, the runtime library may pass the NULL value to the
2045     //    device instead of the value passed to it by the compiler.
2046 
2047     if (Ty->isReferenceType())
2048       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2049 
2050     // Locate map clauses and see if the variable being captured is referred to
2051     // in any of those clauses. Here we only care about variables, not fields,
2052     // because fields are part of aggregates.
2053     bool IsVariableAssociatedWithSection = false;
2054 
2055     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2056         D, Level,
2057         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2058          D](OMPClauseMappableExprCommon::MappableExprComponentListRef
2059                 MapExprComponents,
2060             OpenMPClauseKind WhereFoundClauseKind) {
2061           // Only the map clause information influences how a variable is
2062           // captured. E.g. is_device_ptr does not require changing the default
2063           // behavior.
2064           if (WhereFoundClauseKind != OMPC_map)
2065             return false;
2066 
2067           auto EI = MapExprComponents.rbegin();
2068           auto EE = MapExprComponents.rend();
2069 
2070           assert(EI != EE && "Invalid map expression!");
2071 
2072           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2073             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2074 
2075           ++EI;
2076           if (EI == EE)
2077             return false;
2078 
2079           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2080               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2081               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2082               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2083             IsVariableAssociatedWithSection = true;
2084             // There is nothing more we need to know about this variable.
2085             return true;
2086           }
2087 
2088           // Keep looking for more map info.
2089           return false;
2090         });
2091 
2092     if (IsVariableUsedInMapClause) {
2093       // If variable is identified in a map clause it is always captured by
2094       // reference except if it is a pointer that is dereferenced somehow.
2095       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2096     } else {
2097       // By default, all the data that has a scalar type is mapped by copy
2098       // (except for reduction variables).
2099       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2100       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2101                  !Ty->isAnyPointerType()) ||
2102                 !Ty->isScalarType() ||
2103                 DSAStack->isDefaultmapCapturedByRef(
2104                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2105                 DSAStack->hasExplicitDSA(
2106                     D,
2107                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2108                       return K == OMPC_reduction && !AppliedToPointee;
2109                     },
2110                     Level);
2111     }
2112   }
2113 
2114   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2115     IsByRef =
2116         ((IsVariableUsedInMapClause &&
2117           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2118               OMPD_target) ||
2119          !(DSAStack->hasExplicitDSA(
2120                D,
2121                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2122                  return K == OMPC_firstprivate ||
2123                         (K == OMPC_reduction && AppliedToPointee);
2124                },
2125                Level, /*NotLastprivate=*/true) ||
2126            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2127         // If the variable is artificial and must be captured by value - try to
2128         // capture by value.
2129         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2130           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2131         // If the variable is implicitly firstprivate and scalar - capture by
2132         // copy
2133         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2134           !DSAStack->hasExplicitDSA(
2135               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2136               Level) &&
2137           !DSAStack->isLoopControlVariable(D, Level).first);
2138   }
2139 
2140   // When passing data by copy, we need to make sure it fits the uintptr size
2141   // and alignment, because the runtime library only deals with uintptr types.
2142   // If it does not fit the uintptr size, we need to pass the data by reference
2143   // instead.
2144   if (!IsByRef &&
2145       (Ctx.getTypeSizeInChars(Ty) >
2146            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2147        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2148     IsByRef = true;
2149   }
2150 
2151   return IsByRef;
2152 }
2153 
2154 unsigned Sema::getOpenMPNestingLevel() const {
2155   assert(getLangOpts().OpenMP);
2156   return DSAStack->getNestingLevel();
2157 }
2158 
2159 bool Sema::isInOpenMPTargetExecutionDirective() const {
2160   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2161           !DSAStack->isClauseParsingMode()) ||
2162          DSAStack->hasDirective(
2163              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2164                 SourceLocation) -> bool {
2165                return isOpenMPTargetExecutionDirective(K);
2166              },
2167              false);
2168 }
2169 
2170 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2171                                     unsigned StopAt) {
2172   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2173   D = getCanonicalDecl(D);
2174 
2175   auto *VD = dyn_cast<VarDecl>(D);
2176   // Do not capture constexpr variables.
2177   if (VD && VD->isConstexpr())
2178     return nullptr;
2179 
2180   // If we want to determine whether the variable should be captured from the
2181   // perspective of the current capturing scope, and we've already left all the
2182   // capturing scopes of the top directive on the stack, check from the
2183   // perspective of its parent directive (if any) instead.
2184   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2185       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2186 
2187   // If we are attempting to capture a global variable in a directive with
2188   // 'target' we return true so that this global is also mapped to the device.
2189   //
2190   if (VD && !VD->hasLocalStorage() &&
2191       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2192     if (isInOpenMPTargetExecutionDirective()) {
2193       DSAStackTy::DSAVarData DVarTop =
2194           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2195       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2196         return VD;
2197       // If the declaration is enclosed in a 'declare target' directive,
2198       // then it should not be captured.
2199       //
2200       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2201         return nullptr;
2202       CapturedRegionScopeInfo *CSI = nullptr;
2203       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2204                llvm::reverse(FunctionScopes),
2205                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2206         if (!isa<CapturingScopeInfo>(FSI))
2207           return nullptr;
2208         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2209           if (RSI->CapRegionKind == CR_OpenMP) {
2210             CSI = RSI;
2211             break;
2212           }
2213       }
2214       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2215       SmallVector<OpenMPDirectiveKind, 4> Regions;
2216       getOpenMPCaptureRegions(Regions,
2217                               DSAStack->getDirective(CSI->OpenMPLevel));
2218       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2219         return VD;
2220     }
2221     if (isInOpenMPDeclareTargetContext()) {
2222       // Try to mark variable as declare target if it is used in capturing
2223       // regions.
2224       if (LangOpts.OpenMP <= 45 &&
2225           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2226         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2227       return nullptr;
2228     }
2229   }
2230 
2231   if (CheckScopeInfo) {
2232     bool OpenMPFound = false;
2233     for (unsigned I = StopAt + 1; I > 0; --I) {
2234       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2235       if (!isa<CapturingScopeInfo>(FSI))
2236         return nullptr;
2237       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2238         if (RSI->CapRegionKind == CR_OpenMP) {
2239           OpenMPFound = true;
2240           break;
2241         }
2242     }
2243     if (!OpenMPFound)
2244       return nullptr;
2245   }
2246 
2247   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2248       (!DSAStack->isClauseParsingMode() ||
2249        DSAStack->getParentDirective() != OMPD_unknown)) {
2250     auto &&Info = DSAStack->isLoopControlVariable(D);
2251     if (Info.first ||
2252         (VD && VD->hasLocalStorage() &&
2253          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2254         (VD && DSAStack->isForceVarCapturing()))
2255       return VD ? VD : Info.second;
2256     DSAStackTy::DSAVarData DVarTop =
2257         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2258     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2259         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2260       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2261     // Threadprivate variables must not be captured.
2262     if (isOpenMPThreadPrivate(DVarTop.CKind))
2263       return nullptr;
2264     // The variable is not private or it is the variable in the directive with
2265     // default(none) clause and not used in any clause.
2266     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2267         D,
2268         [](OpenMPClauseKind C, bool AppliedToPointee) {
2269           return isOpenMPPrivate(C) && !AppliedToPointee;
2270         },
2271         [](OpenMPDirectiveKind) { return true; },
2272         DSAStack->isClauseParsingMode());
2273     // Global shared must not be captured.
2274     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2275         ((DSAStack->getDefaultDSA() != DSA_none &&
2276           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2277          DVarTop.CKind == OMPC_shared))
2278       return nullptr;
2279     if (DVarPrivate.CKind != OMPC_unknown ||
2280         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2281                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2282       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2283   }
2284   return nullptr;
2285 }
2286 
2287 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2288                                         unsigned Level) const {
2289   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2290 }
2291 
2292 void Sema::startOpenMPLoop() {
2293   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2294   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2295     DSAStack->loopInit();
2296 }
2297 
2298 void Sema::startOpenMPCXXRangeFor() {
2299   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2300   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2301     DSAStack->resetPossibleLoopCounter();
2302     DSAStack->loopStart();
2303   }
2304 }
2305 
2306 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2307                                            unsigned CapLevel) const {
2308   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2309   if (DSAStack->hasExplicitDirective(
2310           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2311           Level)) {
2312     bool IsTriviallyCopyable =
2313         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2314         !D->getType()
2315              .getNonReferenceType()
2316              .getCanonicalType()
2317              ->getAsCXXRecordDecl();
2318     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2319     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2320     getOpenMPCaptureRegions(CaptureRegions, DKind);
2321     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2322         (IsTriviallyCopyable ||
2323          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2324       if (DSAStack->hasExplicitDSA(
2325               D,
2326               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2327               Level, /*NotLastprivate=*/true))
2328         return OMPC_firstprivate;
2329       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2330       if (DVar.CKind != OMPC_shared &&
2331           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2332         DSAStack->addImplicitTaskFirstprivate(Level, D);
2333         return OMPC_firstprivate;
2334       }
2335     }
2336   }
2337   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2338     if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2339       DSAStack->resetPossibleLoopCounter(D);
2340       DSAStack->loopStart();
2341       return OMPC_private;
2342     }
2343     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2344          DSAStack->isLoopControlVariable(D).first) &&
2345         !DSAStack->hasExplicitDSA(
2346             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2347             Level) &&
2348         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2349       return OMPC_private;
2350   }
2351   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2352     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2353         DSAStack->isForceVarCapturing() &&
2354         !DSAStack->hasExplicitDSA(
2355             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2356             Level))
2357       return OMPC_private;
2358   }
2359   // User-defined allocators are private since they must be defined in the
2360   // context of target region.
2361   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2362       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2363           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2364           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2365     return OMPC_private;
2366   return (DSAStack->hasExplicitDSA(
2367               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2368               Level) ||
2369           (DSAStack->isClauseParsingMode() &&
2370            DSAStack->getClauseParsingMode() == OMPC_private) ||
2371           // Consider taskgroup reduction descriptor variable a private
2372           // to avoid possible capture in the region.
2373           (DSAStack->hasExplicitDirective(
2374                [](OpenMPDirectiveKind K) {
2375                  return K == OMPD_taskgroup ||
2376                         ((isOpenMPParallelDirective(K) ||
2377                           isOpenMPWorksharingDirective(K)) &&
2378                          !isOpenMPSimdDirective(K));
2379                },
2380                Level) &&
2381            DSAStack->isTaskgroupReductionRef(D, Level)))
2382              ? OMPC_private
2383              : OMPC_unknown;
2384 }
2385 
2386 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2387                                 unsigned Level) {
2388   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2389   D = getCanonicalDecl(D);
2390   OpenMPClauseKind OMPC = OMPC_unknown;
2391   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2392     const unsigned NewLevel = I - 1;
2393     if (DSAStack->hasExplicitDSA(
2394             D,
2395             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2396               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2397                 OMPC = K;
2398                 return true;
2399               }
2400               return false;
2401             },
2402             NewLevel))
2403       break;
2404     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2405             D, NewLevel,
2406             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2407                OpenMPClauseKind) { return true; })) {
2408       OMPC = OMPC_map;
2409       break;
2410     }
2411     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2412                                        NewLevel)) {
2413       OMPC = OMPC_map;
2414       if (DSAStack->mustBeFirstprivateAtLevel(
2415               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2416         OMPC = OMPC_firstprivate;
2417       break;
2418     }
2419   }
2420   if (OMPC != OMPC_unknown)
2421     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2422 }
2423 
2424 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2425                                       unsigned CaptureLevel) const {
2426   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2427   // Return true if the current level is no longer enclosed in a target region.
2428 
2429   SmallVector<OpenMPDirectiveKind, 4> Regions;
2430   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2431   const auto *VD = dyn_cast<VarDecl>(D);
2432   return VD && !VD->hasLocalStorage() &&
2433          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2434                                         Level) &&
2435          Regions[CaptureLevel] != OMPD_task;
2436 }
2437 
2438 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2439                                       unsigned CaptureLevel) const {
2440   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2441   // Return true if the current level is no longer enclosed in a target region.
2442 
2443   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2444     if (!VD->hasLocalStorage()) {
2445       if (isInOpenMPTargetExecutionDirective())
2446         return true;
2447       DSAStackTy::DSAVarData TopDVar =
2448           DSAStack->getTopDSA(D, /*FromParent=*/false);
2449       unsigned NumLevels =
2450           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2451       if (Level == 0)
2452         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2453       do {
2454         --Level;
2455         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2456         if (DVar.CKind != OMPC_shared)
2457           return true;
2458       } while (Level > 0);
2459     }
2460   }
2461   return true;
2462 }
2463 
2464 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2465 
2466 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2467                                           OMPTraitInfo &TI) {
2468   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2469 }
2470 
2471 void Sema::ActOnOpenMPEndDeclareVariant() {
2472   assert(isInOpenMPDeclareVariantScope() &&
2473          "Not in OpenMP declare variant scope!");
2474 
2475   OMPDeclareVariantScopes.pop_back();
2476 }
2477 
2478 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2479                                          const FunctionDecl *Callee,
2480                                          SourceLocation Loc) {
2481   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2482   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2483       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2484   // Ignore host functions during device analyzis.
2485   if (LangOpts.OpenMPIsDevice &&
2486       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2487     return;
2488   // Ignore nohost functions during host analyzis.
2489   if (!LangOpts.OpenMPIsDevice && DevTy &&
2490       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2491     return;
2492   const FunctionDecl *FD = Callee->getMostRecentDecl();
2493   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2494   if (LangOpts.OpenMPIsDevice && DevTy &&
2495       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2496     // Diagnose host function called during device codegen.
2497     StringRef HostDevTy =
2498         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2499     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2500     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2501          diag::note_omp_marked_device_type_here)
2502         << HostDevTy;
2503     return;
2504   }
2505   if (!LangOpts.OpenMPIsDevice && DevTy &&
2506       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2507     // Diagnose nohost function called during host codegen.
2508     StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2509         OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2510     Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2511     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2512          diag::note_omp_marked_device_type_here)
2513         << NoHostDevTy;
2514   }
2515 }
2516 
2517 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2518                                const DeclarationNameInfo &DirName,
2519                                Scope *CurScope, SourceLocation Loc) {
2520   DSAStack->push(DKind, DirName, CurScope, Loc);
2521   PushExpressionEvaluationContext(
2522       ExpressionEvaluationContext::PotentiallyEvaluated);
2523 }
2524 
2525 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2526   DSAStack->setClauseParsingMode(K);
2527 }
2528 
2529 void Sema::EndOpenMPClause() {
2530   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2531   CleanupVarDeclMarking();
2532 }
2533 
2534 static std::pair<ValueDecl *, bool>
2535 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2536                SourceRange &ERange, bool AllowArraySection = false);
2537 
2538 /// Check consistency of the reduction clauses.
2539 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2540                                   ArrayRef<OMPClause *> Clauses) {
2541   bool InscanFound = false;
2542   SourceLocation InscanLoc;
2543   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2544   // A reduction clause without the inscan reduction-modifier may not appear on
2545   // a construct on which a reduction clause with the inscan reduction-modifier
2546   // appears.
2547   for (OMPClause *C : Clauses) {
2548     if (C->getClauseKind() != OMPC_reduction)
2549       continue;
2550     auto *RC = cast<OMPReductionClause>(C);
2551     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2552       InscanFound = true;
2553       InscanLoc = RC->getModifierLoc();
2554       continue;
2555     }
2556     if (RC->getModifier() == OMPC_REDUCTION_task) {
2557       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2558       // A reduction clause with the task reduction-modifier may only appear on
2559       // a parallel construct, a worksharing construct or a combined or
2560       // composite construct for which any of the aforementioned constructs is a
2561       // constituent construct and simd or loop are not constituent constructs.
2562       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2563       if (!(isOpenMPParallelDirective(CurDir) ||
2564             isOpenMPWorksharingDirective(CurDir)) ||
2565           isOpenMPSimdDirective(CurDir))
2566         S.Diag(RC->getModifierLoc(),
2567                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2568       continue;
2569     }
2570   }
2571   if (InscanFound) {
2572     for (OMPClause *C : Clauses) {
2573       if (C->getClauseKind() != OMPC_reduction)
2574         continue;
2575       auto *RC = cast<OMPReductionClause>(C);
2576       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2577         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2578                    ? RC->getBeginLoc()
2579                    : RC->getModifierLoc(),
2580                diag::err_omp_inscan_reduction_expected);
2581         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2582         continue;
2583       }
2584       for (Expr *Ref : RC->varlists()) {
2585         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2586         SourceLocation ELoc;
2587         SourceRange ERange;
2588         Expr *SimpleRefExpr = Ref;
2589         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2590                                   /*AllowArraySection=*/true);
2591         ValueDecl *D = Res.first;
2592         if (!D)
2593           continue;
2594         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2595           S.Diag(Ref->getExprLoc(),
2596                  diag::err_omp_reduction_not_inclusive_exclusive)
2597               << Ref->getSourceRange();
2598         }
2599       }
2600     }
2601   }
2602 }
2603 
2604 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2605                                  ArrayRef<OMPClause *> Clauses);
2606 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2607                                  bool WithInit);
2608 
2609 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2610                               const ValueDecl *D,
2611                               const DSAStackTy::DSAVarData &DVar,
2612                               bool IsLoopIterVar = false);
2613 
2614 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2615   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2616   //  A variable of class type (or array thereof) that appears in a lastprivate
2617   //  clause requires an accessible, unambiguous default constructor for the
2618   //  class type, unless the list item is also specified in a firstprivate
2619   //  clause.
2620   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2621     for (OMPClause *C : D->clauses()) {
2622       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2623         SmallVector<Expr *, 8> PrivateCopies;
2624         for (Expr *DE : Clause->varlists()) {
2625           if (DE->isValueDependent() || DE->isTypeDependent()) {
2626             PrivateCopies.push_back(nullptr);
2627             continue;
2628           }
2629           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2630           auto *VD = cast<VarDecl>(DRE->getDecl());
2631           QualType Type = VD->getType().getNonReferenceType();
2632           const DSAStackTy::DSAVarData DVar =
2633               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2634           if (DVar.CKind == OMPC_lastprivate) {
2635             // Generate helper private variable and initialize it with the
2636             // default value. The address of the original variable is replaced
2637             // by the address of the new private variable in CodeGen. This new
2638             // variable is not added to IdResolver, so the code in the OpenMP
2639             // region uses original variable for proper diagnostics.
2640             VarDecl *VDPrivate = buildVarDecl(
2641                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2642                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2643             ActOnUninitializedDecl(VDPrivate);
2644             if (VDPrivate->isInvalidDecl()) {
2645               PrivateCopies.push_back(nullptr);
2646               continue;
2647             }
2648             PrivateCopies.push_back(buildDeclRefExpr(
2649                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2650           } else {
2651             // The variable is also a firstprivate, so initialization sequence
2652             // for private copy is generated already.
2653             PrivateCopies.push_back(nullptr);
2654           }
2655         }
2656         Clause->setPrivateCopies(PrivateCopies);
2657         continue;
2658       }
2659       // Finalize nontemporal clause by handling private copies, if any.
2660       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2661         SmallVector<Expr *, 8> PrivateRefs;
2662         for (Expr *RefExpr : Clause->varlists()) {
2663           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2664           SourceLocation ELoc;
2665           SourceRange ERange;
2666           Expr *SimpleRefExpr = RefExpr;
2667           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2668           if (Res.second)
2669             // It will be analyzed later.
2670             PrivateRefs.push_back(RefExpr);
2671           ValueDecl *D = Res.first;
2672           if (!D)
2673             continue;
2674 
2675           const DSAStackTy::DSAVarData DVar =
2676               DSAStack->getTopDSA(D, /*FromParent=*/false);
2677           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2678                                                  : SimpleRefExpr);
2679         }
2680         Clause->setPrivateRefs(PrivateRefs);
2681         continue;
2682       }
2683       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2684         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2685           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2686           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2687           if (!DRE)
2688             continue;
2689           ValueDecl *VD = DRE->getDecl();
2690           if (!VD || !isa<VarDecl>(VD))
2691             continue;
2692           DSAStackTy::DSAVarData DVar =
2693               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2694           // OpenMP [2.12.5, target Construct]
2695           // Memory allocators that appear in a uses_allocators clause cannot
2696           // appear in other data-sharing attribute clauses or data-mapping
2697           // attribute clauses in the same construct.
2698           Expr *MapExpr = nullptr;
2699           if (DVar.RefExpr ||
2700               DSAStack->checkMappableExprComponentListsForDecl(
2701                   VD, /*CurrentRegionOnly=*/true,
2702                   [VD, &MapExpr](
2703                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2704                           MapExprComponents,
2705                       OpenMPClauseKind C) {
2706                     auto MI = MapExprComponents.rbegin();
2707                     auto ME = MapExprComponents.rend();
2708                     if (MI != ME &&
2709                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2710                             VD->getCanonicalDecl()) {
2711                       MapExpr = MI->getAssociatedExpression();
2712                       return true;
2713                     }
2714                     return false;
2715                   })) {
2716             Diag(D.Allocator->getExprLoc(),
2717                  diag::err_omp_allocator_used_in_clauses)
2718                 << D.Allocator->getSourceRange();
2719             if (DVar.RefExpr)
2720               reportOriginalDsa(*this, DSAStack, VD, DVar);
2721             else
2722               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2723                   << MapExpr->getSourceRange();
2724           }
2725         }
2726         continue;
2727       }
2728     }
2729     // Check allocate clauses.
2730     if (!CurContext->isDependentContext())
2731       checkAllocateClauses(*this, DSAStack, D->clauses());
2732     checkReductionClauses(*this, DSAStack, D->clauses());
2733   }
2734 
2735   DSAStack->pop();
2736   DiscardCleanupsInEvaluationContext();
2737   PopExpressionEvaluationContext();
2738 }
2739 
2740 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2741                                      Expr *NumIterations, Sema &SemaRef,
2742                                      Scope *S, DSAStackTy *Stack);
2743 
2744 namespace {
2745 
2746 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2747 private:
2748   Sema &SemaRef;
2749 
2750 public:
2751   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2752   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2753     NamedDecl *ND = Candidate.getCorrectionDecl();
2754     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2755       return VD->hasGlobalStorage() &&
2756              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2757                                    SemaRef.getCurScope());
2758     }
2759     return false;
2760   }
2761 
2762   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2763     return std::make_unique<VarDeclFilterCCC>(*this);
2764   }
2765 };
2766 
2767 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2768 private:
2769   Sema &SemaRef;
2770 
2771 public:
2772   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2773   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2774     NamedDecl *ND = Candidate.getCorrectionDecl();
2775     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2776                isa<FunctionDecl>(ND))) {
2777       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2778                                    SemaRef.getCurScope());
2779     }
2780     return false;
2781   }
2782 
2783   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2784     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2785   }
2786 };
2787 
2788 } // namespace
2789 
2790 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2791                                          CXXScopeSpec &ScopeSpec,
2792                                          const DeclarationNameInfo &Id,
2793                                          OpenMPDirectiveKind Kind) {
2794   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2795   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2796 
2797   if (Lookup.isAmbiguous())
2798     return ExprError();
2799 
2800   VarDecl *VD;
2801   if (!Lookup.isSingleResult()) {
2802     VarDeclFilterCCC CCC(*this);
2803     if (TypoCorrection Corrected =
2804             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2805                         CTK_ErrorRecovery)) {
2806       diagnoseTypo(Corrected,
2807                    PDiag(Lookup.empty()
2808                              ? diag::err_undeclared_var_use_suggest
2809                              : diag::err_omp_expected_var_arg_suggest)
2810                        << Id.getName());
2811       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2812     } else {
2813       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2814                                        : diag::err_omp_expected_var_arg)
2815           << Id.getName();
2816       return ExprError();
2817     }
2818   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2819     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2820     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2821     return ExprError();
2822   }
2823   Lookup.suppressDiagnostics();
2824 
2825   // OpenMP [2.9.2, Syntax, C/C++]
2826   //   Variables must be file-scope, namespace-scope, or static block-scope.
2827   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2828     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2829         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2830     bool IsDecl =
2831         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2832     Diag(VD->getLocation(),
2833          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2834         << VD;
2835     return ExprError();
2836   }
2837 
2838   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2839   NamedDecl *ND = CanonicalVD;
2840   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2841   //   A threadprivate directive for file-scope variables must appear outside
2842   //   any definition or declaration.
2843   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2844       !getCurLexicalContext()->isTranslationUnit()) {
2845     Diag(Id.getLoc(), diag::err_omp_var_scope)
2846         << getOpenMPDirectiveName(Kind) << VD;
2847     bool IsDecl =
2848         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2849     Diag(VD->getLocation(),
2850          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2851         << VD;
2852     return ExprError();
2853   }
2854   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2855   //   A threadprivate directive for static class member variables must appear
2856   //   in the class definition, in the same scope in which the member
2857   //   variables are declared.
2858   if (CanonicalVD->isStaticDataMember() &&
2859       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2860     Diag(Id.getLoc(), diag::err_omp_var_scope)
2861         << getOpenMPDirectiveName(Kind) << VD;
2862     bool IsDecl =
2863         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2864     Diag(VD->getLocation(),
2865          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2866         << VD;
2867     return ExprError();
2868   }
2869   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2870   //   A threadprivate directive for namespace-scope variables must appear
2871   //   outside any definition or declaration other than the namespace
2872   //   definition itself.
2873   if (CanonicalVD->getDeclContext()->isNamespace() &&
2874       (!getCurLexicalContext()->isFileContext() ||
2875        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2876     Diag(Id.getLoc(), diag::err_omp_var_scope)
2877         << getOpenMPDirectiveName(Kind) << VD;
2878     bool IsDecl =
2879         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2880     Diag(VD->getLocation(),
2881          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2882         << VD;
2883     return ExprError();
2884   }
2885   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2886   //   A threadprivate directive for static block-scope variables must appear
2887   //   in the scope of the variable and not in a nested scope.
2888   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2889       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2890     Diag(Id.getLoc(), diag::err_omp_var_scope)
2891         << getOpenMPDirectiveName(Kind) << VD;
2892     bool IsDecl =
2893         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2894     Diag(VD->getLocation(),
2895          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2896         << VD;
2897     return ExprError();
2898   }
2899 
2900   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2901   //   A threadprivate directive must lexically precede all references to any
2902   //   of the variables in its list.
2903   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2904       !DSAStack->isThreadPrivate(VD)) {
2905     Diag(Id.getLoc(), diag::err_omp_var_used)
2906         << getOpenMPDirectiveName(Kind) << VD;
2907     return ExprError();
2908   }
2909 
2910   QualType ExprType = VD->getType().getNonReferenceType();
2911   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2912                              SourceLocation(), VD,
2913                              /*RefersToEnclosingVariableOrCapture=*/false,
2914                              Id.getLoc(), ExprType, VK_LValue);
2915 }
2916 
2917 Sema::DeclGroupPtrTy
2918 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2919                                         ArrayRef<Expr *> VarList) {
2920   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2921     CurContext->addDecl(D);
2922     return DeclGroupPtrTy::make(DeclGroupRef(D));
2923   }
2924   return nullptr;
2925 }
2926 
2927 namespace {
2928 class LocalVarRefChecker final
2929     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2930   Sema &SemaRef;
2931 
2932 public:
2933   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2934     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2935       if (VD->hasLocalStorage()) {
2936         SemaRef.Diag(E->getBeginLoc(),
2937                      diag::err_omp_local_var_in_threadprivate_init)
2938             << E->getSourceRange();
2939         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2940             << VD << VD->getSourceRange();
2941         return true;
2942       }
2943     }
2944     return false;
2945   }
2946   bool VisitStmt(const Stmt *S) {
2947     for (const Stmt *Child : S->children()) {
2948       if (Child && Visit(Child))
2949         return true;
2950     }
2951     return false;
2952   }
2953   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2954 };
2955 } // namespace
2956 
2957 OMPThreadPrivateDecl *
2958 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2959   SmallVector<Expr *, 8> Vars;
2960   for (Expr *RefExpr : VarList) {
2961     auto *DE = cast<DeclRefExpr>(RefExpr);
2962     auto *VD = cast<VarDecl>(DE->getDecl());
2963     SourceLocation ILoc = DE->getExprLoc();
2964 
2965     // Mark variable as used.
2966     VD->setReferenced();
2967     VD->markUsed(Context);
2968 
2969     QualType QType = VD->getType();
2970     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2971       // It will be analyzed later.
2972       Vars.push_back(DE);
2973       continue;
2974     }
2975 
2976     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2977     //   A threadprivate variable must not have an incomplete type.
2978     if (RequireCompleteType(ILoc, VD->getType(),
2979                             diag::err_omp_threadprivate_incomplete_type)) {
2980       continue;
2981     }
2982 
2983     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2984     //   A threadprivate variable must not have a reference type.
2985     if (VD->getType()->isReferenceType()) {
2986       Diag(ILoc, diag::err_omp_ref_type_arg)
2987           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2988       bool IsDecl =
2989           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2990       Diag(VD->getLocation(),
2991            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2992           << VD;
2993       continue;
2994     }
2995 
2996     // Check if this is a TLS variable. If TLS is not being supported, produce
2997     // the corresponding diagnostic.
2998     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2999          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
3000            getLangOpts().OpenMPUseTLS &&
3001            getASTContext().getTargetInfo().isTLSSupported())) ||
3002         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3003          !VD->isLocalVarDecl())) {
3004       Diag(ILoc, diag::err_omp_var_thread_local)
3005           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3006       bool IsDecl =
3007           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3008       Diag(VD->getLocation(),
3009            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3010           << VD;
3011       continue;
3012     }
3013 
3014     // Check if initial value of threadprivate variable reference variable with
3015     // local storage (it is not supported by runtime).
3016     if (const Expr *Init = VD->getAnyInitializer()) {
3017       LocalVarRefChecker Checker(*this);
3018       if (Checker.Visit(Init))
3019         continue;
3020     }
3021 
3022     Vars.push_back(RefExpr);
3023     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3024     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3025         Context, SourceRange(Loc, Loc)));
3026     if (ASTMutationListener *ML = Context.getASTMutationListener())
3027       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3028   }
3029   OMPThreadPrivateDecl *D = nullptr;
3030   if (!Vars.empty()) {
3031     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3032                                      Vars);
3033     D->setAccess(AS_public);
3034   }
3035   return D;
3036 }
3037 
3038 static OMPAllocateDeclAttr::AllocatorTypeTy
3039 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3040   if (!Allocator)
3041     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3042   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3043       Allocator->isInstantiationDependent() ||
3044       Allocator->containsUnexpandedParameterPack())
3045     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3046   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3047   const Expr *AE = Allocator->IgnoreParenImpCasts();
3048   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3049     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3050     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3051     llvm::FoldingSetNodeID AEId, DAEId;
3052     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3053     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3054     if (AEId == DAEId) {
3055       AllocatorKindRes = AllocatorKind;
3056       break;
3057     }
3058   }
3059   return AllocatorKindRes;
3060 }
3061 
3062 static bool checkPreviousOMPAllocateAttribute(
3063     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3064     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3065   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3066     return false;
3067   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3068   Expr *PrevAllocator = A->getAllocator();
3069   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3070       getAllocatorKind(S, Stack, PrevAllocator);
3071   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3072   if (AllocatorsMatch &&
3073       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3074       Allocator && PrevAllocator) {
3075     const Expr *AE = Allocator->IgnoreParenImpCasts();
3076     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3077     llvm::FoldingSetNodeID AEId, PAEId;
3078     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3079     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3080     AllocatorsMatch = AEId == PAEId;
3081   }
3082   if (!AllocatorsMatch) {
3083     SmallString<256> AllocatorBuffer;
3084     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3085     if (Allocator)
3086       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3087     SmallString<256> PrevAllocatorBuffer;
3088     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3089     if (PrevAllocator)
3090       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3091                                  S.getPrintingPolicy());
3092 
3093     SourceLocation AllocatorLoc =
3094         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3095     SourceRange AllocatorRange =
3096         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3097     SourceLocation PrevAllocatorLoc =
3098         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3099     SourceRange PrevAllocatorRange =
3100         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3101     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3102         << (Allocator ? 1 : 0) << AllocatorStream.str()
3103         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3104         << AllocatorRange;
3105     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3106         << PrevAllocatorRange;
3107     return true;
3108   }
3109   return false;
3110 }
3111 
3112 static void
3113 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3114                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3115                           Expr *Allocator, Expr *Alignment, SourceRange SR) {
3116   if (VD->hasAttr<OMPAllocateDeclAttr>())
3117     return;
3118   if (Alignment &&
3119       (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3120        Alignment->isInstantiationDependent() ||
3121        Alignment->containsUnexpandedParameterPack()))
3122     // Apply later when we have a usable value.
3123     return;
3124   if (Allocator &&
3125       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3126        Allocator->isInstantiationDependent() ||
3127        Allocator->containsUnexpandedParameterPack()))
3128     return;
3129   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3130                                                 Allocator, Alignment, SR);
3131   VD->addAttr(A);
3132   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3133     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3134 }
3135 
3136 Sema::DeclGroupPtrTy
3137 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
3138                                    ArrayRef<OMPClause *> Clauses,
3139                                    DeclContext *Owner) {
3140   assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3141   Expr *Alignment = nullptr;
3142   Expr *Allocator = nullptr;
3143   if (Clauses.empty()) {
3144     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3145     // allocate directives that appear in a target region must specify an
3146     // allocator clause unless a requires directive with the dynamic_allocators
3147     // clause is present in the same compilation unit.
3148     if (LangOpts.OpenMPIsDevice &&
3149         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3150       targetDiag(Loc, diag::err_expected_allocator_clause);
3151   } else {
3152     for (const OMPClause *C : Clauses)
3153       if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3154         Allocator = AC->getAllocator();
3155       else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3156         Alignment = AC->getAlignment();
3157       else
3158         llvm_unreachable("Unexpected clause on allocate directive");
3159   }
3160   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3161       getAllocatorKind(*this, DSAStack, Allocator);
3162   SmallVector<Expr *, 8> Vars;
3163   for (Expr *RefExpr : VarList) {
3164     auto *DE = cast<DeclRefExpr>(RefExpr);
3165     auto *VD = cast<VarDecl>(DE->getDecl());
3166 
3167     // Check if this is a TLS variable or global register.
3168     if (VD->getTLSKind() != VarDecl::TLS_None ||
3169         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3170         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3171          !VD->isLocalVarDecl()))
3172       continue;
3173 
3174     // If the used several times in the allocate directive, the same allocator
3175     // must be used.
3176     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3177                                           AllocatorKind, Allocator))
3178       continue;
3179 
3180     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3181     // If a list item has a static storage type, the allocator expression in the
3182     // allocator clause must be a constant expression that evaluates to one of
3183     // the predefined memory allocator values.
3184     if (Allocator && VD->hasGlobalStorage()) {
3185       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3186         Diag(Allocator->getExprLoc(),
3187              diag::err_omp_expected_predefined_allocator)
3188             << Allocator->getSourceRange();
3189         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3190                       VarDecl::DeclarationOnly;
3191         Diag(VD->getLocation(),
3192              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3193             << VD;
3194         continue;
3195       }
3196     }
3197 
3198     Vars.push_back(RefExpr);
3199     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
3200                               DE->getSourceRange());
3201   }
3202   if (Vars.empty())
3203     return nullptr;
3204   if (!Owner)
3205     Owner = getCurLexicalContext();
3206   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3207   D->setAccess(AS_public);
3208   Owner->addDecl(D);
3209   return DeclGroupPtrTy::make(DeclGroupRef(D));
3210 }
3211 
3212 Sema::DeclGroupPtrTy
3213 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3214                                    ArrayRef<OMPClause *> ClauseList) {
3215   OMPRequiresDecl *D = nullptr;
3216   if (!CurContext->isFileContext()) {
3217     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3218   } else {
3219     D = CheckOMPRequiresDecl(Loc, ClauseList);
3220     if (D) {
3221       CurContext->addDecl(D);
3222       DSAStack->addRequiresDecl(D);
3223     }
3224   }
3225   return DeclGroupPtrTy::make(DeclGroupRef(D));
3226 }
3227 
3228 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3229                                        OpenMPDirectiveKind DKind,
3230                                        ArrayRef<std::string> Assumptions,
3231                                        bool SkippedClauses) {
3232   if (!SkippedClauses && Assumptions.empty())
3233     Diag(Loc, diag::err_omp_no_clause_for_directive)
3234         << llvm::omp::getAllAssumeClauseOptions()
3235         << llvm::omp::getOpenMPDirectiveName(DKind);
3236 
3237   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3238   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3239     OMPAssumeScoped.push_back(AA);
3240     return;
3241   }
3242 
3243   // Global assumes without assumption clauses are ignored.
3244   if (Assumptions.empty())
3245     return;
3246 
3247   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3248          "Unexpected omp assumption directive!");
3249   OMPAssumeGlobal.push_back(AA);
3250 
3251   // The OMPAssumeGlobal scope above will take care of new declarations but
3252   // we also want to apply the assumption to existing ones, e.g., to
3253   // declarations in included headers. To this end, we traverse all existing
3254   // declaration contexts and annotate function declarations here.
3255   SmallVector<DeclContext *, 8> DeclContexts;
3256   auto *Ctx = CurContext;
3257   while (Ctx->getLexicalParent())
3258     Ctx = Ctx->getLexicalParent();
3259   DeclContexts.push_back(Ctx);
3260   while (!DeclContexts.empty()) {
3261     DeclContext *DC = DeclContexts.pop_back_val();
3262     for (auto *SubDC : DC->decls()) {
3263       if (SubDC->isInvalidDecl())
3264         continue;
3265       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3266         DeclContexts.push_back(CTD->getTemplatedDecl());
3267         for (auto *S : CTD->specializations())
3268           DeclContexts.push_back(S);
3269         continue;
3270       }
3271       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3272         DeclContexts.push_back(DC);
3273       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3274         F->addAttr(AA);
3275         continue;
3276       }
3277     }
3278   }
3279 }
3280 
3281 void Sema::ActOnOpenMPEndAssumesDirective() {
3282   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3283   OMPAssumeScoped.pop_back();
3284 }
3285 
3286 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3287                                             ArrayRef<OMPClause *> ClauseList) {
3288   /// For target specific clauses, the requires directive cannot be
3289   /// specified after the handling of any of the target regions in the
3290   /// current compilation unit.
3291   ArrayRef<SourceLocation> TargetLocations =
3292       DSAStack->getEncounteredTargetLocs();
3293   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3294   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3295     for (const OMPClause *CNew : ClauseList) {
3296       // Check if any of the requires clauses affect target regions.
3297       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3298           isa<OMPUnifiedAddressClause>(CNew) ||
3299           isa<OMPReverseOffloadClause>(CNew) ||
3300           isa<OMPDynamicAllocatorsClause>(CNew)) {
3301         Diag(Loc, diag::err_omp_directive_before_requires)
3302             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3303         for (SourceLocation TargetLoc : TargetLocations) {
3304           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3305               << "target";
3306         }
3307       } else if (!AtomicLoc.isInvalid() &&
3308                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3309         Diag(Loc, diag::err_omp_directive_before_requires)
3310             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3311         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3312             << "atomic";
3313       }
3314     }
3315   }
3316 
3317   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3318     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3319                                    ClauseList);
3320   return nullptr;
3321 }
3322 
3323 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3324                               const ValueDecl *D,
3325                               const DSAStackTy::DSAVarData &DVar,
3326                               bool IsLoopIterVar) {
3327   if (DVar.RefExpr) {
3328     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3329         << getOpenMPClauseName(DVar.CKind);
3330     return;
3331   }
3332   enum {
3333     PDSA_StaticMemberShared,
3334     PDSA_StaticLocalVarShared,
3335     PDSA_LoopIterVarPrivate,
3336     PDSA_LoopIterVarLinear,
3337     PDSA_LoopIterVarLastprivate,
3338     PDSA_ConstVarShared,
3339     PDSA_GlobalVarShared,
3340     PDSA_TaskVarFirstprivate,
3341     PDSA_LocalVarPrivate,
3342     PDSA_Implicit
3343   } Reason = PDSA_Implicit;
3344   bool ReportHint = false;
3345   auto ReportLoc = D->getLocation();
3346   auto *VD = dyn_cast<VarDecl>(D);
3347   if (IsLoopIterVar) {
3348     if (DVar.CKind == OMPC_private)
3349       Reason = PDSA_LoopIterVarPrivate;
3350     else if (DVar.CKind == OMPC_lastprivate)
3351       Reason = PDSA_LoopIterVarLastprivate;
3352     else
3353       Reason = PDSA_LoopIterVarLinear;
3354   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3355              DVar.CKind == OMPC_firstprivate) {
3356     Reason = PDSA_TaskVarFirstprivate;
3357     ReportLoc = DVar.ImplicitDSALoc;
3358   } else if (VD && VD->isStaticLocal())
3359     Reason = PDSA_StaticLocalVarShared;
3360   else if (VD && VD->isStaticDataMember())
3361     Reason = PDSA_StaticMemberShared;
3362   else if (VD && VD->isFileVarDecl())
3363     Reason = PDSA_GlobalVarShared;
3364   else if (D->getType().isConstant(SemaRef.getASTContext()))
3365     Reason = PDSA_ConstVarShared;
3366   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3367     ReportHint = true;
3368     Reason = PDSA_LocalVarPrivate;
3369   }
3370   if (Reason != PDSA_Implicit) {
3371     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3372         << Reason << ReportHint
3373         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3374   } else if (DVar.ImplicitDSALoc.isValid()) {
3375     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3376         << getOpenMPClauseName(DVar.CKind);
3377   }
3378 }
3379 
3380 static OpenMPMapClauseKind
3381 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3382                              bool IsAggregateOrDeclareTarget) {
3383   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3384   switch (M) {
3385   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3386     Kind = OMPC_MAP_alloc;
3387     break;
3388   case OMPC_DEFAULTMAP_MODIFIER_to:
3389     Kind = OMPC_MAP_to;
3390     break;
3391   case OMPC_DEFAULTMAP_MODIFIER_from:
3392     Kind = OMPC_MAP_from;
3393     break;
3394   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3395     Kind = OMPC_MAP_tofrom;
3396     break;
3397   case OMPC_DEFAULTMAP_MODIFIER_present:
3398     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3399     // If implicit-behavior is present, each variable referenced in the
3400     // construct in the category specified by variable-category is treated as if
3401     // it had been listed in a map clause with the map-type of alloc and
3402     // map-type-modifier of present.
3403     Kind = OMPC_MAP_alloc;
3404     break;
3405   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3406   case OMPC_DEFAULTMAP_MODIFIER_last:
3407     llvm_unreachable("Unexpected defaultmap implicit behavior");
3408   case OMPC_DEFAULTMAP_MODIFIER_none:
3409   case OMPC_DEFAULTMAP_MODIFIER_default:
3410   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3411     // IsAggregateOrDeclareTarget could be true if:
3412     // 1. the implicit behavior for aggregate is tofrom
3413     // 2. it's a declare target link
3414     if (IsAggregateOrDeclareTarget) {
3415       Kind = OMPC_MAP_tofrom;
3416       break;
3417     }
3418     llvm_unreachable("Unexpected defaultmap implicit behavior");
3419   }
3420   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3421   return Kind;
3422 }
3423 
3424 namespace {
3425 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3426   DSAStackTy *Stack;
3427   Sema &SemaRef;
3428   bool ErrorFound = false;
3429   bool TryCaptureCXXThisMembers = false;
3430   CapturedStmt *CS = nullptr;
3431   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3432   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3433   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3434   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3435       ImplicitMapModifier[DefaultmapKindNum];
3436   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3437   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3438 
3439   void VisitSubCaptures(OMPExecutableDirective *S) {
3440     // Check implicitly captured variables.
3441     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3442       return;
3443     if (S->getDirectiveKind() == OMPD_atomic ||
3444         S->getDirectiveKind() == OMPD_critical ||
3445         S->getDirectiveKind() == OMPD_section ||
3446         S->getDirectiveKind() == OMPD_master ||
3447         S->getDirectiveKind() == OMPD_masked ||
3448         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3449       Visit(S->getAssociatedStmt());
3450       return;
3451     }
3452     visitSubCaptures(S->getInnermostCapturedStmt());
3453     // Try to capture inner this->member references to generate correct mappings
3454     // and diagnostics.
3455     if (TryCaptureCXXThisMembers ||
3456         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3457          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3458                       [](const CapturedStmt::Capture &C) {
3459                         return C.capturesThis();
3460                       }))) {
3461       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3462       TryCaptureCXXThisMembers = true;
3463       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3464       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3465     }
3466     // In tasks firstprivates are not captured anymore, need to analyze them
3467     // explicitly.
3468     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3469         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3470       for (OMPClause *C : S->clauses())
3471         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3472           for (Expr *Ref : FC->varlists())
3473             Visit(Ref);
3474         }
3475     }
3476   }
3477 
3478 public:
3479   void VisitDeclRefExpr(DeclRefExpr *E) {
3480     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3481         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3482         E->isInstantiationDependent())
3483       return;
3484     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3485       // Check the datasharing rules for the expressions in the clauses.
3486       if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
3487                   !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
3488         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3489           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3490             Visit(CED->getInit());
3491             return;
3492           }
3493       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3494         // Do not analyze internal variables and do not enclose them into
3495         // implicit clauses.
3496         return;
3497       VD = VD->getCanonicalDecl();
3498       // Skip internally declared variables.
3499       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3500           !Stack->isImplicitTaskFirstprivate(VD))
3501         return;
3502       // Skip allocators in uses_allocators clauses.
3503       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3504         return;
3505 
3506       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3507       // Check if the variable has explicit DSA set and stop analysis if it so.
3508       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3509         return;
3510 
3511       // Skip internally declared static variables.
3512       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3513           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3514       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3515           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3516            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3517           !Stack->isImplicitTaskFirstprivate(VD))
3518         return;
3519 
3520       SourceLocation ELoc = E->getExprLoc();
3521       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3522       // The default(none) clause requires that each variable that is referenced
3523       // in the construct, and does not have a predetermined data-sharing
3524       // attribute, must have its data-sharing attribute explicitly determined
3525       // by being listed in a data-sharing attribute clause.
3526       if (DVar.CKind == OMPC_unknown &&
3527           (Stack->getDefaultDSA() == DSA_none ||
3528            Stack->getDefaultDSA() == DSA_firstprivate) &&
3529           isImplicitOrExplicitTaskingRegion(DKind) &&
3530           VarsWithInheritedDSA.count(VD) == 0) {
3531         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3532         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3533           DSAStackTy::DSAVarData DVar =
3534               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3535           InheritedDSA = DVar.CKind == OMPC_unknown;
3536         }
3537         if (InheritedDSA)
3538           VarsWithInheritedDSA[VD] = E;
3539         return;
3540       }
3541 
3542       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3543       // If implicit-behavior is none, each variable referenced in the
3544       // construct that does not have a predetermined data-sharing attribute
3545       // and does not appear in a to or link clause on a declare target
3546       // directive must be listed in a data-mapping attribute clause, a
3547       // data-haring attribute clause (including a data-sharing attribute
3548       // clause on a combined construct where target. is one of the
3549       // constituent constructs), or an is_device_ptr clause.
3550       OpenMPDefaultmapClauseKind ClauseKind =
3551           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3552       if (SemaRef.getLangOpts().OpenMP >= 50) {
3553         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3554                               OMPC_DEFAULTMAP_MODIFIER_none;
3555         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3556             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3557           // Only check for data-mapping attribute and is_device_ptr here
3558           // since we have already make sure that the declaration does not
3559           // have a data-sharing attribute above
3560           if (!Stack->checkMappableExprComponentListsForDecl(
3561                   VD, /*CurrentRegionOnly=*/true,
3562                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3563                            MapExprComponents,
3564                        OpenMPClauseKind) {
3565                     auto MI = MapExprComponents.rbegin();
3566                     auto ME = MapExprComponents.rend();
3567                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3568                   })) {
3569             VarsWithInheritedDSA[VD] = E;
3570             return;
3571           }
3572         }
3573       }
3574       if (SemaRef.getLangOpts().OpenMP > 50) {
3575         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3576                                  OMPC_DEFAULTMAP_MODIFIER_present;
3577         if (IsModifierPresent) {
3578           if (llvm::find(ImplicitMapModifier[ClauseKind],
3579                          OMPC_MAP_MODIFIER_present) ==
3580               std::end(ImplicitMapModifier[ClauseKind])) {
3581             ImplicitMapModifier[ClauseKind].push_back(
3582                 OMPC_MAP_MODIFIER_present);
3583           }
3584         }
3585       }
3586 
3587       if (isOpenMPTargetExecutionDirective(DKind) &&
3588           !Stack->isLoopControlVariable(VD).first) {
3589         if (!Stack->checkMappableExprComponentListsForDecl(
3590                 VD, /*CurrentRegionOnly=*/true,
3591                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3592                            StackComponents,
3593                        OpenMPClauseKind) {
3594                   if (SemaRef.LangOpts.OpenMP >= 50)
3595                     return !StackComponents.empty();
3596                   // Variable is used if it has been marked as an array, array
3597                   // section, array shaping or the variable iself.
3598                   return StackComponents.size() == 1 ||
3599                          std::all_of(
3600                              std::next(StackComponents.rbegin()),
3601                              StackComponents.rend(),
3602                              [](const OMPClauseMappableExprCommon::
3603                                     MappableComponent &MC) {
3604                                return MC.getAssociatedDeclaration() ==
3605                                           nullptr &&
3606                                       (isa<OMPArraySectionExpr>(
3607                                            MC.getAssociatedExpression()) ||
3608                                        isa<OMPArrayShapingExpr>(
3609                                            MC.getAssociatedExpression()) ||
3610                                        isa<ArraySubscriptExpr>(
3611                                            MC.getAssociatedExpression()));
3612                              });
3613                 })) {
3614           bool IsFirstprivate = false;
3615           // By default lambdas are captured as firstprivates.
3616           if (const auto *RD =
3617                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3618             IsFirstprivate = RD->isLambda();
3619           IsFirstprivate =
3620               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3621           if (IsFirstprivate) {
3622             ImplicitFirstprivate.emplace_back(E);
3623           } else {
3624             OpenMPDefaultmapClauseModifier M =
3625                 Stack->getDefaultmapModifier(ClauseKind);
3626             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3627                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3628             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3629           }
3630           return;
3631         }
3632       }
3633 
3634       // OpenMP [2.9.3.6, Restrictions, p.2]
3635       //  A list item that appears in a reduction clause of the innermost
3636       //  enclosing worksharing or parallel construct may not be accessed in an
3637       //  explicit task.
3638       DVar = Stack->hasInnermostDSA(
3639           VD,
3640           [](OpenMPClauseKind C, bool AppliedToPointee) {
3641             return C == OMPC_reduction && !AppliedToPointee;
3642           },
3643           [](OpenMPDirectiveKind K) {
3644             return isOpenMPParallelDirective(K) ||
3645                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3646           },
3647           /*FromParent=*/true);
3648       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3649         ErrorFound = true;
3650         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3651         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3652         return;
3653       }
3654 
3655       // Define implicit data-sharing attributes for task.
3656       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3657       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3658            (Stack->getDefaultDSA() == DSA_firstprivate &&
3659             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3660           !Stack->isLoopControlVariable(VD).first) {
3661         ImplicitFirstprivate.push_back(E);
3662         return;
3663       }
3664 
3665       // Store implicitly used globals with declare target link for parent
3666       // target.
3667       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3668           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3669         Stack->addToParentTargetRegionLinkGlobals(E);
3670         return;
3671       }
3672     }
3673   }
3674   void VisitMemberExpr(MemberExpr *E) {
3675     if (E->isTypeDependent() || E->isValueDependent() ||
3676         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3677       return;
3678     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3679     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3680     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3681       if (!FD)
3682         return;
3683       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3684       // Check if the variable has explicit DSA set and stop analysis if it
3685       // so.
3686       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3687         return;
3688 
3689       if (isOpenMPTargetExecutionDirective(DKind) &&
3690           !Stack->isLoopControlVariable(FD).first &&
3691           !Stack->checkMappableExprComponentListsForDecl(
3692               FD, /*CurrentRegionOnly=*/true,
3693               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3694                      StackComponents,
3695                  OpenMPClauseKind) {
3696                 return isa<CXXThisExpr>(
3697                     cast<MemberExpr>(
3698                         StackComponents.back().getAssociatedExpression())
3699                         ->getBase()
3700                         ->IgnoreParens());
3701               })) {
3702         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3703         //  A bit-field cannot appear in a map clause.
3704         //
3705         if (FD->isBitField())
3706           return;
3707 
3708         // Check to see if the member expression is referencing a class that
3709         // has already been explicitly mapped
3710         if (Stack->isClassPreviouslyMapped(TE->getType()))
3711           return;
3712 
3713         OpenMPDefaultmapClauseModifier Modifier =
3714             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3715         OpenMPDefaultmapClauseKind ClauseKind =
3716             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3717         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3718             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3719         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3720         return;
3721       }
3722 
3723       SourceLocation ELoc = E->getExprLoc();
3724       // OpenMP [2.9.3.6, Restrictions, p.2]
3725       //  A list item that appears in a reduction clause of the innermost
3726       //  enclosing worksharing or parallel construct may not be accessed in
3727       //  an  explicit task.
3728       DVar = Stack->hasInnermostDSA(
3729           FD,
3730           [](OpenMPClauseKind C, bool AppliedToPointee) {
3731             return C == OMPC_reduction && !AppliedToPointee;
3732           },
3733           [](OpenMPDirectiveKind K) {
3734             return isOpenMPParallelDirective(K) ||
3735                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3736           },
3737           /*FromParent=*/true);
3738       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3739         ErrorFound = true;
3740         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3741         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3742         return;
3743       }
3744 
3745       // Define implicit data-sharing attributes for task.
3746       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3747       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3748           !Stack->isLoopControlVariable(FD).first) {
3749         // Check if there is a captured expression for the current field in the
3750         // region. Do not mark it as firstprivate unless there is no captured
3751         // expression.
3752         // TODO: try to make it firstprivate.
3753         if (DVar.CKind != OMPC_unknown)
3754           ImplicitFirstprivate.push_back(E);
3755       }
3756       return;
3757     }
3758     if (isOpenMPTargetExecutionDirective(DKind)) {
3759       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3760       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3761                                         Stack->getCurrentDirective(),
3762                                         /*NoDiagnose=*/true))
3763         return;
3764       const auto *VD = cast<ValueDecl>(
3765           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3766       if (!Stack->checkMappableExprComponentListsForDecl(
3767               VD, /*CurrentRegionOnly=*/true,
3768               [&CurComponents](
3769                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3770                       StackComponents,
3771                   OpenMPClauseKind) {
3772                 auto CCI = CurComponents.rbegin();
3773                 auto CCE = CurComponents.rend();
3774                 for (const auto &SC : llvm::reverse(StackComponents)) {
3775                   // Do both expressions have the same kind?
3776                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3777                       SC.getAssociatedExpression()->getStmtClass())
3778                     if (!((isa<OMPArraySectionExpr>(
3779                                SC.getAssociatedExpression()) ||
3780                            isa<OMPArrayShapingExpr>(
3781                                SC.getAssociatedExpression())) &&
3782                           isa<ArraySubscriptExpr>(
3783                               CCI->getAssociatedExpression())))
3784                       return false;
3785 
3786                   const Decl *CCD = CCI->getAssociatedDeclaration();
3787                   const Decl *SCD = SC.getAssociatedDeclaration();
3788                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3789                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3790                   if (SCD != CCD)
3791                     return false;
3792                   std::advance(CCI, 1);
3793                   if (CCI == CCE)
3794                     break;
3795                 }
3796                 return true;
3797               })) {
3798         Visit(E->getBase());
3799       }
3800     } else if (!TryCaptureCXXThisMembers) {
3801       Visit(E->getBase());
3802     }
3803   }
3804   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3805     for (OMPClause *C : S->clauses()) {
3806       // Skip analysis of arguments of private clauses for task|target
3807       // directives.
3808       if (isa_and_nonnull<OMPPrivateClause>(C))
3809         continue;
3810       // Skip analysis of arguments of implicitly defined firstprivate clause
3811       // for task|target directives.
3812       // Skip analysis of arguments of implicitly defined map clause for target
3813       // directives.
3814       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3815                  C->isImplicit() &&
3816                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3817         for (Stmt *CC : C->children()) {
3818           if (CC)
3819             Visit(CC);
3820         }
3821       }
3822     }
3823     // Check implicitly captured variables.
3824     VisitSubCaptures(S);
3825   }
3826 
3827   void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
3828     // Loop transformation directives do not introduce data sharing
3829     VisitStmt(S);
3830   }
3831 
3832   void VisitCallExpr(CallExpr *S) {
3833     for (Stmt *C : S->arguments()) {
3834       if (C) {
3835         // Check implicitly captured variables in the task-based directives to
3836         // check if they must be firstprivatized.
3837         Visit(C);
3838       }
3839     }
3840   }
3841   void VisitStmt(Stmt *S) {
3842     for (Stmt *C : S->children()) {
3843       if (C) {
3844         // Check implicitly captured variables in the task-based directives to
3845         // check if they must be firstprivatized.
3846         Visit(C);
3847       }
3848     }
3849   }
3850 
3851   void visitSubCaptures(CapturedStmt *S) {
3852     for (const CapturedStmt::Capture &Cap : S->captures()) {
3853       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3854         continue;
3855       VarDecl *VD = Cap.getCapturedVar();
3856       // Do not try to map the variable if it or its sub-component was mapped
3857       // already.
3858       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3859           Stack->checkMappableExprComponentListsForDecl(
3860               VD, /*CurrentRegionOnly=*/true,
3861               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3862                  OpenMPClauseKind) { return true; }))
3863         continue;
3864       DeclRefExpr *DRE = buildDeclRefExpr(
3865           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3866           Cap.getLocation(), /*RefersToCapture=*/true);
3867       Visit(DRE);
3868     }
3869   }
3870   bool isErrorFound() const { return ErrorFound; }
3871   ArrayRef<Expr *> getImplicitFirstprivate() const {
3872     return ImplicitFirstprivate;
3873   }
3874   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3875                                   OpenMPMapClauseKind MK) const {
3876     return ImplicitMap[DK][MK];
3877   }
3878   ArrayRef<OpenMPMapModifierKind>
3879   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3880     return ImplicitMapModifier[Kind];
3881   }
3882   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3883     return VarsWithInheritedDSA;
3884   }
3885 
3886   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3887       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3888     // Process declare target link variables for the target directives.
3889     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3890       for (DeclRefExpr *E : Stack->getLinkGlobals())
3891         Visit(E);
3892     }
3893   }
3894 };
3895 } // namespace
3896 
3897 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
3898                                                OpenMPDirectiveKind DKind,
3899                                                bool ScopeEntry) {
3900   SmallVector<llvm::omp::TraitProperty, 8> Traits;
3901   if (isOpenMPTargetExecutionDirective(DKind))
3902     Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
3903   if (isOpenMPTeamsDirective(DKind))
3904     Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
3905   if (isOpenMPParallelDirective(DKind))
3906     Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
3907   if (isOpenMPWorksharingDirective(DKind))
3908     Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
3909   if (isOpenMPSimdDirective(DKind))
3910     Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
3911   Stack->handleConstructTrait(Traits, ScopeEntry);
3912 }
3913 
3914 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3915   switch (DKind) {
3916   case OMPD_parallel:
3917   case OMPD_parallel_for:
3918   case OMPD_parallel_for_simd:
3919   case OMPD_parallel_sections:
3920   case OMPD_parallel_master:
3921   case OMPD_teams:
3922   case OMPD_teams_distribute:
3923   case OMPD_teams_distribute_simd: {
3924     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3925     QualType KmpInt32PtrTy =
3926         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3927     Sema::CapturedParamNameType Params[] = {
3928         std::make_pair(".global_tid.", KmpInt32PtrTy),
3929         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3930         std::make_pair(StringRef(), QualType()) // __context with shared vars
3931     };
3932     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3933                              Params);
3934     break;
3935   }
3936   case OMPD_target_teams:
3937   case OMPD_target_parallel:
3938   case OMPD_target_parallel_for:
3939   case OMPD_target_parallel_for_simd:
3940   case OMPD_target_teams_distribute:
3941   case OMPD_target_teams_distribute_simd: {
3942     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3943     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3944     QualType KmpInt32PtrTy =
3945         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3946     QualType Args[] = {VoidPtrTy};
3947     FunctionProtoType::ExtProtoInfo EPI;
3948     EPI.Variadic = true;
3949     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3950     Sema::CapturedParamNameType Params[] = {
3951         std::make_pair(".global_tid.", KmpInt32Ty),
3952         std::make_pair(".part_id.", KmpInt32PtrTy),
3953         std::make_pair(".privates.", VoidPtrTy),
3954         std::make_pair(
3955             ".copy_fn.",
3956             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3957         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3958         std::make_pair(StringRef(), QualType()) // __context with shared vars
3959     };
3960     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3961                              Params, /*OpenMPCaptureLevel=*/0);
3962     // Mark this captured region as inlined, because we don't use outlined
3963     // function directly.
3964     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3965         AlwaysInlineAttr::CreateImplicit(
3966             Context, {}, AttributeCommonInfo::AS_Keyword,
3967             AlwaysInlineAttr::Keyword_forceinline));
3968     Sema::CapturedParamNameType ParamsTarget[] = {
3969         std::make_pair(StringRef(), QualType()) // __context with shared vars
3970     };
3971     // Start a captured region for 'target' with no implicit parameters.
3972     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3973                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3974     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3975         std::make_pair(".global_tid.", KmpInt32PtrTy),
3976         std::make_pair(".bound_tid.", KmpInt32PtrTy),
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                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3983     break;
3984   }
3985   case OMPD_target:
3986   case OMPD_target_simd: {
3987     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3988     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3989     QualType KmpInt32PtrTy =
3990         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3991     QualType Args[] = {VoidPtrTy};
3992     FunctionProtoType::ExtProtoInfo EPI;
3993     EPI.Variadic = true;
3994     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3995     Sema::CapturedParamNameType Params[] = {
3996         std::make_pair(".global_tid.", KmpInt32Ty),
3997         std::make_pair(".part_id.", KmpInt32PtrTy),
3998         std::make_pair(".privates.", VoidPtrTy),
3999         std::make_pair(
4000             ".copy_fn.",
4001             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4002         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4003         std::make_pair(StringRef(), QualType()) // __context with shared vars
4004     };
4005     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4006                              Params, /*OpenMPCaptureLevel=*/0);
4007     // Mark this captured region as inlined, because we don't use outlined
4008     // function directly.
4009     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4010         AlwaysInlineAttr::CreateImplicit(
4011             Context, {}, AttributeCommonInfo::AS_Keyword,
4012             AlwaysInlineAttr::Keyword_forceinline));
4013     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4014                              std::make_pair(StringRef(), QualType()),
4015                              /*OpenMPCaptureLevel=*/1);
4016     break;
4017   }
4018   case OMPD_atomic:
4019   case OMPD_critical:
4020   case OMPD_section:
4021   case OMPD_master:
4022   case OMPD_masked:
4023   case OMPD_tile:
4024   case OMPD_unroll:
4025     break;
4026   case OMPD_loop:
4027     // TODO: 'loop' may require additional parameters depending on the binding.
4028     // Treat similar to OMPD_simd/OMPD_for for now.
4029   case OMPD_simd:
4030   case OMPD_for:
4031   case OMPD_for_simd:
4032   case OMPD_sections:
4033   case OMPD_single:
4034   case OMPD_taskgroup:
4035   case OMPD_distribute:
4036   case OMPD_distribute_simd:
4037   case OMPD_ordered:
4038   case OMPD_target_data:
4039   case OMPD_dispatch: {
4040     Sema::CapturedParamNameType Params[] = {
4041         std::make_pair(StringRef(), QualType()) // __context with shared vars
4042     };
4043     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4044                              Params);
4045     break;
4046   }
4047   case OMPD_task: {
4048     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4049     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4050     QualType KmpInt32PtrTy =
4051         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4052     QualType Args[] = {VoidPtrTy};
4053     FunctionProtoType::ExtProtoInfo EPI;
4054     EPI.Variadic = true;
4055     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4056     Sema::CapturedParamNameType Params[] = {
4057         std::make_pair(".global_tid.", KmpInt32Ty),
4058         std::make_pair(".part_id.", KmpInt32PtrTy),
4059         std::make_pair(".privates.", VoidPtrTy),
4060         std::make_pair(
4061             ".copy_fn.",
4062             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4063         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4064         std::make_pair(StringRef(), QualType()) // __context with shared vars
4065     };
4066     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4067                              Params);
4068     // Mark this captured region as inlined, because we don't use outlined
4069     // function directly.
4070     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4071         AlwaysInlineAttr::CreateImplicit(
4072             Context, {}, AttributeCommonInfo::AS_Keyword,
4073             AlwaysInlineAttr::Keyword_forceinline));
4074     break;
4075   }
4076   case OMPD_taskloop:
4077   case OMPD_taskloop_simd:
4078   case OMPD_master_taskloop:
4079   case OMPD_master_taskloop_simd: {
4080     QualType KmpInt32Ty =
4081         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4082             .withConst();
4083     QualType KmpUInt64Ty =
4084         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4085             .withConst();
4086     QualType KmpInt64Ty =
4087         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4088             .withConst();
4089     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4090     QualType KmpInt32PtrTy =
4091         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4092     QualType Args[] = {VoidPtrTy};
4093     FunctionProtoType::ExtProtoInfo EPI;
4094     EPI.Variadic = true;
4095     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4096     Sema::CapturedParamNameType Params[] = {
4097         std::make_pair(".global_tid.", KmpInt32Ty),
4098         std::make_pair(".part_id.", KmpInt32PtrTy),
4099         std::make_pair(".privates.", VoidPtrTy),
4100         std::make_pair(
4101             ".copy_fn.",
4102             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4103         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4104         std::make_pair(".lb.", KmpUInt64Ty),
4105         std::make_pair(".ub.", KmpUInt64Ty),
4106         std::make_pair(".st.", KmpInt64Ty),
4107         std::make_pair(".liter.", KmpInt32Ty),
4108         std::make_pair(".reductions.", VoidPtrTy),
4109         std::make_pair(StringRef(), QualType()) // __context with shared vars
4110     };
4111     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4112                              Params);
4113     // Mark this captured region as inlined, because we don't use outlined
4114     // function directly.
4115     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4116         AlwaysInlineAttr::CreateImplicit(
4117             Context, {}, AttributeCommonInfo::AS_Keyword,
4118             AlwaysInlineAttr::Keyword_forceinline));
4119     break;
4120   }
4121   case OMPD_parallel_master_taskloop:
4122   case OMPD_parallel_master_taskloop_simd: {
4123     QualType KmpInt32Ty =
4124         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4125             .withConst();
4126     QualType KmpUInt64Ty =
4127         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4128             .withConst();
4129     QualType KmpInt64Ty =
4130         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4131             .withConst();
4132     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4133     QualType KmpInt32PtrTy =
4134         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4135     Sema::CapturedParamNameType ParamsParallel[] = {
4136         std::make_pair(".global_tid.", KmpInt32PtrTy),
4137         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4138         std::make_pair(StringRef(), QualType()) // __context with shared vars
4139     };
4140     // Start a captured region for 'parallel'.
4141     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4142                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4143     QualType Args[] = {VoidPtrTy};
4144     FunctionProtoType::ExtProtoInfo EPI;
4145     EPI.Variadic = true;
4146     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4147     Sema::CapturedParamNameType Params[] = {
4148         std::make_pair(".global_tid.", KmpInt32Ty),
4149         std::make_pair(".part_id.", KmpInt32PtrTy),
4150         std::make_pair(".privates.", VoidPtrTy),
4151         std::make_pair(
4152             ".copy_fn.",
4153             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4154         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4155         std::make_pair(".lb.", KmpUInt64Ty),
4156         std::make_pair(".ub.", KmpUInt64Ty),
4157         std::make_pair(".st.", KmpInt64Ty),
4158         std::make_pair(".liter.", KmpInt32Ty),
4159         std::make_pair(".reductions.", VoidPtrTy),
4160         std::make_pair(StringRef(), QualType()) // __context with shared vars
4161     };
4162     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4163                              Params, /*OpenMPCaptureLevel=*/1);
4164     // Mark this captured region as inlined, because we don't use outlined
4165     // function directly.
4166     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4167         AlwaysInlineAttr::CreateImplicit(
4168             Context, {}, AttributeCommonInfo::AS_Keyword,
4169             AlwaysInlineAttr::Keyword_forceinline));
4170     break;
4171   }
4172   case OMPD_distribute_parallel_for_simd:
4173   case OMPD_distribute_parallel_for: {
4174     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4175     QualType KmpInt32PtrTy =
4176         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4177     Sema::CapturedParamNameType Params[] = {
4178         std::make_pair(".global_tid.", KmpInt32PtrTy),
4179         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4180         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4181         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4182         std::make_pair(StringRef(), QualType()) // __context with shared vars
4183     };
4184     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4185                              Params);
4186     break;
4187   }
4188   case OMPD_target_teams_distribute_parallel_for:
4189   case OMPD_target_teams_distribute_parallel_for_simd: {
4190     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4191     QualType KmpInt32PtrTy =
4192         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4193     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4194 
4195     QualType Args[] = {VoidPtrTy};
4196     FunctionProtoType::ExtProtoInfo EPI;
4197     EPI.Variadic = true;
4198     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4199     Sema::CapturedParamNameType Params[] = {
4200         std::make_pair(".global_tid.", KmpInt32Ty),
4201         std::make_pair(".part_id.", KmpInt32PtrTy),
4202         std::make_pair(".privates.", VoidPtrTy),
4203         std::make_pair(
4204             ".copy_fn.",
4205             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4206         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4207         std::make_pair(StringRef(), QualType()) // __context with shared vars
4208     };
4209     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4210                              Params, /*OpenMPCaptureLevel=*/0);
4211     // Mark this captured region as inlined, because we don't use outlined
4212     // function directly.
4213     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4214         AlwaysInlineAttr::CreateImplicit(
4215             Context, {}, AttributeCommonInfo::AS_Keyword,
4216             AlwaysInlineAttr::Keyword_forceinline));
4217     Sema::CapturedParamNameType ParamsTarget[] = {
4218         std::make_pair(StringRef(), QualType()) // __context with shared vars
4219     };
4220     // Start a captured region for 'target' with no implicit parameters.
4221     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4222                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4223 
4224     Sema::CapturedParamNameType ParamsTeams[] = {
4225         std::make_pair(".global_tid.", KmpInt32PtrTy),
4226         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4227         std::make_pair(StringRef(), QualType()) // __context with shared vars
4228     };
4229     // Start a captured region for 'target' with no implicit parameters.
4230     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4231                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4232 
4233     Sema::CapturedParamNameType ParamsParallel[] = {
4234         std::make_pair(".global_tid.", KmpInt32PtrTy),
4235         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4236         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4237         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4238         std::make_pair(StringRef(), QualType()) // __context with shared vars
4239     };
4240     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4241     // the same implicit parameters.
4242     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4243                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4244     break;
4245   }
4246 
4247   case OMPD_teams_distribute_parallel_for:
4248   case OMPD_teams_distribute_parallel_for_simd: {
4249     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4250     QualType KmpInt32PtrTy =
4251         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4252 
4253     Sema::CapturedParamNameType ParamsTeams[] = {
4254         std::make_pair(".global_tid.", KmpInt32PtrTy),
4255         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4256         std::make_pair(StringRef(), QualType()) // __context with shared vars
4257     };
4258     // Start a captured region for 'target' with no implicit parameters.
4259     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4260                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4261 
4262     Sema::CapturedParamNameType ParamsParallel[] = {
4263         std::make_pair(".global_tid.", KmpInt32PtrTy),
4264         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4265         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4266         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4267         std::make_pair(StringRef(), QualType()) // __context with shared vars
4268     };
4269     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4270     // the same implicit parameters.
4271     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4272                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4273     break;
4274   }
4275   case OMPD_target_update:
4276   case OMPD_target_enter_data:
4277   case OMPD_target_exit_data: {
4278     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4279     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4280     QualType KmpInt32PtrTy =
4281         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4282     QualType Args[] = {VoidPtrTy};
4283     FunctionProtoType::ExtProtoInfo EPI;
4284     EPI.Variadic = true;
4285     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4286     Sema::CapturedParamNameType Params[] = {
4287         std::make_pair(".global_tid.", KmpInt32Ty),
4288         std::make_pair(".part_id.", KmpInt32PtrTy),
4289         std::make_pair(".privates.", VoidPtrTy),
4290         std::make_pair(
4291             ".copy_fn.",
4292             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4293         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4294         std::make_pair(StringRef(), QualType()) // __context with shared vars
4295     };
4296     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4297                              Params);
4298     // Mark this captured region as inlined, because we don't use outlined
4299     // function directly.
4300     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4301         AlwaysInlineAttr::CreateImplicit(
4302             Context, {}, AttributeCommonInfo::AS_Keyword,
4303             AlwaysInlineAttr::Keyword_forceinline));
4304     break;
4305   }
4306   case OMPD_threadprivate:
4307   case OMPD_allocate:
4308   case OMPD_taskyield:
4309   case OMPD_barrier:
4310   case OMPD_taskwait:
4311   case OMPD_cancellation_point:
4312   case OMPD_cancel:
4313   case OMPD_flush:
4314   case OMPD_depobj:
4315   case OMPD_scan:
4316   case OMPD_declare_reduction:
4317   case OMPD_declare_mapper:
4318   case OMPD_declare_simd:
4319   case OMPD_declare_target:
4320   case OMPD_end_declare_target:
4321   case OMPD_requires:
4322   case OMPD_declare_variant:
4323   case OMPD_begin_declare_variant:
4324   case OMPD_end_declare_variant:
4325   case OMPD_metadirective:
4326     llvm_unreachable("OpenMP Directive is not allowed");
4327   case OMPD_unknown:
4328   default:
4329     llvm_unreachable("Unknown OpenMP directive");
4330   }
4331   DSAStack->setContext(CurContext);
4332   handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
4333 }
4334 
4335 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4336   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4337 }
4338 
4339 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4340   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4341   getOpenMPCaptureRegions(CaptureRegions, DKind);
4342   return CaptureRegions.size();
4343 }
4344 
4345 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4346                                              Expr *CaptureExpr, bool WithInit,
4347                                              bool AsExpression) {
4348   assert(CaptureExpr);
4349   ASTContext &C = S.getASTContext();
4350   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4351   QualType Ty = Init->getType();
4352   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4353     if (S.getLangOpts().CPlusPlus) {
4354       Ty = C.getLValueReferenceType(Ty);
4355     } else {
4356       Ty = C.getPointerType(Ty);
4357       ExprResult Res =
4358           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4359       if (!Res.isUsable())
4360         return nullptr;
4361       Init = Res.get();
4362     }
4363     WithInit = true;
4364   }
4365   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4366                                           CaptureExpr->getBeginLoc());
4367   if (!WithInit)
4368     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4369   S.CurContext->addHiddenDecl(CED);
4370   Sema::TentativeAnalysisScope Trap(S);
4371   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4372   return CED;
4373 }
4374 
4375 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4376                                  bool WithInit) {
4377   OMPCapturedExprDecl *CD;
4378   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4379     CD = cast<OMPCapturedExprDecl>(VD);
4380   else
4381     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4382                           /*AsExpression=*/false);
4383   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4384                           CaptureExpr->getExprLoc());
4385 }
4386 
4387 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4388   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4389   if (!Ref) {
4390     OMPCapturedExprDecl *CD = buildCaptureDecl(
4391         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4392         /*WithInit=*/true, /*AsExpression=*/true);
4393     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4394                            CaptureExpr->getExprLoc());
4395   }
4396   ExprResult Res = Ref;
4397   if (!S.getLangOpts().CPlusPlus &&
4398       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4399       Ref->getType()->isPointerType()) {
4400     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4401     if (!Res.isUsable())
4402       return ExprError();
4403   }
4404   return S.DefaultLvalueConversion(Res.get());
4405 }
4406 
4407 namespace {
4408 // OpenMP directives parsed in this section are represented as a
4409 // CapturedStatement with an associated statement.  If a syntax error
4410 // is detected during the parsing of the associated statement, the
4411 // compiler must abort processing and close the CapturedStatement.
4412 //
4413 // Combined directives such as 'target parallel' have more than one
4414 // nested CapturedStatements.  This RAII ensures that we unwind out
4415 // of all the nested CapturedStatements when an error is found.
4416 class CaptureRegionUnwinderRAII {
4417 private:
4418   Sema &S;
4419   bool &ErrorFound;
4420   OpenMPDirectiveKind DKind = OMPD_unknown;
4421 
4422 public:
4423   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4424                             OpenMPDirectiveKind DKind)
4425       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4426   ~CaptureRegionUnwinderRAII() {
4427     if (ErrorFound) {
4428       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4429       while (--ThisCaptureLevel >= 0)
4430         S.ActOnCapturedRegionError();
4431     }
4432   }
4433 };
4434 } // namespace
4435 
4436 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4437   // Capture variables captured by reference in lambdas for target-based
4438   // directives.
4439   if (!CurContext->isDependentContext() &&
4440       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4441        isOpenMPTargetDataManagementDirective(
4442            DSAStack->getCurrentDirective()))) {
4443     QualType Type = V->getType();
4444     if (const auto *RD = Type.getCanonicalType()
4445                              .getNonReferenceType()
4446                              ->getAsCXXRecordDecl()) {
4447       bool SavedForceCaptureByReferenceInTargetExecutable =
4448           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4449       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4450           /*V=*/true);
4451       if (RD->isLambda()) {
4452         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4453         FieldDecl *ThisCapture;
4454         RD->getCaptureFields(Captures, ThisCapture);
4455         for (const LambdaCapture &LC : RD->captures()) {
4456           if (LC.getCaptureKind() == LCK_ByRef) {
4457             VarDecl *VD = LC.getCapturedVar();
4458             DeclContext *VDC = VD->getDeclContext();
4459             if (!VDC->Encloses(CurContext))
4460               continue;
4461             MarkVariableReferenced(LC.getLocation(), VD);
4462           } else if (LC.getCaptureKind() == LCK_This) {
4463             QualType ThisTy = getCurrentThisType();
4464             if (!ThisTy.isNull() &&
4465                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4466               CheckCXXThisCapture(LC.getLocation());
4467           }
4468         }
4469       }
4470       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4471           SavedForceCaptureByReferenceInTargetExecutable);
4472     }
4473   }
4474 }
4475 
4476 static bool checkOrderedOrderSpecified(Sema &S,
4477                                        const ArrayRef<OMPClause *> Clauses) {
4478   const OMPOrderedClause *Ordered = nullptr;
4479   const OMPOrderClause *Order = nullptr;
4480 
4481   for (const OMPClause *Clause : Clauses) {
4482     if (Clause->getClauseKind() == OMPC_ordered)
4483       Ordered = cast<OMPOrderedClause>(Clause);
4484     else if (Clause->getClauseKind() == OMPC_order) {
4485       Order = cast<OMPOrderClause>(Clause);
4486       if (Order->getKind() != OMPC_ORDER_concurrent)
4487         Order = nullptr;
4488     }
4489     if (Ordered && Order)
4490       break;
4491   }
4492 
4493   if (Ordered && Order) {
4494     S.Diag(Order->getKindKwLoc(),
4495            diag::err_omp_simple_clause_incompatible_with_ordered)
4496         << getOpenMPClauseName(OMPC_order)
4497         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4498         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4499     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4500         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4501     return true;
4502   }
4503   return false;
4504 }
4505 
4506 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4507                                       ArrayRef<OMPClause *> Clauses) {
4508   handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
4509                                      /* ScopeEntry */ false);
4510   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4511       DSAStack->getCurrentDirective() == OMPD_critical ||
4512       DSAStack->getCurrentDirective() == OMPD_section ||
4513       DSAStack->getCurrentDirective() == OMPD_master ||
4514       DSAStack->getCurrentDirective() == OMPD_masked)
4515     return S;
4516 
4517   bool ErrorFound = false;
4518   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4519       *this, ErrorFound, DSAStack->getCurrentDirective());
4520   if (!S.isUsable()) {
4521     ErrorFound = true;
4522     return StmtError();
4523   }
4524 
4525   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4526   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4527   OMPOrderedClause *OC = nullptr;
4528   OMPScheduleClause *SC = nullptr;
4529   SmallVector<const OMPLinearClause *, 4> LCs;
4530   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4531   // This is required for proper codegen.
4532   for (OMPClause *Clause : Clauses) {
4533     if (!LangOpts.OpenMPSimd &&
4534         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4535         Clause->getClauseKind() == OMPC_in_reduction) {
4536       // Capture taskgroup task_reduction descriptors inside the tasking regions
4537       // with the corresponding in_reduction items.
4538       auto *IRC = cast<OMPInReductionClause>(Clause);
4539       for (Expr *E : IRC->taskgroup_descriptors())
4540         if (E)
4541           MarkDeclarationsReferencedInExpr(E);
4542     }
4543     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4544         Clause->getClauseKind() == OMPC_copyprivate ||
4545         (getLangOpts().OpenMPUseTLS &&
4546          getASTContext().getTargetInfo().isTLSSupported() &&
4547          Clause->getClauseKind() == OMPC_copyin)) {
4548       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4549       // Mark all variables in private list clauses as used in inner region.
4550       for (Stmt *VarRef : Clause->children()) {
4551         if (auto *E = cast_or_null<Expr>(VarRef)) {
4552           MarkDeclarationsReferencedInExpr(E);
4553         }
4554       }
4555       DSAStack->setForceVarCapturing(/*V=*/false);
4556     } else if (isOpenMPLoopTransformationDirective(
4557                    DSAStack->getCurrentDirective())) {
4558       assert(CaptureRegions.empty() &&
4559              "No captured regions in loop transformation directives.");
4560     } else if (CaptureRegions.size() > 1 ||
4561                CaptureRegions.back() != OMPD_unknown) {
4562       if (auto *C = OMPClauseWithPreInit::get(Clause))
4563         PICs.push_back(C);
4564       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4565         if (Expr *E = C->getPostUpdateExpr())
4566           MarkDeclarationsReferencedInExpr(E);
4567       }
4568     }
4569     if (Clause->getClauseKind() == OMPC_schedule)
4570       SC = cast<OMPScheduleClause>(Clause);
4571     else if (Clause->getClauseKind() == OMPC_ordered)
4572       OC = cast<OMPOrderedClause>(Clause);
4573     else if (Clause->getClauseKind() == OMPC_linear)
4574       LCs.push_back(cast<OMPLinearClause>(Clause));
4575   }
4576   // Capture allocator expressions if used.
4577   for (Expr *E : DSAStack->getInnerAllocators())
4578     MarkDeclarationsReferencedInExpr(E);
4579   // OpenMP, 2.7.1 Loop Construct, Restrictions
4580   // The nonmonotonic modifier cannot be specified if an ordered clause is
4581   // specified.
4582   if (SC &&
4583       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4584        SC->getSecondScheduleModifier() ==
4585            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4586       OC) {
4587     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4588              ? SC->getFirstScheduleModifierLoc()
4589              : SC->getSecondScheduleModifierLoc(),
4590          diag::err_omp_simple_clause_incompatible_with_ordered)
4591         << getOpenMPClauseName(OMPC_schedule)
4592         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4593                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4594         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4595     ErrorFound = true;
4596   }
4597   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4598   // If an order(concurrent) clause is present, an ordered clause may not appear
4599   // on the same directive.
4600   if (checkOrderedOrderSpecified(*this, Clauses))
4601     ErrorFound = true;
4602   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4603     for (const OMPLinearClause *C : LCs) {
4604       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4605           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4606     }
4607     ErrorFound = true;
4608   }
4609   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4610       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4611       OC->getNumForLoops()) {
4612     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4613         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4614     ErrorFound = true;
4615   }
4616   if (ErrorFound) {
4617     return StmtError();
4618   }
4619   StmtResult SR = S;
4620   unsigned CompletedRegions = 0;
4621   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4622     // Mark all variables in private list clauses as used in inner region.
4623     // Required for proper codegen of combined directives.
4624     // TODO: add processing for other clauses.
4625     if (ThisCaptureRegion != OMPD_unknown) {
4626       for (const clang::OMPClauseWithPreInit *C : PICs) {
4627         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4628         // Find the particular capture region for the clause if the
4629         // directive is a combined one with multiple capture regions.
4630         // If the directive is not a combined one, the capture region
4631         // associated with the clause is OMPD_unknown and is generated
4632         // only once.
4633         if (CaptureRegion == ThisCaptureRegion ||
4634             CaptureRegion == OMPD_unknown) {
4635           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4636             for (Decl *D : DS->decls())
4637               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4638           }
4639         }
4640       }
4641     }
4642     if (ThisCaptureRegion == OMPD_target) {
4643       // Capture allocator traits in the target region. They are used implicitly
4644       // and, thus, are not captured by default.
4645       for (OMPClause *C : Clauses) {
4646         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4647           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4648                ++I) {
4649             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4650             if (Expr *E = D.AllocatorTraits)
4651               MarkDeclarationsReferencedInExpr(E);
4652           }
4653           continue;
4654         }
4655       }
4656     }
4657     if (ThisCaptureRegion == OMPD_parallel) {
4658       // Capture temp arrays for inscan reductions and locals in aligned
4659       // clauses.
4660       for (OMPClause *C : Clauses) {
4661         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4662           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4663             continue;
4664           for (Expr *E : RC->copy_array_temps())
4665             MarkDeclarationsReferencedInExpr(E);
4666         }
4667         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4668           for (Expr *E : AC->varlists())
4669             MarkDeclarationsReferencedInExpr(E);
4670         }
4671       }
4672     }
4673     if (++CompletedRegions == CaptureRegions.size())
4674       DSAStack->setBodyComplete();
4675     SR = ActOnCapturedRegionEnd(SR.get());
4676   }
4677   return SR;
4678 }
4679 
4680 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4681                               OpenMPDirectiveKind CancelRegion,
4682                               SourceLocation StartLoc) {
4683   // CancelRegion is only needed for cancel and cancellation_point.
4684   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4685     return false;
4686 
4687   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4688       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4689     return false;
4690 
4691   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4692       << getOpenMPDirectiveName(CancelRegion);
4693   return true;
4694 }
4695 
4696 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4697                                   OpenMPDirectiveKind CurrentRegion,
4698                                   const DeclarationNameInfo &CurrentName,
4699                                   OpenMPDirectiveKind CancelRegion,
4700                                   OpenMPBindClauseKind BindKind,
4701                                   SourceLocation StartLoc) {
4702   if (Stack->getCurScope()) {
4703     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4704     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4705     bool NestingProhibited = false;
4706     bool CloseNesting = true;
4707     bool OrphanSeen = false;
4708     enum {
4709       NoRecommend,
4710       ShouldBeInParallelRegion,
4711       ShouldBeInOrderedRegion,
4712       ShouldBeInTargetRegion,
4713       ShouldBeInTeamsRegion,
4714       ShouldBeInLoopSimdRegion,
4715     } Recommend = NoRecommend;
4716     if (isOpenMPSimdDirective(ParentRegion) &&
4717         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4718          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4719           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4720           CurrentRegion != OMPD_scan))) {
4721       // OpenMP [2.16, Nesting of Regions]
4722       // OpenMP constructs may not be nested inside a simd region.
4723       // OpenMP [2.8.1,simd Construct, Restrictions]
4724       // An ordered construct with the simd clause is the only OpenMP
4725       // construct that can appear in the simd region.
4726       // Allowing a SIMD construct nested in another SIMD construct is an
4727       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4728       // message.
4729       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4730       // The only OpenMP constructs that can be encountered during execution of
4731       // a simd region are the atomic construct, the loop construct, the simd
4732       // construct and the ordered construct with the simd clause.
4733       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4734                                  ? diag::err_omp_prohibited_region_simd
4735                                  : diag::warn_omp_nesting_simd)
4736           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4737       return CurrentRegion != OMPD_simd;
4738     }
4739     if (ParentRegion == OMPD_atomic) {
4740       // OpenMP [2.16, Nesting of Regions]
4741       // OpenMP constructs may not be nested inside an atomic region.
4742       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4743       return true;
4744     }
4745     if (CurrentRegion == OMPD_section) {
4746       // OpenMP [2.7.2, sections Construct, Restrictions]
4747       // Orphaned section directives are prohibited. That is, the section
4748       // directives must appear within the sections construct and must not be
4749       // encountered elsewhere in the sections region.
4750       if (ParentRegion != OMPD_sections &&
4751           ParentRegion != OMPD_parallel_sections) {
4752         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4753             << (ParentRegion != OMPD_unknown)
4754             << getOpenMPDirectiveName(ParentRegion);
4755         return true;
4756       }
4757       return false;
4758     }
4759     // Allow some constructs (except teams and cancellation constructs) to be
4760     // orphaned (they could be used in functions, called from OpenMP regions
4761     // with the required preconditions).
4762     if (ParentRegion == OMPD_unknown &&
4763         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4764         CurrentRegion != OMPD_cancellation_point &&
4765         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4766       return false;
4767     if (CurrentRegion == OMPD_cancellation_point ||
4768         CurrentRegion == OMPD_cancel) {
4769       // OpenMP [2.16, Nesting of Regions]
4770       // A cancellation point construct for which construct-type-clause is
4771       // taskgroup must be nested inside a task construct. A cancellation
4772       // point construct for which construct-type-clause is not taskgroup must
4773       // be closely nested inside an OpenMP construct that matches the type
4774       // specified in construct-type-clause.
4775       // A cancel construct for which construct-type-clause is taskgroup must be
4776       // nested inside a task construct. A cancel construct for which
4777       // construct-type-clause is not taskgroup must be closely nested inside an
4778       // OpenMP construct that matches the type specified in
4779       // construct-type-clause.
4780       NestingProhibited =
4781           !((CancelRegion == OMPD_parallel &&
4782              (ParentRegion == OMPD_parallel ||
4783               ParentRegion == OMPD_target_parallel)) ||
4784             (CancelRegion == OMPD_for &&
4785              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4786               ParentRegion == OMPD_target_parallel_for ||
4787               ParentRegion == OMPD_distribute_parallel_for ||
4788               ParentRegion == OMPD_teams_distribute_parallel_for ||
4789               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4790             (CancelRegion == OMPD_taskgroup &&
4791              (ParentRegion == OMPD_task ||
4792               (SemaRef.getLangOpts().OpenMP >= 50 &&
4793                (ParentRegion == OMPD_taskloop ||
4794                 ParentRegion == OMPD_master_taskloop ||
4795                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4796             (CancelRegion == OMPD_sections &&
4797              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4798               ParentRegion == OMPD_parallel_sections)));
4799       OrphanSeen = ParentRegion == OMPD_unknown;
4800     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4801       // OpenMP 5.1 [2.22, Nesting of Regions]
4802       // A masked region may not be closely nested inside a worksharing, loop,
4803       // atomic, task, or taskloop region.
4804       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4805                           isOpenMPGenericLoopDirective(ParentRegion) ||
4806                           isOpenMPTaskingDirective(ParentRegion);
4807     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4808       // OpenMP [2.16, Nesting of Regions]
4809       // A critical region may not be nested (closely or otherwise) inside a
4810       // critical region with the same name. Note that this restriction is not
4811       // sufficient to prevent deadlock.
4812       SourceLocation PreviousCriticalLoc;
4813       bool DeadLock = Stack->hasDirective(
4814           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4815                                               const DeclarationNameInfo &DNI,
4816                                               SourceLocation Loc) {
4817             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4818               PreviousCriticalLoc = Loc;
4819               return true;
4820             }
4821             return false;
4822           },
4823           false /* skip top directive */);
4824       if (DeadLock) {
4825         SemaRef.Diag(StartLoc,
4826                      diag::err_omp_prohibited_region_critical_same_name)
4827             << CurrentName.getName();
4828         if (PreviousCriticalLoc.isValid())
4829           SemaRef.Diag(PreviousCriticalLoc,
4830                        diag::note_omp_previous_critical_region);
4831         return true;
4832       }
4833     } else if (CurrentRegion == OMPD_barrier) {
4834       // OpenMP 5.1 [2.22, Nesting of Regions]
4835       // A barrier region may not be closely nested inside a worksharing, loop,
4836       // task, taskloop, critical, ordered, atomic, or masked region.
4837       NestingProhibited =
4838           isOpenMPWorksharingDirective(ParentRegion) ||
4839           isOpenMPGenericLoopDirective(ParentRegion) ||
4840           isOpenMPTaskingDirective(ParentRegion) ||
4841           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4842           ParentRegion == OMPD_parallel_master ||
4843           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4844     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4845                !isOpenMPParallelDirective(CurrentRegion) &&
4846                !isOpenMPTeamsDirective(CurrentRegion)) {
4847       // OpenMP 5.1 [2.22, Nesting of Regions]
4848       // A loop region that binds to a parallel region or a worksharing region
4849       // may not be closely nested inside a worksharing, loop, task, taskloop,
4850       // critical, ordered, atomic, or masked region.
4851       NestingProhibited =
4852           isOpenMPWorksharingDirective(ParentRegion) ||
4853           isOpenMPGenericLoopDirective(ParentRegion) ||
4854           isOpenMPTaskingDirective(ParentRegion) ||
4855           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4856           ParentRegion == OMPD_parallel_master ||
4857           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4858       Recommend = ShouldBeInParallelRegion;
4859     } else if (CurrentRegion == OMPD_ordered) {
4860       // OpenMP [2.16, Nesting of Regions]
4861       // An ordered region may not be closely nested inside a critical,
4862       // atomic, or explicit task region.
4863       // An ordered region must be closely nested inside a loop region (or
4864       // parallel loop region) with an ordered clause.
4865       // OpenMP [2.8.1,simd Construct, Restrictions]
4866       // An ordered construct with the simd clause is the only OpenMP construct
4867       // that can appear in the simd region.
4868       NestingProhibited = ParentRegion == OMPD_critical ||
4869                           isOpenMPTaskingDirective(ParentRegion) ||
4870                           !(isOpenMPSimdDirective(ParentRegion) ||
4871                             Stack->isParentOrderedRegion());
4872       Recommend = ShouldBeInOrderedRegion;
4873     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4874       // OpenMP [2.16, Nesting of Regions]
4875       // If specified, a teams construct must be contained within a target
4876       // construct.
4877       NestingProhibited =
4878           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4879           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4880            ParentRegion != OMPD_target);
4881       OrphanSeen = ParentRegion == OMPD_unknown;
4882       Recommend = ShouldBeInTargetRegion;
4883     } else if (CurrentRegion == OMPD_scan) {
4884       // OpenMP [2.16, Nesting of Regions]
4885       // If specified, a teams construct must be contained within a target
4886       // construct.
4887       NestingProhibited =
4888           SemaRef.LangOpts.OpenMP < 50 ||
4889           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4890            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4891            ParentRegion != OMPD_parallel_for_simd);
4892       OrphanSeen = ParentRegion == OMPD_unknown;
4893       Recommend = ShouldBeInLoopSimdRegion;
4894     }
4895     if (!NestingProhibited &&
4896         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4897         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4898         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4899       // OpenMP [5.1, 2.22, Nesting of Regions]
4900       // distribute, distribute simd, distribute parallel worksharing-loop,
4901       // distribute parallel worksharing-loop SIMD, loop, parallel regions,
4902       // including any parallel regions arising from combined constructs,
4903       // omp_get_num_teams() regions, and omp_get_team_num() regions are the
4904       // only OpenMP regions that may be strictly nested inside the teams
4905       // region.
4906       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4907                           !isOpenMPDistributeDirective(CurrentRegion) &&
4908                           CurrentRegion != OMPD_loop;
4909       Recommend = ShouldBeInParallelRegion;
4910     }
4911     if (!NestingProhibited && CurrentRegion == OMPD_loop) {
4912       // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
4913       // If the bind clause is present on the loop construct and binding is
4914       // teams then the corresponding loop region must be strictly nested inside
4915       // a teams region.
4916       NestingProhibited = BindKind == OMPC_BIND_teams &&
4917                           ParentRegion != OMPD_teams &&
4918                           ParentRegion != OMPD_target_teams;
4919       Recommend = ShouldBeInTeamsRegion;
4920     }
4921     if (!NestingProhibited &&
4922         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4923       // OpenMP 4.5 [2.17 Nesting of Regions]
4924       // The region associated with the distribute construct must be strictly
4925       // nested inside a teams region
4926       NestingProhibited =
4927           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4928       Recommend = ShouldBeInTeamsRegion;
4929     }
4930     if (!NestingProhibited &&
4931         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4932          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4933       // OpenMP 4.5 [2.17 Nesting of Regions]
4934       // If a target, target update, target data, target enter data, or
4935       // target exit data construct is encountered during execution of a
4936       // target region, the behavior is unspecified.
4937       NestingProhibited = Stack->hasDirective(
4938           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4939                              SourceLocation) {
4940             if (isOpenMPTargetExecutionDirective(K)) {
4941               OffendingRegion = K;
4942               return true;
4943             }
4944             return false;
4945           },
4946           false /* don't skip top directive */);
4947       CloseNesting = false;
4948     }
4949     if (NestingProhibited) {
4950       if (OrphanSeen) {
4951         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4952             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4953       } else {
4954         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4955             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4956             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4957       }
4958       return true;
4959     }
4960   }
4961   return false;
4962 }
4963 
4964 struct Kind2Unsigned {
4965   using argument_type = OpenMPDirectiveKind;
4966   unsigned operator()(argument_type DK) { return unsigned(DK); }
4967 };
4968 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4969                            ArrayRef<OMPClause *> Clauses,
4970                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4971   bool ErrorFound = false;
4972   unsigned NamedModifiersNumber = 0;
4973   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4974   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4975   SmallVector<SourceLocation, 4> NameModifierLoc;
4976   for (const OMPClause *C : Clauses) {
4977     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4978       // At most one if clause without a directive-name-modifier can appear on
4979       // the directive.
4980       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4981       if (FoundNameModifiers[CurNM]) {
4982         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4983             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4984             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4985         ErrorFound = true;
4986       } else if (CurNM != OMPD_unknown) {
4987         NameModifierLoc.push_back(IC->getNameModifierLoc());
4988         ++NamedModifiersNumber;
4989       }
4990       FoundNameModifiers[CurNM] = IC;
4991       if (CurNM == OMPD_unknown)
4992         continue;
4993       // Check if the specified name modifier is allowed for the current
4994       // directive.
4995       // At most one if clause with the particular directive-name-modifier can
4996       // appear on the directive.
4997       if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
4998         S.Diag(IC->getNameModifierLoc(),
4999                diag::err_omp_wrong_if_directive_name_modifier)
5000             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
5001         ErrorFound = true;
5002       }
5003     }
5004   }
5005   // If any if clause on the directive includes a directive-name-modifier then
5006   // all if clauses on the directive must include a directive-name-modifier.
5007   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5008     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5009       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5010              diag::err_omp_no_more_if_clause);
5011     } else {
5012       std::string Values;
5013       std::string Sep(", ");
5014       unsigned AllowedCnt = 0;
5015       unsigned TotalAllowedNum =
5016           AllowedNameModifiers.size() - NamedModifiersNumber;
5017       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5018            ++Cnt) {
5019         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5020         if (!FoundNameModifiers[NM]) {
5021           Values += "'";
5022           Values += getOpenMPDirectiveName(NM);
5023           Values += "'";
5024           if (AllowedCnt + 2 == TotalAllowedNum)
5025             Values += " or ";
5026           else if (AllowedCnt + 1 != TotalAllowedNum)
5027             Values += Sep;
5028           ++AllowedCnt;
5029         }
5030       }
5031       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5032              diag::err_omp_unnamed_if_clause)
5033           << (TotalAllowedNum > 1) << Values;
5034     }
5035     for (SourceLocation Loc : NameModifierLoc) {
5036       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5037     }
5038     ErrorFound = true;
5039   }
5040   return ErrorFound;
5041 }
5042 
5043 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
5044                                                    SourceLocation &ELoc,
5045                                                    SourceRange &ERange,
5046                                                    bool AllowArraySection) {
5047   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5048       RefExpr->containsUnexpandedParameterPack())
5049     return std::make_pair(nullptr, true);
5050 
5051   // OpenMP [3.1, C/C++]
5052   //  A list item is a variable name.
5053   // OpenMP  [2.9.3.3, Restrictions, p.1]
5054   //  A variable that is part of another variable (as an array or
5055   //  structure element) cannot appear in a private clause.
5056   RefExpr = RefExpr->IgnoreParens();
5057   enum {
5058     NoArrayExpr = -1,
5059     ArraySubscript = 0,
5060     OMPArraySection = 1
5061   } IsArrayExpr = NoArrayExpr;
5062   if (AllowArraySection) {
5063     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5064       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5065       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5066         Base = TempASE->getBase()->IgnoreParenImpCasts();
5067       RefExpr = Base;
5068       IsArrayExpr = ArraySubscript;
5069     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5070       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5071       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5072         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5073       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5074         Base = TempASE->getBase()->IgnoreParenImpCasts();
5075       RefExpr = Base;
5076       IsArrayExpr = OMPArraySection;
5077     }
5078   }
5079   ELoc = RefExpr->getExprLoc();
5080   ERange = RefExpr->getSourceRange();
5081   RefExpr = RefExpr->IgnoreParenImpCasts();
5082   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5083   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5084   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5085       (S.getCurrentThisType().isNull() || !ME ||
5086        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5087        !isa<FieldDecl>(ME->getMemberDecl()))) {
5088     if (IsArrayExpr != NoArrayExpr) {
5089       S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5090           << IsArrayExpr << ERange;
5091     } else {
5092       S.Diag(ELoc,
5093              AllowArraySection
5094                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5095                  : diag::err_omp_expected_var_name_member_expr)
5096           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5097     }
5098     return std::make_pair(nullptr, false);
5099   }
5100   return std::make_pair(
5101       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5102 }
5103 
5104 namespace {
5105 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5106 /// target regions.
5107 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5108   DSAStackTy *S = nullptr;
5109 
5110 public:
5111   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5112     return S->isUsesAllocatorsDecl(E->getDecl())
5113                .getValueOr(
5114                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5115            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5116   }
5117   bool VisitStmt(const Stmt *S) {
5118     for (const Stmt *Child : S->children()) {
5119       if (Child && Visit(Child))
5120         return true;
5121     }
5122     return false;
5123   }
5124   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5125 };
5126 } // namespace
5127 
5128 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5129                                  ArrayRef<OMPClause *> Clauses) {
5130   assert(!S.CurContext->isDependentContext() &&
5131          "Expected non-dependent context.");
5132   auto AllocateRange =
5133       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5134   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5135   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5136     return isOpenMPPrivate(C->getClauseKind());
5137   });
5138   for (OMPClause *Cl : PrivateRange) {
5139     MutableArrayRef<Expr *>::iterator I, It, Et;
5140     if (Cl->getClauseKind() == OMPC_private) {
5141       auto *PC = cast<OMPPrivateClause>(Cl);
5142       I = PC->private_copies().begin();
5143       It = PC->varlist_begin();
5144       Et = PC->varlist_end();
5145     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5146       auto *PC = cast<OMPFirstprivateClause>(Cl);
5147       I = PC->private_copies().begin();
5148       It = PC->varlist_begin();
5149       Et = PC->varlist_end();
5150     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5151       auto *PC = cast<OMPLastprivateClause>(Cl);
5152       I = PC->private_copies().begin();
5153       It = PC->varlist_begin();
5154       Et = PC->varlist_end();
5155     } else if (Cl->getClauseKind() == OMPC_linear) {
5156       auto *PC = cast<OMPLinearClause>(Cl);
5157       I = PC->privates().begin();
5158       It = PC->varlist_begin();
5159       Et = PC->varlist_end();
5160     } else if (Cl->getClauseKind() == OMPC_reduction) {
5161       auto *PC = cast<OMPReductionClause>(Cl);
5162       I = PC->privates().begin();
5163       It = PC->varlist_begin();
5164       Et = PC->varlist_end();
5165     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5166       auto *PC = cast<OMPTaskReductionClause>(Cl);
5167       I = PC->privates().begin();
5168       It = PC->varlist_begin();
5169       Et = PC->varlist_end();
5170     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5171       auto *PC = cast<OMPInReductionClause>(Cl);
5172       I = PC->privates().begin();
5173       It = PC->varlist_begin();
5174       Et = PC->varlist_end();
5175     } else {
5176       llvm_unreachable("Expected private clause.");
5177     }
5178     for (Expr *E : llvm::make_range(It, Et)) {
5179       if (!*I) {
5180         ++I;
5181         continue;
5182       }
5183       SourceLocation ELoc;
5184       SourceRange ERange;
5185       Expr *SimpleRefExpr = E;
5186       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5187                                 /*AllowArraySection=*/true);
5188       DeclToCopy.try_emplace(Res.first,
5189                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5190       ++I;
5191     }
5192   }
5193   for (OMPClause *C : AllocateRange) {
5194     auto *AC = cast<OMPAllocateClause>(C);
5195     if (S.getLangOpts().OpenMP >= 50 &&
5196         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5197         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5198         AC->getAllocator()) {
5199       Expr *Allocator = AC->getAllocator();
5200       // OpenMP, 2.12.5 target Construct
5201       // Memory allocators that do not appear in a uses_allocators clause cannot
5202       // appear as an allocator in an allocate clause or be used in the target
5203       // region unless a requires directive with the dynamic_allocators clause
5204       // is present in the same compilation unit.
5205       AllocatorChecker Checker(Stack);
5206       if (Checker.Visit(Allocator))
5207         S.Diag(Allocator->getExprLoc(),
5208                diag::err_omp_allocator_not_in_uses_allocators)
5209             << Allocator->getSourceRange();
5210     }
5211     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5212         getAllocatorKind(S, Stack, AC->getAllocator());
5213     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5214     // For task, taskloop or target directives, allocation requests to memory
5215     // allocators with the trait access set to thread result in unspecified
5216     // behavior.
5217     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5218         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5219          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5220       S.Diag(AC->getAllocator()->getExprLoc(),
5221              diag::warn_omp_allocate_thread_on_task_target_directive)
5222           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5223     }
5224     for (Expr *E : AC->varlists()) {
5225       SourceLocation ELoc;
5226       SourceRange ERange;
5227       Expr *SimpleRefExpr = E;
5228       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5229       ValueDecl *VD = Res.first;
5230       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5231       if (!isOpenMPPrivate(Data.CKind)) {
5232         S.Diag(E->getExprLoc(),
5233                diag::err_omp_expected_private_copy_for_allocate);
5234         continue;
5235       }
5236       VarDecl *PrivateVD = DeclToCopy[VD];
5237       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5238                                             AllocatorKind, AC->getAllocator()))
5239         continue;
5240       // Placeholder until allocate clause supports align modifier.
5241       Expr *Alignment = nullptr;
5242       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5243                                 Alignment, E->getSourceRange());
5244     }
5245   }
5246 }
5247 
5248 namespace {
5249 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5250 ///
5251 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5252 /// context. DeclRefExpr used inside the new context are changed to refer to the
5253 /// captured variable instead.
5254 class CaptureVars : public TreeTransform<CaptureVars> {
5255   using BaseTransform = TreeTransform<CaptureVars>;
5256 
5257 public:
5258   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5259 
5260   bool AlwaysRebuild() { return true; }
5261 };
5262 } // namespace
5263 
5264 static VarDecl *precomputeExpr(Sema &Actions,
5265                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5266                                StringRef Name) {
5267   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5268   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5269                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5270   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5271       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5272   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5273   BodyStmts.push_back(NewDeclStmt);
5274   return NewVar;
5275 }
5276 
5277 /// Create a closure that computes the number of iterations of a loop.
5278 ///
5279 /// \param Actions   The Sema object.
5280 /// \param LogicalTy Type for the logical iteration number.
5281 /// \param Rel       Comparison operator of the loop condition.
5282 /// \param StartExpr Value of the loop counter at the first iteration.
5283 /// \param StopExpr  Expression the loop counter is compared against in the loop
5284 /// condition. \param StepExpr      Amount of increment after each iteration.
5285 ///
5286 /// \return Closure (CapturedStmt) of the distance calculation.
5287 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5288                                        BinaryOperator::Opcode Rel,
5289                                        Expr *StartExpr, Expr *StopExpr,
5290                                        Expr *StepExpr) {
5291   ASTContext &Ctx = Actions.getASTContext();
5292   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5293 
5294   // Captured regions currently don't support return values, we use an
5295   // out-parameter instead. All inputs are implicit captures.
5296   // TODO: Instead of capturing each DeclRefExpr occurring in
5297   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5298   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5299   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5300                                           {StringRef(), QualType()}};
5301   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5302 
5303   Stmt *Body;
5304   {
5305     Sema::CompoundScopeRAII CompoundScope(Actions);
5306     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5307 
5308     // Get the LValue expression for the result.
5309     ImplicitParamDecl *DistParam = CS->getParam(0);
5310     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5311         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5312 
5313     SmallVector<Stmt *, 4> BodyStmts;
5314 
5315     // Capture all referenced variable references.
5316     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5317     // CapturedStmt, we could compute them before and capture the result, to be
5318     // used jointly with the LoopVar function.
5319     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5320     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5321     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5322     auto BuildVarRef = [&](VarDecl *VD) {
5323       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5324     };
5325 
5326     IntegerLiteral *Zero = IntegerLiteral::Create(
5327         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5328     Expr *Dist;
5329     if (Rel == BO_NE) {
5330       // When using a != comparison, the increment can be +1 or -1. This can be
5331       // dynamic at runtime, so we need to check for the direction.
5332       Expr *IsNegStep = AssertSuccess(
5333           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5334 
5335       // Positive increment.
5336       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5337           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5338       ForwardRange = AssertSuccess(
5339           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5340       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5341           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5342 
5343       // Negative increment.
5344       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5345           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5346       BackwardRange = AssertSuccess(
5347           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5348       Expr *NegIncAmount = AssertSuccess(
5349           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5350       Expr *BackwardDist = AssertSuccess(
5351           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5352 
5353       // Use the appropriate case.
5354       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5355           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5356     } else {
5357       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5358              "Expected one of these relational operators");
5359 
5360       // We can derive the direction from any other comparison operator. It is
5361       // non well-formed OpenMP if Step increments/decrements in the other
5362       // directions. Whether at least the first iteration passes the loop
5363       // condition.
5364       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5365           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5366 
5367       // Compute the range between first and last counter value.
5368       Expr *Range;
5369       if (Rel == BO_GE || Rel == BO_GT)
5370         Range = AssertSuccess(Actions.BuildBinOp(
5371             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5372       else
5373         Range = AssertSuccess(Actions.BuildBinOp(
5374             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5375 
5376       // Ensure unsigned range space.
5377       Range =
5378           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5379 
5380       if (Rel == BO_LE || Rel == BO_GE) {
5381         // Add one to the range if the relational operator is inclusive.
5382         Range = AssertSuccess(Actions.BuildBinOp(
5383             nullptr, {}, BO_Add, Range,
5384             Actions.ActOnIntegerConstant(SourceLocation(), 1).get()));
5385       }
5386 
5387       // Divide by the absolute step amount.
5388       Expr *Divisor = BuildVarRef(NewStep);
5389       if (Rel == BO_GE || Rel == BO_GT)
5390         Divisor =
5391             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5392       Dist = AssertSuccess(
5393           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5394 
5395       // If there is not at least one iteration, the range contains garbage. Fix
5396       // to zero in this case.
5397       Dist = AssertSuccess(
5398           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5399     }
5400 
5401     // Assign the result to the out-parameter.
5402     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5403         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5404     BodyStmts.push_back(ResultAssign);
5405 
5406     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5407   }
5408 
5409   return cast<CapturedStmt>(
5410       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5411 }
5412 
5413 /// Create a closure that computes the loop variable from the logical iteration
5414 /// number.
5415 ///
5416 /// \param Actions   The Sema object.
5417 /// \param LoopVarTy Type for the loop variable used for result value.
5418 /// \param LogicalTy Type for the logical iteration number.
5419 /// \param StartExpr Value of the loop counter at the first iteration.
5420 /// \param Step      Amount of increment after each iteration.
5421 /// \param Deref     Whether the loop variable is a dereference of the loop
5422 /// counter variable.
5423 ///
5424 /// \return Closure (CapturedStmt) of the loop value calculation.
5425 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5426                                       QualType LogicalTy,
5427                                       DeclRefExpr *StartExpr, Expr *Step,
5428                                       bool Deref) {
5429   ASTContext &Ctx = Actions.getASTContext();
5430 
5431   // Pass the result as an out-parameter. Passing as return value would require
5432   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5433   // invoke a copy constructor.
5434   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5435   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5436                                           {"Logical", LogicalTy},
5437                                           {StringRef(), QualType()}};
5438   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5439 
5440   // Capture the initial iterator which represents the LoopVar value at the
5441   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5442   // it in every iteration, capture it by value before it is modified.
5443   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5444   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5445                                             Sema::TryCapture_ExplicitByVal, {});
5446   (void)Invalid;
5447   assert(!Invalid && "Expecting capture-by-value to work.");
5448 
5449   Expr *Body;
5450   {
5451     Sema::CompoundScopeRAII CompoundScope(Actions);
5452     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5453 
5454     ImplicitParamDecl *TargetParam = CS->getParam(0);
5455     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5456         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5457     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5458     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5459         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5460 
5461     // Capture the Start expression.
5462     CaptureVars Recap(Actions);
5463     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5464     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5465 
5466     Expr *Skip = AssertSuccess(
5467         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5468     // TODO: Explicitly cast to the iterator's difference_type instead of
5469     // relying on implicit conversion.
5470     Expr *Advanced =
5471         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5472 
5473     if (Deref) {
5474       // For range-based for-loops convert the loop counter value to a concrete
5475       // loop variable value by dereferencing the iterator.
5476       Advanced =
5477           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5478     }
5479 
5480     // Assign the result to the output parameter.
5481     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5482                                             BO_Assign, TargetRef, Advanced));
5483   }
5484   return cast<CapturedStmt>(
5485       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5486 }
5487 
5488 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5489   ASTContext &Ctx = getASTContext();
5490 
5491   // Extract the common elements of ForStmt and CXXForRangeStmt:
5492   // Loop variable, repeat condition, increment
5493   Expr *Cond, *Inc;
5494   VarDecl *LIVDecl, *LUVDecl;
5495   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5496     Stmt *Init = For->getInit();
5497     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5498       // For statement declares loop variable.
5499       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5500     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5501       // For statement reuses variable.
5502       assert(LCAssign->getOpcode() == BO_Assign &&
5503              "init part must be a loop variable assignment");
5504       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5505       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5506     } else
5507       llvm_unreachable("Cannot determine loop variable");
5508     LUVDecl = LIVDecl;
5509 
5510     Cond = For->getCond();
5511     Inc = For->getInc();
5512   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5513     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5514     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5515     LUVDecl = RangeFor->getLoopVariable();
5516 
5517     Cond = RangeFor->getCond();
5518     Inc = RangeFor->getInc();
5519   } else
5520     llvm_unreachable("unhandled kind of loop");
5521 
5522   QualType CounterTy = LIVDecl->getType();
5523   QualType LVTy = LUVDecl->getType();
5524 
5525   // Analyze the loop condition.
5526   Expr *LHS, *RHS;
5527   BinaryOperator::Opcode CondRel;
5528   Cond = Cond->IgnoreImplicit();
5529   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5530     LHS = CondBinExpr->getLHS();
5531     RHS = CondBinExpr->getRHS();
5532     CondRel = CondBinExpr->getOpcode();
5533   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5534     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5535     LHS = CondCXXOp->getArg(0);
5536     RHS = CondCXXOp->getArg(1);
5537     switch (CondCXXOp->getOperator()) {
5538     case OO_ExclaimEqual:
5539       CondRel = BO_NE;
5540       break;
5541     case OO_Less:
5542       CondRel = BO_LT;
5543       break;
5544     case OO_LessEqual:
5545       CondRel = BO_LE;
5546       break;
5547     case OO_Greater:
5548       CondRel = BO_GT;
5549       break;
5550     case OO_GreaterEqual:
5551       CondRel = BO_GE;
5552       break;
5553     default:
5554       llvm_unreachable("unexpected iterator operator");
5555     }
5556   } else
5557     llvm_unreachable("unexpected loop condition");
5558 
5559   // Normalize such that the loop counter is on the LHS.
5560   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5561       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5562     std::swap(LHS, RHS);
5563     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5564   }
5565   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5566 
5567   // Decide the bit width for the logical iteration counter. By default use the
5568   // unsigned ptrdiff_t integer size (for iterators and pointers).
5569   // TODO: For iterators, use iterator::difference_type,
5570   // std::iterator_traits<>::difference_type or decltype(it - end).
5571   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5572   if (CounterTy->isIntegerType()) {
5573     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5574     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5575   }
5576 
5577   // Analyze the loop increment.
5578   Expr *Step;
5579   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5580     int Direction;
5581     switch (IncUn->getOpcode()) {
5582     case UO_PreInc:
5583     case UO_PostInc:
5584       Direction = 1;
5585       break;
5586     case UO_PreDec:
5587     case UO_PostDec:
5588       Direction = -1;
5589       break;
5590     default:
5591       llvm_unreachable("unhandled unary increment operator");
5592     }
5593     Step = IntegerLiteral::Create(
5594         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5595   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5596     if (IncBin->getOpcode() == BO_AddAssign) {
5597       Step = IncBin->getRHS();
5598     } else if (IncBin->getOpcode() == BO_SubAssign) {
5599       Step =
5600           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5601     } else
5602       llvm_unreachable("unhandled binary increment operator");
5603   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5604     switch (CondCXXOp->getOperator()) {
5605     case OO_PlusPlus:
5606       Step = IntegerLiteral::Create(
5607           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5608       break;
5609     case OO_MinusMinus:
5610       Step = IntegerLiteral::Create(
5611           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5612       break;
5613     case OO_PlusEqual:
5614       Step = CondCXXOp->getArg(1);
5615       break;
5616     case OO_MinusEqual:
5617       Step = AssertSuccess(
5618           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5619       break;
5620     default:
5621       llvm_unreachable("unhandled overloaded increment operator");
5622     }
5623   } else
5624     llvm_unreachable("unknown increment expression");
5625 
5626   CapturedStmt *DistanceFunc =
5627       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5628   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5629       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5630   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5631                                         {}, nullptr, nullptr, {}, nullptr);
5632   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5633                                   LoopVarFunc, LVRef);
5634 }
5635 
5636 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
5637   // Handle a literal loop.
5638   if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
5639     return ActOnOpenMPCanonicalLoop(AStmt);
5640 
5641   // If not a literal loop, it must be the result of a loop transformation.
5642   OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
5643   assert(
5644       isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
5645       "Loop transformation directive expected");
5646   return LoopTransform;
5647 }
5648 
5649 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5650                                             CXXScopeSpec &MapperIdScopeSpec,
5651                                             const DeclarationNameInfo &MapperId,
5652                                             QualType Type,
5653                                             Expr *UnresolvedMapper);
5654 
5655 /// Perform DFS through the structure/class data members trying to find
5656 /// member(s) with user-defined 'default' mapper and generate implicit map
5657 /// clauses for such members with the found 'default' mapper.
5658 static void
5659 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5660                                       SmallVectorImpl<OMPClause *> &Clauses) {
5661   // Check for the deault mapper for data members.
5662   if (S.getLangOpts().OpenMP < 50)
5663     return;
5664   SmallVector<OMPClause *, 4> ImplicitMaps;
5665   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5666     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5667     if (!C)
5668       continue;
5669     SmallVector<Expr *, 4> SubExprs;
5670     auto *MI = C->mapperlist_begin();
5671     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5672          ++I, ++MI) {
5673       // Expression is mapped using mapper - skip it.
5674       if (*MI)
5675         continue;
5676       Expr *E = *I;
5677       // Expression is dependent - skip it, build the mapper when it gets
5678       // instantiated.
5679       if (E->isTypeDependent() || E->isValueDependent() ||
5680           E->containsUnexpandedParameterPack())
5681         continue;
5682       // Array section - need to check for the mapping of the array section
5683       // element.
5684       QualType CanonType = E->getType().getCanonicalType();
5685       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5686         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5687         QualType BaseType =
5688             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5689         QualType ElemType;
5690         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5691           ElemType = ATy->getElementType();
5692         else
5693           ElemType = BaseType->getPointeeType();
5694         CanonType = ElemType;
5695       }
5696 
5697       // DFS over data members in structures/classes.
5698       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5699           1, {CanonType, nullptr});
5700       llvm::DenseMap<const Type *, Expr *> Visited;
5701       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5702           1, {nullptr, 1});
5703       while (!Types.empty()) {
5704         QualType BaseType;
5705         FieldDecl *CurFD;
5706         std::tie(BaseType, CurFD) = Types.pop_back_val();
5707         while (ParentChain.back().second == 0)
5708           ParentChain.pop_back();
5709         --ParentChain.back().second;
5710         if (BaseType.isNull())
5711           continue;
5712         // Only structs/classes are allowed to have mappers.
5713         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5714         if (!RD)
5715           continue;
5716         auto It = Visited.find(BaseType.getTypePtr());
5717         if (It == Visited.end()) {
5718           // Try to find the associated user-defined mapper.
5719           CXXScopeSpec MapperIdScopeSpec;
5720           DeclarationNameInfo DefaultMapperId;
5721           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5722               &S.Context.Idents.get("default")));
5723           DefaultMapperId.setLoc(E->getExprLoc());
5724           ExprResult ER = buildUserDefinedMapperRef(
5725               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5726               BaseType, /*UnresolvedMapper=*/nullptr);
5727           if (ER.isInvalid())
5728             continue;
5729           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5730         }
5731         // Found default mapper.
5732         if (It->second) {
5733           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5734                                                      VK_LValue, OK_Ordinary, E);
5735           OE->setIsUnique(/*V=*/true);
5736           Expr *BaseExpr = OE;
5737           for (const auto &P : ParentChain) {
5738             if (P.first) {
5739               BaseExpr = S.BuildMemberExpr(
5740                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5741                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5742                   DeclAccessPair::make(P.first, P.first->getAccess()),
5743                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5744                   P.first->getType(), VK_LValue, OK_Ordinary);
5745               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5746             }
5747           }
5748           if (CurFD)
5749             BaseExpr = S.BuildMemberExpr(
5750                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5751                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5752                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5753                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5754                 CurFD->getType(), VK_LValue, OK_Ordinary);
5755           SubExprs.push_back(BaseExpr);
5756           continue;
5757         }
5758         // Check for the "default" mapper for data members.
5759         bool FirstIter = true;
5760         for (FieldDecl *FD : RD->fields()) {
5761           if (!FD)
5762             continue;
5763           QualType FieldTy = FD->getType();
5764           if (FieldTy.isNull() ||
5765               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5766             continue;
5767           if (FirstIter) {
5768             FirstIter = false;
5769             ParentChain.emplace_back(CurFD, 1);
5770           } else {
5771             ++ParentChain.back().second;
5772           }
5773           Types.emplace_back(FieldTy, FD);
5774         }
5775       }
5776     }
5777     if (SubExprs.empty())
5778       continue;
5779     CXXScopeSpec MapperIdScopeSpec;
5780     DeclarationNameInfo MapperId;
5781     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5782             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5783             MapperIdScopeSpec, MapperId, C->getMapType(),
5784             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5785             SubExprs, OMPVarListLocTy()))
5786       Clauses.push_back(NewClause);
5787   }
5788 }
5789 
5790 StmtResult Sema::ActOnOpenMPExecutableDirective(
5791     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5792     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5793     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5794   StmtResult Res = StmtError();
5795   OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
5796   if (const OMPBindClause *BC =
5797           OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
5798     BindKind = BC->getBindKind();
5799   // First check CancelRegion which is then used in checkNestingOfRegions.
5800   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5801       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5802                             BindKind, StartLoc))
5803     return StmtError();
5804 
5805   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5806   VarsWithInheritedDSAType VarsWithInheritedDSA;
5807   bool ErrorFound = false;
5808   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5809   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5810       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5811       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5812     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5813 
5814     // Check default data sharing attributes for referenced variables.
5815     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5816     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5817     Stmt *S = AStmt;
5818     while (--ThisCaptureLevel >= 0)
5819       S = cast<CapturedStmt>(S)->getCapturedStmt();
5820     DSAChecker.Visit(S);
5821     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5822         !isOpenMPTaskingDirective(Kind)) {
5823       // Visit subcaptures to generate implicit clauses for captured vars.
5824       auto *CS = cast<CapturedStmt>(AStmt);
5825       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5826       getOpenMPCaptureRegions(CaptureRegions, Kind);
5827       // Ignore outer tasking regions for target directives.
5828       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5829         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5830       DSAChecker.visitSubCaptures(CS);
5831     }
5832     if (DSAChecker.isErrorFound())
5833       return StmtError();
5834     // Generate list of implicitly defined firstprivate variables.
5835     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5836 
5837     SmallVector<Expr *, 4> ImplicitFirstprivates(
5838         DSAChecker.getImplicitFirstprivate().begin(),
5839         DSAChecker.getImplicitFirstprivate().end());
5840     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5841     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5842     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5843         ImplicitMapModifiers[DefaultmapKindNum];
5844     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5845         ImplicitMapModifiersLoc[DefaultmapKindNum];
5846     // Get the original location of present modifier from Defaultmap clause.
5847     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5848     for (OMPClause *C : Clauses) {
5849       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5850         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5851           PresentModifierLocs[DMC->getDefaultmapKind()] =
5852               DMC->getDefaultmapModifierLoc();
5853     }
5854     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5855       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5856       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5857         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5858             Kind, static_cast<OpenMPMapClauseKind>(I));
5859         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5860       }
5861       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5862           DSAChecker.getImplicitMapModifier(Kind);
5863       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5864                                       ImplicitModifier.end());
5865       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5866                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5867     }
5868     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5869     for (OMPClause *C : Clauses) {
5870       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5871         for (Expr *E : IRC->taskgroup_descriptors())
5872           if (E)
5873             ImplicitFirstprivates.emplace_back(E);
5874       }
5875       // OpenMP 5.0, 2.10.1 task Construct
5876       // [detach clause]... The event-handle will be considered as if it was
5877       // specified on a firstprivate clause.
5878       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5879         ImplicitFirstprivates.push_back(DC->getEventHandler());
5880     }
5881     if (!ImplicitFirstprivates.empty()) {
5882       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5883               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5884               SourceLocation())) {
5885         ClausesWithImplicit.push_back(Implicit);
5886         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5887                      ImplicitFirstprivates.size();
5888       } else {
5889         ErrorFound = true;
5890       }
5891     }
5892     // OpenMP 5.0 [2.19.7]
5893     // If a list item appears in a reduction, lastprivate or linear
5894     // clause on a combined target construct then it is treated as
5895     // if it also appears in a map clause with a map-type of tofrom
5896     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5897         isOpenMPTargetExecutionDirective(Kind)) {
5898       SmallVector<Expr *, 4> ImplicitExprs;
5899       for (OMPClause *C : Clauses) {
5900         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5901           for (Expr *E : RC->varlists())
5902             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5903               ImplicitExprs.emplace_back(E);
5904       }
5905       if (!ImplicitExprs.empty()) {
5906         ArrayRef<Expr *> Exprs = ImplicitExprs;
5907         CXXScopeSpec MapperIdScopeSpec;
5908         DeclarationNameInfo MapperId;
5909         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5910                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
5911                 MapperId, OMPC_MAP_tofrom,
5912                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5913                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
5914           ClausesWithImplicit.emplace_back(Implicit);
5915       }
5916     }
5917     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5918       int ClauseKindCnt = -1;
5919       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5920         ++ClauseKindCnt;
5921         if (ImplicitMap.empty())
5922           continue;
5923         CXXScopeSpec MapperIdScopeSpec;
5924         DeclarationNameInfo MapperId;
5925         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5926         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5927                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5928                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5929                 SourceLocation(), SourceLocation(), ImplicitMap,
5930                 OMPVarListLocTy())) {
5931           ClausesWithImplicit.emplace_back(Implicit);
5932           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5933                         ImplicitMap.size();
5934         } else {
5935           ErrorFound = true;
5936         }
5937       }
5938     }
5939     // Build expressions for implicit maps of data members with 'default'
5940     // mappers.
5941     if (LangOpts.OpenMP >= 50)
5942       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5943                                             ClausesWithImplicit);
5944   }
5945 
5946   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5947   switch (Kind) {
5948   case OMPD_parallel:
5949     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5950                                        EndLoc);
5951     AllowedNameModifiers.push_back(OMPD_parallel);
5952     break;
5953   case OMPD_simd:
5954     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5955                                    VarsWithInheritedDSA);
5956     if (LangOpts.OpenMP >= 50)
5957       AllowedNameModifiers.push_back(OMPD_simd);
5958     break;
5959   case OMPD_tile:
5960     Res =
5961         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5962     break;
5963   case OMPD_unroll:
5964     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
5965                                      EndLoc);
5966     break;
5967   case OMPD_for:
5968     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5969                                   VarsWithInheritedDSA);
5970     break;
5971   case OMPD_for_simd:
5972     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5973                                       EndLoc, VarsWithInheritedDSA);
5974     if (LangOpts.OpenMP >= 50)
5975       AllowedNameModifiers.push_back(OMPD_simd);
5976     break;
5977   case OMPD_sections:
5978     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5979                                        EndLoc);
5980     break;
5981   case OMPD_section:
5982     assert(ClausesWithImplicit.empty() &&
5983            "No clauses are allowed for 'omp section' directive");
5984     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5985     break;
5986   case OMPD_single:
5987     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5988                                      EndLoc);
5989     break;
5990   case OMPD_master:
5991     assert(ClausesWithImplicit.empty() &&
5992            "No clauses are allowed for 'omp master' directive");
5993     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5994     break;
5995   case OMPD_masked:
5996     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
5997                                      EndLoc);
5998     break;
5999   case OMPD_critical:
6000     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
6001                                        StartLoc, EndLoc);
6002     break;
6003   case OMPD_parallel_for:
6004     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
6005                                           EndLoc, VarsWithInheritedDSA);
6006     AllowedNameModifiers.push_back(OMPD_parallel);
6007     break;
6008   case OMPD_parallel_for_simd:
6009     Res = ActOnOpenMPParallelForSimdDirective(
6010         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6011     AllowedNameModifiers.push_back(OMPD_parallel);
6012     if (LangOpts.OpenMP >= 50)
6013       AllowedNameModifiers.push_back(OMPD_simd);
6014     break;
6015   case OMPD_parallel_master:
6016     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
6017                                              StartLoc, EndLoc);
6018     AllowedNameModifiers.push_back(OMPD_parallel);
6019     break;
6020   case OMPD_parallel_sections:
6021     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
6022                                                StartLoc, EndLoc);
6023     AllowedNameModifiers.push_back(OMPD_parallel);
6024     break;
6025   case OMPD_task:
6026     Res =
6027         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6028     AllowedNameModifiers.push_back(OMPD_task);
6029     break;
6030   case OMPD_taskyield:
6031     assert(ClausesWithImplicit.empty() &&
6032            "No clauses are allowed for 'omp taskyield' directive");
6033     assert(AStmt == nullptr &&
6034            "No associated statement allowed for 'omp taskyield' directive");
6035     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
6036     break;
6037   case OMPD_barrier:
6038     assert(ClausesWithImplicit.empty() &&
6039            "No clauses are allowed for 'omp barrier' directive");
6040     assert(AStmt == nullptr &&
6041            "No associated statement allowed for 'omp barrier' directive");
6042     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
6043     break;
6044   case OMPD_taskwait:
6045     assert(AStmt == nullptr &&
6046            "No associated statement allowed for 'omp taskwait' directive");
6047     Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
6048     break;
6049   case OMPD_taskgroup:
6050     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
6051                                         EndLoc);
6052     break;
6053   case OMPD_flush:
6054     assert(AStmt == nullptr &&
6055            "No associated statement allowed for 'omp flush' directive");
6056     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
6057     break;
6058   case OMPD_depobj:
6059     assert(AStmt == nullptr &&
6060            "No associated statement allowed for 'omp depobj' directive");
6061     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
6062     break;
6063   case OMPD_scan:
6064     assert(AStmt == nullptr &&
6065            "No associated statement allowed for 'omp scan' directive");
6066     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
6067     break;
6068   case OMPD_ordered:
6069     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
6070                                       EndLoc);
6071     break;
6072   case OMPD_atomic:
6073     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
6074                                      EndLoc);
6075     break;
6076   case OMPD_teams:
6077     Res =
6078         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6079     break;
6080   case OMPD_target:
6081     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6082                                      EndLoc);
6083     AllowedNameModifiers.push_back(OMPD_target);
6084     break;
6085   case OMPD_target_parallel:
6086     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6087                                              StartLoc, EndLoc);
6088     AllowedNameModifiers.push_back(OMPD_target);
6089     AllowedNameModifiers.push_back(OMPD_parallel);
6090     break;
6091   case OMPD_target_parallel_for:
6092     Res = ActOnOpenMPTargetParallelForDirective(
6093         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6094     AllowedNameModifiers.push_back(OMPD_target);
6095     AllowedNameModifiers.push_back(OMPD_parallel);
6096     break;
6097   case OMPD_cancellation_point:
6098     assert(ClausesWithImplicit.empty() &&
6099            "No clauses are allowed for 'omp cancellation point' directive");
6100     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6101                                "cancellation point' directive");
6102     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6103     break;
6104   case OMPD_cancel:
6105     assert(AStmt == nullptr &&
6106            "No associated statement allowed for 'omp cancel' directive");
6107     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6108                                      CancelRegion);
6109     AllowedNameModifiers.push_back(OMPD_cancel);
6110     break;
6111   case OMPD_target_data:
6112     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6113                                          EndLoc);
6114     AllowedNameModifiers.push_back(OMPD_target_data);
6115     break;
6116   case OMPD_target_enter_data:
6117     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6118                                               EndLoc, AStmt);
6119     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6120     break;
6121   case OMPD_target_exit_data:
6122     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6123                                              EndLoc, AStmt);
6124     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6125     break;
6126   case OMPD_taskloop:
6127     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6128                                        EndLoc, VarsWithInheritedDSA);
6129     AllowedNameModifiers.push_back(OMPD_taskloop);
6130     break;
6131   case OMPD_taskloop_simd:
6132     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6133                                            EndLoc, VarsWithInheritedDSA);
6134     AllowedNameModifiers.push_back(OMPD_taskloop);
6135     if (LangOpts.OpenMP >= 50)
6136       AllowedNameModifiers.push_back(OMPD_simd);
6137     break;
6138   case OMPD_master_taskloop:
6139     Res = ActOnOpenMPMasterTaskLoopDirective(
6140         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6141     AllowedNameModifiers.push_back(OMPD_taskloop);
6142     break;
6143   case OMPD_master_taskloop_simd:
6144     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6145         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6146     AllowedNameModifiers.push_back(OMPD_taskloop);
6147     if (LangOpts.OpenMP >= 50)
6148       AllowedNameModifiers.push_back(OMPD_simd);
6149     break;
6150   case OMPD_parallel_master_taskloop:
6151     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6152         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6153     AllowedNameModifiers.push_back(OMPD_taskloop);
6154     AllowedNameModifiers.push_back(OMPD_parallel);
6155     break;
6156   case OMPD_parallel_master_taskloop_simd:
6157     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6158         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6159     AllowedNameModifiers.push_back(OMPD_taskloop);
6160     AllowedNameModifiers.push_back(OMPD_parallel);
6161     if (LangOpts.OpenMP >= 50)
6162       AllowedNameModifiers.push_back(OMPD_simd);
6163     break;
6164   case OMPD_distribute:
6165     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6166                                          EndLoc, VarsWithInheritedDSA);
6167     break;
6168   case OMPD_target_update:
6169     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6170                                            EndLoc, AStmt);
6171     AllowedNameModifiers.push_back(OMPD_target_update);
6172     break;
6173   case OMPD_distribute_parallel_for:
6174     Res = ActOnOpenMPDistributeParallelForDirective(
6175         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6176     AllowedNameModifiers.push_back(OMPD_parallel);
6177     break;
6178   case OMPD_distribute_parallel_for_simd:
6179     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6180         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6181     AllowedNameModifiers.push_back(OMPD_parallel);
6182     if (LangOpts.OpenMP >= 50)
6183       AllowedNameModifiers.push_back(OMPD_simd);
6184     break;
6185   case OMPD_distribute_simd:
6186     Res = ActOnOpenMPDistributeSimdDirective(
6187         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6188     if (LangOpts.OpenMP >= 50)
6189       AllowedNameModifiers.push_back(OMPD_simd);
6190     break;
6191   case OMPD_target_parallel_for_simd:
6192     Res = ActOnOpenMPTargetParallelForSimdDirective(
6193         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6194     AllowedNameModifiers.push_back(OMPD_target);
6195     AllowedNameModifiers.push_back(OMPD_parallel);
6196     if (LangOpts.OpenMP >= 50)
6197       AllowedNameModifiers.push_back(OMPD_simd);
6198     break;
6199   case OMPD_target_simd:
6200     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6201                                          EndLoc, VarsWithInheritedDSA);
6202     AllowedNameModifiers.push_back(OMPD_target);
6203     if (LangOpts.OpenMP >= 50)
6204       AllowedNameModifiers.push_back(OMPD_simd);
6205     break;
6206   case OMPD_teams_distribute:
6207     Res = ActOnOpenMPTeamsDistributeDirective(
6208         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6209     break;
6210   case OMPD_teams_distribute_simd:
6211     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6212         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6213     if (LangOpts.OpenMP >= 50)
6214       AllowedNameModifiers.push_back(OMPD_simd);
6215     break;
6216   case OMPD_teams_distribute_parallel_for_simd:
6217     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6218         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6219     AllowedNameModifiers.push_back(OMPD_parallel);
6220     if (LangOpts.OpenMP >= 50)
6221       AllowedNameModifiers.push_back(OMPD_simd);
6222     break;
6223   case OMPD_teams_distribute_parallel_for:
6224     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6225         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6226     AllowedNameModifiers.push_back(OMPD_parallel);
6227     break;
6228   case OMPD_target_teams:
6229     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6230                                           EndLoc);
6231     AllowedNameModifiers.push_back(OMPD_target);
6232     break;
6233   case OMPD_target_teams_distribute:
6234     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6235         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6236     AllowedNameModifiers.push_back(OMPD_target);
6237     break;
6238   case OMPD_target_teams_distribute_parallel_for:
6239     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6240         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6241     AllowedNameModifiers.push_back(OMPD_target);
6242     AllowedNameModifiers.push_back(OMPD_parallel);
6243     break;
6244   case OMPD_target_teams_distribute_parallel_for_simd:
6245     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6246         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6247     AllowedNameModifiers.push_back(OMPD_target);
6248     AllowedNameModifiers.push_back(OMPD_parallel);
6249     if (LangOpts.OpenMP >= 50)
6250       AllowedNameModifiers.push_back(OMPD_simd);
6251     break;
6252   case OMPD_target_teams_distribute_simd:
6253     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6254         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6255     AllowedNameModifiers.push_back(OMPD_target);
6256     if (LangOpts.OpenMP >= 50)
6257       AllowedNameModifiers.push_back(OMPD_simd);
6258     break;
6259   case OMPD_interop:
6260     assert(AStmt == nullptr &&
6261            "No associated statement allowed for 'omp interop' directive");
6262     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6263     break;
6264   case OMPD_dispatch:
6265     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6266                                        EndLoc);
6267     break;
6268   case OMPD_loop:
6269     Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6270                                           EndLoc, VarsWithInheritedDSA);
6271     break;
6272   case OMPD_declare_target:
6273   case OMPD_end_declare_target:
6274   case OMPD_threadprivate:
6275   case OMPD_allocate:
6276   case OMPD_declare_reduction:
6277   case OMPD_declare_mapper:
6278   case OMPD_declare_simd:
6279   case OMPD_requires:
6280   case OMPD_declare_variant:
6281   case OMPD_begin_declare_variant:
6282   case OMPD_end_declare_variant:
6283     llvm_unreachable("OpenMP Directive is not allowed");
6284   case OMPD_unknown:
6285   default:
6286     llvm_unreachable("Unknown OpenMP directive");
6287   }
6288 
6289   ErrorFound = Res.isInvalid() || ErrorFound;
6290 
6291   // Check variables in the clauses if default(none) or
6292   // default(firstprivate) was specified.
6293   if (DSAStack->getDefaultDSA() == DSA_none ||
6294       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6295     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6296     for (OMPClause *C : Clauses) {
6297       switch (C->getClauseKind()) {
6298       case OMPC_num_threads:
6299       case OMPC_dist_schedule:
6300         // Do not analyse if no parent teams directive.
6301         if (isOpenMPTeamsDirective(Kind))
6302           break;
6303         continue;
6304       case OMPC_if:
6305         if (isOpenMPTeamsDirective(Kind) &&
6306             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6307           break;
6308         if (isOpenMPParallelDirective(Kind) &&
6309             isOpenMPTaskLoopDirective(Kind) &&
6310             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6311           break;
6312         continue;
6313       case OMPC_schedule:
6314       case OMPC_detach:
6315         break;
6316       case OMPC_grainsize:
6317       case OMPC_num_tasks:
6318       case OMPC_final:
6319       case OMPC_priority:
6320       case OMPC_novariants:
6321       case OMPC_nocontext:
6322         // Do not analyze if no parent parallel directive.
6323         if (isOpenMPParallelDirective(Kind))
6324           break;
6325         continue;
6326       case OMPC_ordered:
6327       case OMPC_device:
6328       case OMPC_num_teams:
6329       case OMPC_thread_limit:
6330       case OMPC_hint:
6331       case OMPC_collapse:
6332       case OMPC_safelen:
6333       case OMPC_simdlen:
6334       case OMPC_sizes:
6335       case OMPC_default:
6336       case OMPC_proc_bind:
6337       case OMPC_private:
6338       case OMPC_firstprivate:
6339       case OMPC_lastprivate:
6340       case OMPC_shared:
6341       case OMPC_reduction:
6342       case OMPC_task_reduction:
6343       case OMPC_in_reduction:
6344       case OMPC_linear:
6345       case OMPC_aligned:
6346       case OMPC_copyin:
6347       case OMPC_copyprivate:
6348       case OMPC_nowait:
6349       case OMPC_untied:
6350       case OMPC_mergeable:
6351       case OMPC_allocate:
6352       case OMPC_read:
6353       case OMPC_write:
6354       case OMPC_update:
6355       case OMPC_capture:
6356       case OMPC_seq_cst:
6357       case OMPC_acq_rel:
6358       case OMPC_acquire:
6359       case OMPC_release:
6360       case OMPC_relaxed:
6361       case OMPC_depend:
6362       case OMPC_threads:
6363       case OMPC_simd:
6364       case OMPC_map:
6365       case OMPC_nogroup:
6366       case OMPC_defaultmap:
6367       case OMPC_to:
6368       case OMPC_from:
6369       case OMPC_use_device_ptr:
6370       case OMPC_use_device_addr:
6371       case OMPC_is_device_ptr:
6372       case OMPC_nontemporal:
6373       case OMPC_order:
6374       case OMPC_destroy:
6375       case OMPC_inclusive:
6376       case OMPC_exclusive:
6377       case OMPC_uses_allocators:
6378       case OMPC_affinity:
6379       case OMPC_bind:
6380         continue;
6381       case OMPC_allocator:
6382       case OMPC_flush:
6383       case OMPC_depobj:
6384       case OMPC_threadprivate:
6385       case OMPC_uniform:
6386       case OMPC_unknown:
6387       case OMPC_unified_address:
6388       case OMPC_unified_shared_memory:
6389       case OMPC_reverse_offload:
6390       case OMPC_dynamic_allocators:
6391       case OMPC_atomic_default_mem_order:
6392       case OMPC_device_type:
6393       case OMPC_match:
6394       case OMPC_when:
6395       default:
6396         llvm_unreachable("Unexpected clause");
6397       }
6398       for (Stmt *CC : C->children()) {
6399         if (CC)
6400           DSAChecker.Visit(CC);
6401       }
6402     }
6403     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6404       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6405   }
6406   for (const auto &P : VarsWithInheritedDSA) {
6407     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6408       continue;
6409     ErrorFound = true;
6410     if (DSAStack->getDefaultDSA() == DSA_none ||
6411         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6412       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6413           << P.first << P.second->getSourceRange();
6414       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6415     } else if (getLangOpts().OpenMP >= 50) {
6416       Diag(P.second->getExprLoc(),
6417            diag::err_omp_defaultmap_no_attr_for_variable)
6418           << P.first << P.second->getSourceRange();
6419       Diag(DSAStack->getDefaultDSALocation(),
6420            diag::note_omp_defaultmap_attr_none);
6421     }
6422   }
6423 
6424   if (!AllowedNameModifiers.empty())
6425     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6426                  ErrorFound;
6427 
6428   if (ErrorFound)
6429     return StmtError();
6430 
6431   if (!CurContext->isDependentContext() &&
6432       isOpenMPTargetExecutionDirective(Kind) &&
6433       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6434         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6435         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6436         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6437     // Register target to DSA Stack.
6438     DSAStack->addTargetDirLocation(StartLoc);
6439   }
6440 
6441   return Res;
6442 }
6443 
6444 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6445     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6446     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6447     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6448     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6449   assert(Aligneds.size() == Alignments.size());
6450   assert(Linears.size() == LinModifiers.size());
6451   assert(Linears.size() == Steps.size());
6452   if (!DG || DG.get().isNull())
6453     return DeclGroupPtrTy();
6454 
6455   const int SimdId = 0;
6456   if (!DG.get().isSingleDecl()) {
6457     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6458         << SimdId;
6459     return DG;
6460   }
6461   Decl *ADecl = DG.get().getSingleDecl();
6462   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6463     ADecl = FTD->getTemplatedDecl();
6464 
6465   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6466   if (!FD) {
6467     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6468     return DeclGroupPtrTy();
6469   }
6470 
6471   // OpenMP [2.8.2, declare simd construct, Description]
6472   // The parameter of the simdlen clause must be a constant positive integer
6473   // expression.
6474   ExprResult SL;
6475   if (Simdlen)
6476     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6477   // OpenMP [2.8.2, declare simd construct, Description]
6478   // The special this pointer can be used as if was one of the arguments to the
6479   // function in any of the linear, aligned, or uniform clauses.
6480   // The uniform clause declares one or more arguments to have an invariant
6481   // value for all concurrent invocations of the function in the execution of a
6482   // single SIMD loop.
6483   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6484   const Expr *UniformedLinearThis = nullptr;
6485   for (const Expr *E : Uniforms) {
6486     E = E->IgnoreParenImpCasts();
6487     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6488       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6489         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6490             FD->getParamDecl(PVD->getFunctionScopeIndex())
6491                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6492           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6493           continue;
6494         }
6495     if (isa<CXXThisExpr>(E)) {
6496       UniformedLinearThis = E;
6497       continue;
6498     }
6499     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6500         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6501   }
6502   // OpenMP [2.8.2, declare simd construct, Description]
6503   // The aligned clause declares that the object to which each list item points
6504   // is aligned to the number of bytes expressed in the optional parameter of
6505   // the aligned clause.
6506   // The special this pointer can be used as if was one of the arguments to the
6507   // function in any of the linear, aligned, or uniform clauses.
6508   // The type of list items appearing in the aligned clause must be array,
6509   // pointer, reference to array, or reference to pointer.
6510   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6511   const Expr *AlignedThis = nullptr;
6512   for (const Expr *E : Aligneds) {
6513     E = E->IgnoreParenImpCasts();
6514     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6515       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6516         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6517         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6518             FD->getParamDecl(PVD->getFunctionScopeIndex())
6519                     ->getCanonicalDecl() == CanonPVD) {
6520           // OpenMP  [2.8.1, simd construct, Restrictions]
6521           // A list-item cannot appear in more than one aligned clause.
6522           if (AlignedArgs.count(CanonPVD) > 0) {
6523             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6524                 << 1 << getOpenMPClauseName(OMPC_aligned)
6525                 << E->getSourceRange();
6526             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6527                  diag::note_omp_explicit_dsa)
6528                 << getOpenMPClauseName(OMPC_aligned);
6529             continue;
6530           }
6531           AlignedArgs[CanonPVD] = E;
6532           QualType QTy = PVD->getType()
6533                              .getNonReferenceType()
6534                              .getUnqualifiedType()
6535                              .getCanonicalType();
6536           const Type *Ty = QTy.getTypePtrOrNull();
6537           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6538             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6539                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6540             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6541           }
6542           continue;
6543         }
6544       }
6545     if (isa<CXXThisExpr>(E)) {
6546       if (AlignedThis) {
6547         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6548             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6549         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6550             << getOpenMPClauseName(OMPC_aligned);
6551       }
6552       AlignedThis = E;
6553       continue;
6554     }
6555     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6556         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6557   }
6558   // The optional parameter of the aligned clause, alignment, must be a constant
6559   // positive integer expression. If no optional parameter is specified,
6560   // implementation-defined default alignments for SIMD instructions on the
6561   // target platforms are assumed.
6562   SmallVector<const Expr *, 4> NewAligns;
6563   for (Expr *E : Alignments) {
6564     ExprResult Align;
6565     if (E)
6566       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6567     NewAligns.push_back(Align.get());
6568   }
6569   // OpenMP [2.8.2, declare simd construct, Description]
6570   // The linear clause declares one or more list items to be private to a SIMD
6571   // lane and to have a linear relationship with respect to the iteration space
6572   // of a loop.
6573   // The special this pointer can be used as if was one of the arguments to the
6574   // function in any of the linear, aligned, or uniform clauses.
6575   // When a linear-step expression is specified in a linear clause it must be
6576   // either a constant integer expression or an integer-typed parameter that is
6577   // specified in a uniform clause on the directive.
6578   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6579   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6580   auto MI = LinModifiers.begin();
6581   for (const Expr *E : Linears) {
6582     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6583     ++MI;
6584     E = E->IgnoreParenImpCasts();
6585     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6586       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6587         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6588         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6589             FD->getParamDecl(PVD->getFunctionScopeIndex())
6590                     ->getCanonicalDecl() == CanonPVD) {
6591           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6592           // A list-item cannot appear in more than one linear clause.
6593           if (LinearArgs.count(CanonPVD) > 0) {
6594             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6595                 << getOpenMPClauseName(OMPC_linear)
6596                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6597             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6598                  diag::note_omp_explicit_dsa)
6599                 << getOpenMPClauseName(OMPC_linear);
6600             continue;
6601           }
6602           // Each argument can appear in at most one uniform or linear clause.
6603           if (UniformedArgs.count(CanonPVD) > 0) {
6604             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6605                 << getOpenMPClauseName(OMPC_linear)
6606                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6607             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6608                  diag::note_omp_explicit_dsa)
6609                 << getOpenMPClauseName(OMPC_uniform);
6610             continue;
6611           }
6612           LinearArgs[CanonPVD] = E;
6613           if (E->isValueDependent() || E->isTypeDependent() ||
6614               E->isInstantiationDependent() ||
6615               E->containsUnexpandedParameterPack())
6616             continue;
6617           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6618                                       PVD->getOriginalType(),
6619                                       /*IsDeclareSimd=*/true);
6620           continue;
6621         }
6622       }
6623     if (isa<CXXThisExpr>(E)) {
6624       if (UniformedLinearThis) {
6625         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6626             << getOpenMPClauseName(OMPC_linear)
6627             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6628             << E->getSourceRange();
6629         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6630             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6631                                                    : OMPC_linear);
6632         continue;
6633       }
6634       UniformedLinearThis = E;
6635       if (E->isValueDependent() || E->isTypeDependent() ||
6636           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6637         continue;
6638       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6639                                   E->getType(), /*IsDeclareSimd=*/true);
6640       continue;
6641     }
6642     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6643         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6644   }
6645   Expr *Step = nullptr;
6646   Expr *NewStep = nullptr;
6647   SmallVector<Expr *, 4> NewSteps;
6648   for (Expr *E : Steps) {
6649     // Skip the same step expression, it was checked already.
6650     if (Step == E || !E) {
6651       NewSteps.push_back(E ? NewStep : nullptr);
6652       continue;
6653     }
6654     Step = E;
6655     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6656       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6657         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6658         if (UniformedArgs.count(CanonPVD) == 0) {
6659           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6660               << Step->getSourceRange();
6661         } else if (E->isValueDependent() || E->isTypeDependent() ||
6662                    E->isInstantiationDependent() ||
6663                    E->containsUnexpandedParameterPack() ||
6664                    CanonPVD->getType()->hasIntegerRepresentation()) {
6665           NewSteps.push_back(Step);
6666         } else {
6667           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6668               << Step->getSourceRange();
6669         }
6670         continue;
6671       }
6672     NewStep = Step;
6673     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6674         !Step->isInstantiationDependent() &&
6675         !Step->containsUnexpandedParameterPack()) {
6676       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6677                     .get();
6678       if (NewStep)
6679         NewStep =
6680             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6681     }
6682     NewSteps.push_back(NewStep);
6683   }
6684   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6685       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6686       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6687       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6688       const_cast<Expr **>(Linears.data()), Linears.size(),
6689       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6690       NewSteps.data(), NewSteps.size(), SR);
6691   ADecl->addAttr(NewAttr);
6692   return DG;
6693 }
6694 
6695 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6696                          QualType NewType) {
6697   assert(NewType->isFunctionProtoType() &&
6698          "Expected function type with prototype.");
6699   assert(FD->getType()->isFunctionNoProtoType() &&
6700          "Expected function with type with no prototype.");
6701   assert(FDWithProto->getType()->isFunctionProtoType() &&
6702          "Expected function with prototype.");
6703   // Synthesize parameters with the same types.
6704   FD->setType(NewType);
6705   SmallVector<ParmVarDecl *, 16> Params;
6706   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6707     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6708                                       SourceLocation(), nullptr, P->getType(),
6709                                       /*TInfo=*/nullptr, SC_None, nullptr);
6710     Param->setScopeInfo(0, Params.size());
6711     Param->setImplicit();
6712     Params.push_back(Param);
6713   }
6714 
6715   FD->setParams(Params);
6716 }
6717 
6718 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6719   if (D->isInvalidDecl())
6720     return;
6721   FunctionDecl *FD = nullptr;
6722   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6723     FD = UTemplDecl->getTemplatedDecl();
6724   else
6725     FD = cast<FunctionDecl>(D);
6726   assert(FD && "Expected a function declaration!");
6727 
6728   // If we are instantiating templates we do *not* apply scoped assumptions but
6729   // only global ones. We apply scoped assumption to the template definition
6730   // though.
6731   if (!inTemplateInstantiation()) {
6732     for (AssumptionAttr *AA : OMPAssumeScoped)
6733       FD->addAttr(AA);
6734   }
6735   for (AssumptionAttr *AA : OMPAssumeGlobal)
6736     FD->addAttr(AA);
6737 }
6738 
6739 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6740     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6741 
6742 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6743     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6744     SmallVectorImpl<FunctionDecl *> &Bases) {
6745   if (!D.getIdentifier())
6746     return;
6747 
6748   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6749 
6750   // Template specialization is an extension, check if we do it.
6751   bool IsTemplated = !TemplateParamLists.empty();
6752   if (IsTemplated &
6753       !DVScope.TI->isExtensionActive(
6754           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6755     return;
6756 
6757   IdentifierInfo *BaseII = D.getIdentifier();
6758   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6759                       LookupOrdinaryName);
6760   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6761 
6762   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6763   QualType FType = TInfo->getType();
6764 
6765   bool IsConstexpr =
6766       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6767   bool IsConsteval =
6768       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6769 
6770   for (auto *Candidate : Lookup) {
6771     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6772     FunctionDecl *UDecl = nullptr;
6773     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
6774       auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
6775       if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
6776         UDecl = FTD->getTemplatedDecl();
6777     } else if (!IsTemplated)
6778       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6779     if (!UDecl)
6780       continue;
6781 
6782     // Don't specialize constexpr/consteval functions with
6783     // non-constexpr/consteval functions.
6784     if (UDecl->isConstexpr() && !IsConstexpr)
6785       continue;
6786     if (UDecl->isConsteval() && !IsConsteval)
6787       continue;
6788 
6789     QualType UDeclTy = UDecl->getType();
6790     if (!UDeclTy->isDependentType()) {
6791       QualType NewType = Context.mergeFunctionTypes(
6792           FType, UDeclTy, /* OfBlockPointer */ false,
6793           /* Unqualified */ false, /* AllowCXX */ true);
6794       if (NewType.isNull())
6795         continue;
6796     }
6797 
6798     // Found a base!
6799     Bases.push_back(UDecl);
6800   }
6801 
6802   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6803       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6804   // If no base was found we create a declaration that we use as base.
6805   if (Bases.empty() && UseImplicitBase) {
6806     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6807     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6808     BaseD->setImplicit(true);
6809     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6810       Bases.push_back(BaseTemplD->getTemplatedDecl());
6811     else
6812       Bases.push_back(cast<FunctionDecl>(BaseD));
6813   }
6814 
6815   std::string MangledName;
6816   MangledName += D.getIdentifier()->getName();
6817   MangledName += getOpenMPVariantManglingSeparatorStr();
6818   MangledName += DVScope.NameSuffix;
6819   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6820 
6821   VariantII.setMangledOpenMPVariantName(true);
6822   D.SetIdentifier(&VariantII, D.getBeginLoc());
6823 }
6824 
6825 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6826     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6827   // Do not mark function as is used to prevent its emission if this is the
6828   // only place where it is used.
6829   EnterExpressionEvaluationContext Unevaluated(
6830       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6831 
6832   FunctionDecl *FD = nullptr;
6833   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6834     FD = UTemplDecl->getTemplatedDecl();
6835   else
6836     FD = cast<FunctionDecl>(D);
6837   auto *VariantFuncRef = DeclRefExpr::Create(
6838       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6839       /* RefersToEnclosingVariableOrCapture */ false,
6840       /* NameLoc */ FD->getLocation(), FD->getType(),
6841       ExprValueKind::VK_PRValue);
6842 
6843   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6844   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6845       Context, VariantFuncRef, DVScope.TI,
6846       /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
6847       /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
6848       /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
6849   for (FunctionDecl *BaseFD : Bases)
6850     BaseFD->addAttr(OMPDeclareVariantA);
6851 }
6852 
6853 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6854                                  SourceLocation LParenLoc,
6855                                  MultiExprArg ArgExprs,
6856                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6857   // The common case is a regular call we do not want to specialize at all. Try
6858   // to make that case fast by bailing early.
6859   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6860   if (!CE)
6861     return Call;
6862 
6863   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6864   if (!CalleeFnDecl)
6865     return Call;
6866 
6867   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6868     return Call;
6869 
6870   ASTContext &Context = getASTContext();
6871   std::function<void(StringRef)> DiagUnknownTrait = [this,
6872                                                      CE](StringRef ISATrait) {
6873     // TODO Track the selector locations in a way that is accessible here to
6874     // improve the diagnostic location.
6875     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6876         << ISATrait;
6877   };
6878   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6879                           getCurFunctionDecl(), DSAStack->getConstructTraits());
6880 
6881   QualType CalleeFnType = CalleeFnDecl->getType();
6882 
6883   SmallVector<Expr *, 4> Exprs;
6884   SmallVector<VariantMatchInfo, 4> VMIs;
6885   while (CalleeFnDecl) {
6886     for (OMPDeclareVariantAttr *A :
6887          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6888       Expr *VariantRef = A->getVariantFuncRef();
6889 
6890       VariantMatchInfo VMI;
6891       OMPTraitInfo &TI = A->getTraitInfo();
6892       TI.getAsVariantMatchInfo(Context, VMI);
6893       if (!isVariantApplicableInContext(VMI, OMPCtx,
6894                                         /* DeviceSetOnly */ false))
6895         continue;
6896 
6897       VMIs.push_back(VMI);
6898       Exprs.push_back(VariantRef);
6899     }
6900 
6901     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6902   }
6903 
6904   ExprResult NewCall;
6905   do {
6906     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6907     if (BestIdx < 0)
6908       return Call;
6909     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6910     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6911 
6912     {
6913       // Try to build a (member) call expression for the current best applicable
6914       // variant expression. We allow this to fail in which case we continue
6915       // with the next best variant expression. The fail case is part of the
6916       // implementation defined behavior in the OpenMP standard when it talks
6917       // about what differences in the function prototypes: "Any differences
6918       // that the specific OpenMP context requires in the prototype of the
6919       // variant from the base function prototype are implementation defined."
6920       // This wording is there to allow the specialized variant to have a
6921       // different type than the base function. This is intended and OK but if
6922       // we cannot create a call the difference is not in the "implementation
6923       // defined range" we allow.
6924       Sema::TentativeAnalysisScope Trap(*this);
6925 
6926       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6927         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6928         BestExpr = MemberExpr::CreateImplicit(
6929             Context, MemberCall->getImplicitObjectArgument(),
6930             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6931             MemberCall->getValueKind(), MemberCall->getObjectKind());
6932       }
6933       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6934                               ExecConfig);
6935       if (NewCall.isUsable()) {
6936         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6937           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6938           QualType NewType = Context.mergeFunctionTypes(
6939               CalleeFnType, NewCalleeFnDecl->getType(),
6940               /* OfBlockPointer */ false,
6941               /* Unqualified */ false, /* AllowCXX */ true);
6942           if (!NewType.isNull())
6943             break;
6944           // Don't use the call if the function type was not compatible.
6945           NewCall = nullptr;
6946         }
6947       }
6948     }
6949 
6950     VMIs.erase(VMIs.begin() + BestIdx);
6951     Exprs.erase(Exprs.begin() + BestIdx);
6952   } while (!VMIs.empty());
6953 
6954   if (!NewCall.isUsable())
6955     return Call;
6956   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6957 }
6958 
6959 Optional<std::pair<FunctionDecl *, Expr *>>
6960 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6961                                         Expr *VariantRef, OMPTraitInfo &TI,
6962                                         unsigned NumAppendArgs,
6963                                         SourceRange SR) {
6964   if (!DG || DG.get().isNull())
6965     return None;
6966 
6967   const int VariantId = 1;
6968   // Must be applied only to single decl.
6969   if (!DG.get().isSingleDecl()) {
6970     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6971         << VariantId << SR;
6972     return None;
6973   }
6974   Decl *ADecl = DG.get().getSingleDecl();
6975   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6976     ADecl = FTD->getTemplatedDecl();
6977 
6978   // Decl must be a function.
6979   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6980   if (!FD) {
6981     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6982         << VariantId << SR;
6983     return None;
6984   }
6985 
6986   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6987     return FD->hasAttrs() &&
6988            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6989             FD->hasAttr<TargetAttr>());
6990   };
6991   // OpenMP is not compatible with CPU-specific attributes.
6992   if (HasMultiVersionAttributes(FD)) {
6993     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6994         << SR;
6995     return None;
6996   }
6997 
6998   // Allow #pragma omp declare variant only if the function is not used.
6999   if (FD->isUsed(false))
7000     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
7001         << FD->getLocation();
7002 
7003   // Check if the function was emitted already.
7004   const FunctionDecl *Definition;
7005   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
7006       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
7007     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
7008         << FD->getLocation();
7009 
7010   // The VariantRef must point to function.
7011   if (!VariantRef) {
7012     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
7013     return None;
7014   }
7015 
7016   auto ShouldDelayChecks = [](Expr *&E, bool) {
7017     return E && (E->isTypeDependent() || E->isValueDependent() ||
7018                  E->containsUnexpandedParameterPack() ||
7019                  E->isInstantiationDependent());
7020   };
7021   // Do not check templates, wait until instantiation.
7022   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
7023       TI.anyScoreOrCondition(ShouldDelayChecks))
7024     return std::make_pair(FD, VariantRef);
7025 
7026   // Deal with non-constant score and user condition expressions.
7027   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
7028                                                      bool IsScore) -> bool {
7029     if (!E || E->isIntegerConstantExpr(Context))
7030       return false;
7031 
7032     if (IsScore) {
7033       // We warn on non-constant scores and pretend they were not present.
7034       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
7035           << E;
7036       E = nullptr;
7037     } else {
7038       // We could replace a non-constant user condition with "false" but we
7039       // will soon need to handle these anyway for the dynamic version of
7040       // OpenMP context selectors.
7041       Diag(E->getExprLoc(),
7042            diag::err_omp_declare_variant_user_condition_not_constant)
7043           << E;
7044     }
7045     return true;
7046   };
7047   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
7048     return None;
7049 
7050   QualType AdjustedFnType = FD->getType();
7051   if (NumAppendArgs) {
7052     if (isa<FunctionNoProtoType>(FD->getType())) {
7053       Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
7054           << SR;
7055       return None;
7056     }
7057     // Adjust the function type to account for an extra omp_interop_t for each
7058     // specified in the append_args clause.
7059     const TypeDecl *TD = nullptr;
7060     LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
7061                         SR.getBegin(), Sema::LookupOrdinaryName);
7062     if (LookupName(Result, getCurScope())) {
7063       NamedDecl *ND = Result.getFoundDecl();
7064       TD = dyn_cast_or_null<TypeDecl>(ND);
7065     }
7066     if (!TD) {
7067       Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
7068       return None;
7069     }
7070     QualType InteropType = QualType(TD->getTypeForDecl(), 0);
7071     auto *PTy = cast<FunctionProtoType>(FD->getType());
7072     if (PTy->isVariadic()) {
7073       Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
7074       return None;
7075     }
7076     llvm::SmallVector<QualType, 8> Params;
7077     Params.append(PTy->param_type_begin(), PTy->param_type_end());
7078     Params.insert(Params.end(), NumAppendArgs, InteropType);
7079     AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
7080                                              PTy->getExtProtoInfo());
7081   }
7082 
7083   // Convert VariantRef expression to the type of the original function to
7084   // resolve possible conflicts.
7085   ExprResult VariantRefCast = VariantRef;
7086   if (LangOpts.CPlusPlus) {
7087     QualType FnPtrType;
7088     auto *Method = dyn_cast<CXXMethodDecl>(FD);
7089     if (Method && !Method->isStatic()) {
7090       const Type *ClassType =
7091           Context.getTypeDeclType(Method->getParent()).getTypePtr();
7092       FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
7093       ExprResult ER;
7094       {
7095         // Build adrr_of unary op to correctly handle type checks for member
7096         // functions.
7097         Sema::TentativeAnalysisScope Trap(*this);
7098         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
7099                                   VariantRef);
7100       }
7101       if (!ER.isUsable()) {
7102         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7103             << VariantId << VariantRef->getSourceRange();
7104         return None;
7105       }
7106       VariantRef = ER.get();
7107     } else {
7108       FnPtrType = Context.getPointerType(AdjustedFnType);
7109     }
7110     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
7111     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
7112       ImplicitConversionSequence ICS = TryImplicitConversion(
7113           VariantRef, FnPtrType.getUnqualifiedType(),
7114           /*SuppressUserConversions=*/false, AllowedExplicit::None,
7115           /*InOverloadResolution=*/false,
7116           /*CStyle=*/false,
7117           /*AllowObjCWritebackConversion=*/false);
7118       if (ICS.isFailure()) {
7119         Diag(VariantRef->getExprLoc(),
7120              diag::err_omp_declare_variant_incompat_types)
7121             << VariantRef->getType()
7122             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7123             << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
7124         return None;
7125       }
7126       VariantRefCast = PerformImplicitConversion(
7127           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7128       if (!VariantRefCast.isUsable())
7129         return None;
7130     }
7131     // Drop previously built artificial addr_of unary op for member functions.
7132     if (Method && !Method->isStatic()) {
7133       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7134       if (auto *UO = dyn_cast<UnaryOperator>(
7135               PossibleAddrOfVariantRef->IgnoreImplicit()))
7136         VariantRefCast = UO->getSubExpr();
7137     }
7138   }
7139 
7140   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7141   if (!ER.isUsable() ||
7142       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7143     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7144         << VariantId << VariantRef->getSourceRange();
7145     return None;
7146   }
7147 
7148   // The VariantRef must point to function.
7149   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7150   if (!DRE) {
7151     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7152         << VariantId << VariantRef->getSourceRange();
7153     return None;
7154   }
7155   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7156   if (!NewFD) {
7157     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7158         << VariantId << VariantRef->getSourceRange();
7159     return None;
7160   }
7161 
7162   // Check if function types are compatible in C.
7163   if (!LangOpts.CPlusPlus) {
7164     QualType NewType =
7165         Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
7166     if (NewType.isNull()) {
7167       Diag(VariantRef->getExprLoc(),
7168            diag::err_omp_declare_variant_incompat_types)
7169           << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
7170           << VariantRef->getSourceRange();
7171       return None;
7172     }
7173     if (NewType->isFunctionProtoType()) {
7174       if (FD->getType()->isFunctionNoProtoType())
7175         setPrototype(*this, FD, NewFD, NewType);
7176       else if (NewFD->getType()->isFunctionNoProtoType())
7177         setPrototype(*this, NewFD, FD, NewType);
7178     }
7179   }
7180 
7181   // Check if variant function is not marked with declare variant directive.
7182   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7183     Diag(VariantRef->getExprLoc(),
7184          diag::warn_omp_declare_variant_marked_as_declare_variant)
7185         << VariantRef->getSourceRange();
7186     SourceRange SR =
7187         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7188     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7189     return None;
7190   }
7191 
7192   enum DoesntSupport {
7193     VirtFuncs = 1,
7194     Constructors = 3,
7195     Destructors = 4,
7196     DeletedFuncs = 5,
7197     DefaultedFuncs = 6,
7198     ConstexprFuncs = 7,
7199     ConstevalFuncs = 8,
7200   };
7201   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7202     if (CXXFD->isVirtual()) {
7203       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7204           << VirtFuncs;
7205       return None;
7206     }
7207 
7208     if (isa<CXXConstructorDecl>(FD)) {
7209       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7210           << Constructors;
7211       return None;
7212     }
7213 
7214     if (isa<CXXDestructorDecl>(FD)) {
7215       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7216           << Destructors;
7217       return None;
7218     }
7219   }
7220 
7221   if (FD->isDeleted()) {
7222     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7223         << DeletedFuncs;
7224     return None;
7225   }
7226 
7227   if (FD->isDefaulted()) {
7228     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7229         << DefaultedFuncs;
7230     return None;
7231   }
7232 
7233   if (FD->isConstexpr()) {
7234     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7235         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7236     return None;
7237   }
7238 
7239   // Check general compatibility.
7240   if (areMultiversionVariantFunctionsCompatible(
7241           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7242           PartialDiagnosticAt(SourceLocation(),
7243                               PartialDiagnostic::NullDiagnostic()),
7244           PartialDiagnosticAt(
7245               VariantRef->getExprLoc(),
7246               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7247           PartialDiagnosticAt(VariantRef->getExprLoc(),
7248                               PDiag(diag::err_omp_declare_variant_diff)
7249                                   << FD->getLocation()),
7250           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7251           /*CLinkageMayDiffer=*/true))
7252     return None;
7253   return std::make_pair(FD, cast<Expr>(DRE));
7254 }
7255 
7256 void Sema::ActOnOpenMPDeclareVariantDirective(
7257     FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
7258     ArrayRef<Expr *> AdjustArgsNothing,
7259     ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
7260     ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
7261     SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
7262     SourceRange SR) {
7263 
7264   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7265   // An adjust_args clause or append_args clause can only be specified if the
7266   // dispatch selector of the construct selector set appears in the match
7267   // clause.
7268 
7269   SmallVector<Expr *, 8> AllAdjustArgs;
7270   llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
7271   llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
7272 
7273   if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
7274     VariantMatchInfo VMI;
7275     TI.getAsVariantMatchInfo(Context, VMI);
7276     if (!llvm::is_contained(
7277             VMI.ConstructTraits,
7278             llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
7279       if (!AllAdjustArgs.empty())
7280         Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7281             << getOpenMPClauseName(OMPC_adjust_args);
7282       if (!AppendArgs.empty())
7283         Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7284             << getOpenMPClauseName(OMPC_append_args);
7285       return;
7286     }
7287   }
7288 
7289   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7290   // Each argument can only appear in a single adjust_args clause for each
7291   // declare variant directive.
7292   llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
7293 
7294   for (Expr *E : AllAdjustArgs) {
7295     E = E->IgnoreParenImpCasts();
7296     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
7297       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7298         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7299         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7300             FD->getParamDecl(PVD->getFunctionScopeIndex())
7301                     ->getCanonicalDecl() == CanonPVD) {
7302           // It's a parameter of the function, check duplicates.
7303           if (!AdjustVars.insert(CanonPVD).second) {
7304             Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
7305                 << PVD;
7306             return;
7307           }
7308           continue;
7309         }
7310       }
7311     }
7312     // Anything that is not a function parameter is an error.
7313     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
7314     return;
7315   }
7316 
7317   auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
7318       Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
7319       AdjustArgsNothing.size(),
7320       const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
7321       AdjustArgsNeedDevicePtr.size(),
7322       const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
7323       AppendArgs.size(), SR);
7324   FD->addAttr(NewAttr);
7325 }
7326 
7327 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7328                                               Stmt *AStmt,
7329                                               SourceLocation StartLoc,
7330                                               SourceLocation EndLoc) {
7331   if (!AStmt)
7332     return StmtError();
7333 
7334   auto *CS = cast<CapturedStmt>(AStmt);
7335   // 1.2.2 OpenMP Language Terminology
7336   // Structured block - An executable statement with a single entry at the
7337   // top and a single exit at the bottom.
7338   // The point of exit cannot be a branch out of the structured block.
7339   // longjmp() and throw() must not violate the entry/exit criteria.
7340   CS->getCapturedDecl()->setNothrow();
7341 
7342   setFunctionHasBranchProtectedScope();
7343 
7344   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7345                                       DSAStack->getTaskgroupReductionRef(),
7346                                       DSAStack->isCancelRegion());
7347 }
7348 
7349 namespace {
7350 /// Iteration space of a single for loop.
7351 struct LoopIterationSpace final {
7352   /// True if the condition operator is the strict compare operator (<, > or
7353   /// !=).
7354   bool IsStrictCompare = false;
7355   /// Condition of the loop.
7356   Expr *PreCond = nullptr;
7357   /// This expression calculates the number of iterations in the loop.
7358   /// It is always possible to calculate it before starting the loop.
7359   Expr *NumIterations = nullptr;
7360   /// The loop counter variable.
7361   Expr *CounterVar = nullptr;
7362   /// Private loop counter variable.
7363   Expr *PrivateCounterVar = nullptr;
7364   /// This is initializer for the initial value of #CounterVar.
7365   Expr *CounterInit = nullptr;
7366   /// This is step for the #CounterVar used to generate its update:
7367   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7368   Expr *CounterStep = nullptr;
7369   /// Should step be subtracted?
7370   bool Subtract = false;
7371   /// Source range of the loop init.
7372   SourceRange InitSrcRange;
7373   /// Source range of the loop condition.
7374   SourceRange CondSrcRange;
7375   /// Source range of the loop increment.
7376   SourceRange IncSrcRange;
7377   /// Minimum value that can have the loop control variable. Used to support
7378   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7379   /// since only such variables can be used in non-loop invariant expressions.
7380   Expr *MinValue = nullptr;
7381   /// Maximum value that can have the loop control variable. Used to support
7382   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7383   /// since only such variables can be used in non-loop invariant expressions.
7384   Expr *MaxValue = nullptr;
7385   /// true, if the lower bound depends on the outer loop control var.
7386   bool IsNonRectangularLB = false;
7387   /// true, if the upper bound depends on the outer loop control var.
7388   bool IsNonRectangularUB = false;
7389   /// Index of the loop this loop depends on and forms non-rectangular loop
7390   /// nest.
7391   unsigned LoopDependentIdx = 0;
7392   /// Final condition for the non-rectangular loop nest support. It is used to
7393   /// check that the number of iterations for this particular counter must be
7394   /// finished.
7395   Expr *FinalCondition = nullptr;
7396 };
7397 
7398 /// Helper class for checking canonical form of the OpenMP loops and
7399 /// extracting iteration space of each loop in the loop nest, that will be used
7400 /// for IR generation.
7401 class OpenMPIterationSpaceChecker {
7402   /// Reference to Sema.
7403   Sema &SemaRef;
7404   /// Does the loop associated directive support non-rectangular loops?
7405   bool SupportsNonRectangular;
7406   /// Data-sharing stack.
7407   DSAStackTy &Stack;
7408   /// A location for diagnostics (when there is no some better location).
7409   SourceLocation DefaultLoc;
7410   /// A location for diagnostics (when increment is not compatible).
7411   SourceLocation ConditionLoc;
7412   /// A source location for referring to loop init later.
7413   SourceRange InitSrcRange;
7414   /// A source location for referring to condition later.
7415   SourceRange ConditionSrcRange;
7416   /// A source location for referring to increment later.
7417   SourceRange IncrementSrcRange;
7418   /// Loop variable.
7419   ValueDecl *LCDecl = nullptr;
7420   /// Reference to loop variable.
7421   Expr *LCRef = nullptr;
7422   /// Lower bound (initializer for the var).
7423   Expr *LB = nullptr;
7424   /// Upper bound.
7425   Expr *UB = nullptr;
7426   /// Loop step (increment).
7427   Expr *Step = nullptr;
7428   /// This flag is true when condition is one of:
7429   ///   Var <  UB
7430   ///   Var <= UB
7431   ///   UB  >  Var
7432   ///   UB  >= Var
7433   /// This will have no value when the condition is !=
7434   llvm::Optional<bool> TestIsLessOp;
7435   /// This flag is true when condition is strict ( < or > ).
7436   bool TestIsStrictOp = false;
7437   /// This flag is true when step is subtracted on each iteration.
7438   bool SubtractStep = false;
7439   /// The outer loop counter this loop depends on (if any).
7440   const ValueDecl *DepDecl = nullptr;
7441   /// Contains number of loop (starts from 1) on which loop counter init
7442   /// expression of this loop depends on.
7443   Optional<unsigned> InitDependOnLC;
7444   /// Contains number of loop (starts from 1) on which loop counter condition
7445   /// expression of this loop depends on.
7446   Optional<unsigned> CondDependOnLC;
7447   /// Checks if the provide statement depends on the loop counter.
7448   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7449   /// Original condition required for checking of the exit condition for
7450   /// non-rectangular loop.
7451   Expr *Condition = nullptr;
7452 
7453 public:
7454   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7455                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7456       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7457         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7458   /// Check init-expr for canonical loop form and save loop counter
7459   /// variable - #Var and its initialization value - #LB.
7460   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7461   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7462   /// for less/greater and for strict/non-strict comparison.
7463   bool checkAndSetCond(Expr *S);
7464   /// Check incr-expr for canonical loop form and return true if it
7465   /// does not conform, otherwise save loop step (#Step).
7466   bool checkAndSetInc(Expr *S);
7467   /// Return the loop counter variable.
7468   ValueDecl *getLoopDecl() const { return LCDecl; }
7469   /// Return the reference expression to loop counter variable.
7470   Expr *getLoopDeclRefExpr() const { return LCRef; }
7471   /// Source range of the loop init.
7472   SourceRange getInitSrcRange() const { return InitSrcRange; }
7473   /// Source range of the loop condition.
7474   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7475   /// Source range of the loop increment.
7476   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7477   /// True if the step should be subtracted.
7478   bool shouldSubtractStep() const { return SubtractStep; }
7479   /// True, if the compare operator is strict (<, > or !=).
7480   bool isStrictTestOp() const { return TestIsStrictOp; }
7481   /// Build the expression to calculate the number of iterations.
7482   Expr *buildNumIterations(
7483       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7484       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7485   /// Build the precondition expression for the loops.
7486   Expr *
7487   buildPreCond(Scope *S, Expr *Cond,
7488                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7489   /// Build reference expression to the counter be used for codegen.
7490   DeclRefExpr *
7491   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7492                   DSAStackTy &DSA) const;
7493   /// Build reference expression to the private counter be used for
7494   /// codegen.
7495   Expr *buildPrivateCounterVar() const;
7496   /// Build initialization of the counter be used for codegen.
7497   Expr *buildCounterInit() const;
7498   /// Build step of the counter be used for codegen.
7499   Expr *buildCounterStep() const;
7500   /// Build loop data with counter value for depend clauses in ordered
7501   /// directives.
7502   Expr *
7503   buildOrderedLoopData(Scope *S, Expr *Counter,
7504                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7505                        SourceLocation Loc, Expr *Inc = nullptr,
7506                        OverloadedOperatorKind OOK = OO_Amp);
7507   /// Builds the minimum value for the loop counter.
7508   std::pair<Expr *, Expr *> buildMinMaxValues(
7509       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7510   /// Builds final condition for the non-rectangular loops.
7511   Expr *buildFinalCondition(Scope *S) const;
7512   /// Return true if any expression is dependent.
7513   bool dependent() const;
7514   /// Returns true if the initializer forms non-rectangular loop.
7515   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7516   /// Returns true if the condition forms non-rectangular loop.
7517   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7518   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7519   unsigned getLoopDependentIdx() const {
7520     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7521   }
7522 
7523 private:
7524   /// Check the right-hand side of an assignment in the increment
7525   /// expression.
7526   bool checkAndSetIncRHS(Expr *RHS);
7527   /// Helper to set loop counter variable and its initializer.
7528   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7529                       bool EmitDiags);
7530   /// Helper to set upper bound.
7531   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7532              SourceRange SR, SourceLocation SL);
7533   /// Helper to set loop increment.
7534   bool setStep(Expr *NewStep, bool Subtract);
7535 };
7536 
7537 bool OpenMPIterationSpaceChecker::dependent() const {
7538   if (!LCDecl) {
7539     assert(!LB && !UB && !Step);
7540     return false;
7541   }
7542   return LCDecl->getType()->isDependentType() ||
7543          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7544          (Step && Step->isValueDependent());
7545 }
7546 
7547 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7548                                                  Expr *NewLCRefExpr,
7549                                                  Expr *NewLB, bool EmitDiags) {
7550   // State consistency checking to ensure correct usage.
7551   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7552          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7553   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7554     return true;
7555   LCDecl = getCanonicalDecl(NewLCDecl);
7556   LCRef = NewLCRefExpr;
7557   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7558     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7559       if ((Ctor->isCopyOrMoveConstructor() ||
7560            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7561           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7562         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7563   LB = NewLB;
7564   if (EmitDiags)
7565     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7566   return false;
7567 }
7568 
7569 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7570                                         llvm::Optional<bool> LessOp,
7571                                         bool StrictOp, SourceRange SR,
7572                                         SourceLocation SL) {
7573   // State consistency checking to ensure correct usage.
7574   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7575          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7576   if (!NewUB || NewUB->containsErrors())
7577     return true;
7578   UB = NewUB;
7579   if (LessOp)
7580     TestIsLessOp = LessOp;
7581   TestIsStrictOp = StrictOp;
7582   ConditionSrcRange = SR;
7583   ConditionLoc = SL;
7584   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7585   return false;
7586 }
7587 
7588 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7589   // State consistency checking to ensure correct usage.
7590   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7591   if (!NewStep || NewStep->containsErrors())
7592     return true;
7593   if (!NewStep->isValueDependent()) {
7594     // Check that the step is integer expression.
7595     SourceLocation StepLoc = NewStep->getBeginLoc();
7596     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7597         StepLoc, getExprAsWritten(NewStep));
7598     if (Val.isInvalid())
7599       return true;
7600     NewStep = Val.get();
7601 
7602     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7603     //  If test-expr is of form var relational-op b and relational-op is < or
7604     //  <= then incr-expr must cause var to increase on each iteration of the
7605     //  loop. If test-expr is of form var relational-op b and relational-op is
7606     //  > or >= then incr-expr must cause var to decrease on each iteration of
7607     //  the loop.
7608     //  If test-expr is of form b relational-op var and relational-op is < or
7609     //  <= then incr-expr must cause var to decrease on each iteration of the
7610     //  loop. If test-expr is of form b relational-op var and relational-op is
7611     //  > or >= then incr-expr must cause var to increase on each iteration of
7612     //  the loop.
7613     Optional<llvm::APSInt> Result =
7614         NewStep->getIntegerConstantExpr(SemaRef.Context);
7615     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7616     bool IsConstNeg =
7617         Result && Result->isSigned() && (Subtract != Result->isNegative());
7618     bool IsConstPos =
7619         Result && Result->isSigned() && (Subtract == Result->isNegative());
7620     bool IsConstZero = Result && !Result->getBoolValue();
7621 
7622     // != with increment is treated as <; != with decrement is treated as >
7623     if (!TestIsLessOp.hasValue())
7624       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7625     if (UB &&
7626         (IsConstZero || (TestIsLessOp.getValue()
7627                              ? (IsConstNeg || (IsUnsigned && Subtract))
7628                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
7629       SemaRef.Diag(NewStep->getExprLoc(),
7630                    diag::err_omp_loop_incr_not_compatible)
7631           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7632       SemaRef.Diag(ConditionLoc,
7633                    diag::note_omp_loop_cond_requres_compatible_incr)
7634           << TestIsLessOp.getValue() << ConditionSrcRange;
7635       return true;
7636     }
7637     if (TestIsLessOp.getValue() == Subtract) {
7638       NewStep =
7639           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7640               .get();
7641       Subtract = !Subtract;
7642     }
7643   }
7644 
7645   Step = NewStep;
7646   SubtractStep = Subtract;
7647   return false;
7648 }
7649 
7650 namespace {
7651 /// Checker for the non-rectangular loops. Checks if the initializer or
7652 /// condition expression references loop counter variable.
7653 class LoopCounterRefChecker final
7654     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7655   Sema &SemaRef;
7656   DSAStackTy &Stack;
7657   const ValueDecl *CurLCDecl = nullptr;
7658   const ValueDecl *DepDecl = nullptr;
7659   const ValueDecl *PrevDepDecl = nullptr;
7660   bool IsInitializer = true;
7661   bool SupportsNonRectangular;
7662   unsigned BaseLoopId = 0;
7663   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7664     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7665       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7666           << (IsInitializer ? 0 : 1);
7667       return false;
7668     }
7669     const auto &&Data = Stack.isLoopControlVariable(VD);
7670     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7671     // The type of the loop iterator on which we depend may not have a random
7672     // access iterator type.
7673     if (Data.first && VD->getType()->isRecordType()) {
7674       SmallString<128> Name;
7675       llvm::raw_svector_ostream OS(Name);
7676       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7677                                /*Qualified=*/true);
7678       SemaRef.Diag(E->getExprLoc(),
7679                    diag::err_omp_wrong_dependency_iterator_type)
7680           << OS.str();
7681       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7682       return false;
7683     }
7684     if (Data.first && !SupportsNonRectangular) {
7685       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7686       return false;
7687     }
7688     if (Data.first &&
7689         (DepDecl || (PrevDepDecl &&
7690                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7691       if (!DepDecl && PrevDepDecl)
7692         DepDecl = PrevDepDecl;
7693       SmallString<128> Name;
7694       llvm::raw_svector_ostream OS(Name);
7695       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7696                                     /*Qualified=*/true);
7697       SemaRef.Diag(E->getExprLoc(),
7698                    diag::err_omp_invariant_or_linear_dependency)
7699           << OS.str();
7700       return false;
7701     }
7702     if (Data.first) {
7703       DepDecl = VD;
7704       BaseLoopId = Data.first;
7705     }
7706     return Data.first;
7707   }
7708 
7709 public:
7710   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7711     const ValueDecl *VD = E->getDecl();
7712     if (isa<VarDecl>(VD))
7713       return checkDecl(E, VD);
7714     return false;
7715   }
7716   bool VisitMemberExpr(const MemberExpr *E) {
7717     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7718       const ValueDecl *VD = E->getMemberDecl();
7719       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7720         return checkDecl(E, VD);
7721     }
7722     return false;
7723   }
7724   bool VisitStmt(const Stmt *S) {
7725     bool Res = false;
7726     for (const Stmt *Child : S->children())
7727       Res = (Child && Visit(Child)) || Res;
7728     return Res;
7729   }
7730   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7731                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7732                                  const ValueDecl *PrevDepDecl = nullptr,
7733                                  bool SupportsNonRectangular = true)
7734       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7735         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7736         SupportsNonRectangular(SupportsNonRectangular) {}
7737   unsigned getBaseLoopId() const {
7738     assert(CurLCDecl && "Expected loop dependency.");
7739     return BaseLoopId;
7740   }
7741   const ValueDecl *getDepDecl() const {
7742     assert(CurLCDecl && "Expected loop dependency.");
7743     return DepDecl;
7744   }
7745 };
7746 } // namespace
7747 
7748 Optional<unsigned>
7749 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7750                                                      bool IsInitializer) {
7751   // Check for the non-rectangular loops.
7752   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7753                                         DepDecl, SupportsNonRectangular);
7754   if (LoopStmtChecker.Visit(S)) {
7755     DepDecl = LoopStmtChecker.getDepDecl();
7756     return LoopStmtChecker.getBaseLoopId();
7757   }
7758   return llvm::None;
7759 }
7760 
7761 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7762   // Check init-expr for canonical loop form and save loop counter
7763   // variable - #Var and its initialization value - #LB.
7764   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7765   //   var = lb
7766   //   integer-type var = lb
7767   //   random-access-iterator-type var = lb
7768   //   pointer-type var = lb
7769   //
7770   if (!S) {
7771     if (EmitDiags) {
7772       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7773     }
7774     return true;
7775   }
7776   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7777     if (!ExprTemp->cleanupsHaveSideEffects())
7778       S = ExprTemp->getSubExpr();
7779 
7780   InitSrcRange = S->getSourceRange();
7781   if (Expr *E = dyn_cast<Expr>(S))
7782     S = E->IgnoreParens();
7783   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7784     if (BO->getOpcode() == BO_Assign) {
7785       Expr *LHS = BO->getLHS()->IgnoreParens();
7786       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7787         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7788           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7789             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7790                                   EmitDiags);
7791         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7792       }
7793       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7794         if (ME->isArrow() &&
7795             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7796           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7797                                 EmitDiags);
7798       }
7799     }
7800   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7801     if (DS->isSingleDecl()) {
7802       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7803         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7804           // Accept non-canonical init form here but emit ext. warning.
7805           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7806             SemaRef.Diag(S->getBeginLoc(),
7807                          diag::ext_omp_loop_not_canonical_init)
7808                 << S->getSourceRange();
7809           return setLCDeclAndLB(
7810               Var,
7811               buildDeclRefExpr(SemaRef, Var,
7812                                Var->getType().getNonReferenceType(),
7813                                DS->getBeginLoc()),
7814               Var->getInit(), EmitDiags);
7815         }
7816       }
7817     }
7818   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7819     if (CE->getOperator() == OO_Equal) {
7820       Expr *LHS = CE->getArg(0);
7821       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7822         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7823           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7824             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7825                                   EmitDiags);
7826         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7827       }
7828       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7829         if (ME->isArrow() &&
7830             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7831           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7832                                 EmitDiags);
7833       }
7834     }
7835   }
7836 
7837   if (dependent() || SemaRef.CurContext->isDependentContext())
7838     return false;
7839   if (EmitDiags) {
7840     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7841         << S->getSourceRange();
7842   }
7843   return true;
7844 }
7845 
7846 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7847 /// variable (which may be the loop variable) if possible.
7848 static const ValueDecl *getInitLCDecl(const Expr *E) {
7849   if (!E)
7850     return nullptr;
7851   E = getExprAsWritten(E);
7852   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7853     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7854       if ((Ctor->isCopyOrMoveConstructor() ||
7855            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7856           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7857         E = CE->getArg(0)->IgnoreParenImpCasts();
7858   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7859     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7860       return getCanonicalDecl(VD);
7861   }
7862   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7863     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7864       return getCanonicalDecl(ME->getMemberDecl());
7865   return nullptr;
7866 }
7867 
7868 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7869   // Check test-expr for canonical form, save upper-bound UB, flags for
7870   // less/greater and for strict/non-strict comparison.
7871   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7872   //   var relational-op b
7873   //   b relational-op var
7874   //
7875   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7876   if (!S) {
7877     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7878         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7879     return true;
7880   }
7881   Condition = S;
7882   S = getExprAsWritten(S);
7883   SourceLocation CondLoc = S->getBeginLoc();
7884   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7885                                BinaryOperatorKind Opcode, const Expr *LHS,
7886                                const Expr *RHS, SourceRange SR,
7887                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7888     if (BinaryOperator::isRelationalOp(Opcode)) {
7889       if (getInitLCDecl(LHS) == LCDecl)
7890         return setUB(const_cast<Expr *>(RHS),
7891                      (Opcode == BO_LT || Opcode == BO_LE),
7892                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7893       if (getInitLCDecl(RHS) == LCDecl)
7894         return setUB(const_cast<Expr *>(LHS),
7895                      (Opcode == BO_GT || Opcode == BO_GE),
7896                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7897     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7898       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7899                    /*LessOp=*/llvm::None,
7900                    /*StrictOp=*/true, SR, OpLoc);
7901     }
7902     return llvm::None;
7903   };
7904   llvm::Optional<bool> Res;
7905   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7906     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7907     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7908                           RBO->getOperatorLoc());
7909   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7910     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7911                           BO->getSourceRange(), BO->getOperatorLoc());
7912   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7913     if (CE->getNumArgs() == 2) {
7914       Res = CheckAndSetCond(
7915           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7916           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7917     }
7918   }
7919   if (Res.hasValue())
7920     return *Res;
7921   if (dependent() || SemaRef.CurContext->isDependentContext())
7922     return false;
7923   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7924       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7925   return true;
7926 }
7927 
7928 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7929   // RHS of canonical loop form increment can be:
7930   //   var + incr
7931   //   incr + var
7932   //   var - incr
7933   //
7934   RHS = RHS->IgnoreParenImpCasts();
7935   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7936     if (BO->isAdditiveOp()) {
7937       bool IsAdd = BO->getOpcode() == BO_Add;
7938       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7939         return setStep(BO->getRHS(), !IsAdd);
7940       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7941         return setStep(BO->getLHS(), /*Subtract=*/false);
7942     }
7943   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7944     bool IsAdd = CE->getOperator() == OO_Plus;
7945     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7946       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7947         return setStep(CE->getArg(1), !IsAdd);
7948       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7949         return setStep(CE->getArg(0), /*Subtract=*/false);
7950     }
7951   }
7952   if (dependent() || SemaRef.CurContext->isDependentContext())
7953     return false;
7954   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7955       << RHS->getSourceRange() << LCDecl;
7956   return true;
7957 }
7958 
7959 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7960   // Check incr-expr for canonical loop form and return true if it
7961   // does not conform.
7962   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7963   //   ++var
7964   //   var++
7965   //   --var
7966   //   var--
7967   //   var += incr
7968   //   var -= incr
7969   //   var = var + incr
7970   //   var = incr + var
7971   //   var = var - incr
7972   //
7973   if (!S) {
7974     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7975     return true;
7976   }
7977   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7978     if (!ExprTemp->cleanupsHaveSideEffects())
7979       S = ExprTemp->getSubExpr();
7980 
7981   IncrementSrcRange = S->getSourceRange();
7982   S = S->IgnoreParens();
7983   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7984     if (UO->isIncrementDecrementOp() &&
7985         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7986       return setStep(SemaRef
7987                          .ActOnIntegerConstant(UO->getBeginLoc(),
7988                                                (UO->isDecrementOp() ? -1 : 1))
7989                          .get(),
7990                      /*Subtract=*/false);
7991   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7992     switch (BO->getOpcode()) {
7993     case BO_AddAssign:
7994     case BO_SubAssign:
7995       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7996         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7997       break;
7998     case BO_Assign:
7999       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8000         return checkAndSetIncRHS(BO->getRHS());
8001       break;
8002     default:
8003       break;
8004     }
8005   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8006     switch (CE->getOperator()) {
8007     case OO_PlusPlus:
8008     case OO_MinusMinus:
8009       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8010         return setStep(SemaRef
8011                            .ActOnIntegerConstant(
8012                                CE->getBeginLoc(),
8013                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
8014                            .get(),
8015                        /*Subtract=*/false);
8016       break;
8017     case OO_PlusEqual:
8018     case OO_MinusEqual:
8019       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8020         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
8021       break;
8022     case OO_Equal:
8023       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8024         return checkAndSetIncRHS(CE->getArg(1));
8025       break;
8026     default:
8027       break;
8028     }
8029   }
8030   if (dependent() || SemaRef.CurContext->isDependentContext())
8031     return false;
8032   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8033       << S->getSourceRange() << LCDecl;
8034   return true;
8035 }
8036 
8037 static ExprResult
8038 tryBuildCapture(Sema &SemaRef, Expr *Capture,
8039                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8040   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
8041     return Capture;
8042   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
8043     return SemaRef.PerformImplicitConversion(
8044         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
8045         /*AllowExplicit=*/true);
8046   auto I = Captures.find(Capture);
8047   if (I != Captures.end())
8048     return buildCapture(SemaRef, Capture, I->second);
8049   DeclRefExpr *Ref = nullptr;
8050   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
8051   Captures[Capture] = Ref;
8052   return Res;
8053 }
8054 
8055 /// Calculate number of iterations, transforming to unsigned, if number of
8056 /// iterations may be larger than the original type.
8057 static Expr *
8058 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
8059                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
8060                   bool TestIsStrictOp, bool RoundToStep,
8061                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8062   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8063   if (!NewStep.isUsable())
8064     return nullptr;
8065   llvm::APSInt LRes, SRes;
8066   bool IsLowerConst = false, IsStepConst = false;
8067   if (Optional<llvm::APSInt> Res =
8068           Lower->getIntegerConstantExpr(SemaRef.Context)) {
8069     LRes = *Res;
8070     IsLowerConst = true;
8071   }
8072   if (Optional<llvm::APSInt> Res =
8073           Step->getIntegerConstantExpr(SemaRef.Context)) {
8074     SRes = *Res;
8075     IsStepConst = true;
8076   }
8077   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
8078                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
8079                           (TestIsStrictOp && LRes.isStrictlyPositive()));
8080   bool NeedToReorganize = false;
8081   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
8082   if (!NoNeedToConvert && IsLowerConst &&
8083       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
8084     NoNeedToConvert = true;
8085     if (RoundToStep) {
8086       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
8087                         ? LRes.getBitWidth()
8088                         : SRes.getBitWidth();
8089       LRes = LRes.extend(BW + 1);
8090       LRes.setIsSigned(true);
8091       SRes = SRes.extend(BW + 1);
8092       SRes.setIsSigned(true);
8093       LRes -= SRes;
8094       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
8095       LRes = LRes.trunc(BW);
8096     }
8097     if (TestIsStrictOp) {
8098       unsigned BW = LRes.getBitWidth();
8099       LRes = LRes.extend(BW + 1);
8100       LRes.setIsSigned(true);
8101       ++LRes;
8102       NoNeedToConvert =
8103           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
8104       // truncate to the original bitwidth.
8105       LRes = LRes.trunc(BW);
8106     }
8107     NeedToReorganize = NoNeedToConvert;
8108   }
8109   llvm::APSInt URes;
8110   bool IsUpperConst = false;
8111   if (Optional<llvm::APSInt> Res =
8112           Upper->getIntegerConstantExpr(SemaRef.Context)) {
8113     URes = *Res;
8114     IsUpperConst = true;
8115   }
8116   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
8117       (!RoundToStep || IsStepConst)) {
8118     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
8119                                                           : URes.getBitWidth();
8120     LRes = LRes.extend(BW + 1);
8121     LRes.setIsSigned(true);
8122     URes = URes.extend(BW + 1);
8123     URes.setIsSigned(true);
8124     URes -= LRes;
8125     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
8126     NeedToReorganize = NoNeedToConvert;
8127   }
8128   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
8129   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
8130   // unsigned.
8131   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
8132       !LCTy->isDependentType() && LCTy->isIntegerType()) {
8133     QualType LowerTy = Lower->getType();
8134     QualType UpperTy = Upper->getType();
8135     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
8136     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
8137     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
8138         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
8139       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
8140           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
8141       Upper =
8142           SemaRef
8143               .PerformImplicitConversion(
8144                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8145                   CastType, Sema::AA_Converting)
8146               .get();
8147       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
8148       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
8149     }
8150   }
8151   if (!Lower || !Upper || NewStep.isInvalid())
8152     return nullptr;
8153 
8154   ExprResult Diff;
8155   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
8156   // 1]).
8157   if (NeedToReorganize) {
8158     Diff = Lower;
8159 
8160     if (RoundToStep) {
8161       // Lower - Step
8162       Diff =
8163           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
8164       if (!Diff.isUsable())
8165         return nullptr;
8166     }
8167 
8168     // Lower - Step [+ 1]
8169     if (TestIsStrictOp)
8170       Diff = SemaRef.BuildBinOp(
8171           S, DefaultLoc, BO_Add, Diff.get(),
8172           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8173     if (!Diff.isUsable())
8174       return nullptr;
8175 
8176     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8177     if (!Diff.isUsable())
8178       return nullptr;
8179 
8180     // Upper - (Lower - Step [+ 1]).
8181     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
8182     if (!Diff.isUsable())
8183       return nullptr;
8184   } else {
8185     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8186 
8187     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8188       // BuildBinOp already emitted error, this one is to point user to upper
8189       // and lower bound, and to tell what is passed to 'operator-'.
8190       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8191           << Upper->getSourceRange() << Lower->getSourceRange();
8192       return nullptr;
8193     }
8194 
8195     if (!Diff.isUsable())
8196       return nullptr;
8197 
8198     // Upper - Lower [- 1]
8199     if (TestIsStrictOp)
8200       Diff = SemaRef.BuildBinOp(
8201           S, DefaultLoc, BO_Sub, Diff.get(),
8202           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8203     if (!Diff.isUsable())
8204       return nullptr;
8205 
8206     if (RoundToStep) {
8207       // Upper - Lower [- 1] + Step
8208       Diff =
8209           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8210       if (!Diff.isUsable())
8211         return nullptr;
8212     }
8213   }
8214 
8215   // Parentheses (for dumping/debugging purposes only).
8216   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8217   if (!Diff.isUsable())
8218     return nullptr;
8219 
8220   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8221   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8222   if (!Diff.isUsable())
8223     return nullptr;
8224 
8225   return Diff.get();
8226 }
8227 
8228 /// Build the expression to calculate the number of iterations.
8229 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8230     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8231     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8232   QualType VarType = LCDecl->getType().getNonReferenceType();
8233   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8234       !SemaRef.getLangOpts().CPlusPlus)
8235     return nullptr;
8236   Expr *LBVal = LB;
8237   Expr *UBVal = UB;
8238   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8239   // max(LB(MinVal), LB(MaxVal))
8240   if (InitDependOnLC) {
8241     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8242     if (!IS.MinValue || !IS.MaxValue)
8243       return nullptr;
8244     // OuterVar = Min
8245     ExprResult MinValue =
8246         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8247     if (!MinValue.isUsable())
8248       return nullptr;
8249 
8250     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8251                                              IS.CounterVar, MinValue.get());
8252     if (!LBMinVal.isUsable())
8253       return nullptr;
8254     // OuterVar = Min, LBVal
8255     LBMinVal =
8256         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8257     if (!LBMinVal.isUsable())
8258       return nullptr;
8259     // (OuterVar = Min, LBVal)
8260     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8261     if (!LBMinVal.isUsable())
8262       return nullptr;
8263 
8264     // OuterVar = Max
8265     ExprResult MaxValue =
8266         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8267     if (!MaxValue.isUsable())
8268       return nullptr;
8269 
8270     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8271                                              IS.CounterVar, MaxValue.get());
8272     if (!LBMaxVal.isUsable())
8273       return nullptr;
8274     // OuterVar = Max, LBVal
8275     LBMaxVal =
8276         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8277     if (!LBMaxVal.isUsable())
8278       return nullptr;
8279     // (OuterVar = Max, LBVal)
8280     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8281     if (!LBMaxVal.isUsable())
8282       return nullptr;
8283 
8284     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8285     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8286     if (!LBMin || !LBMax)
8287       return nullptr;
8288     // LB(MinVal) < LB(MaxVal)
8289     ExprResult MinLessMaxRes =
8290         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8291     if (!MinLessMaxRes.isUsable())
8292       return nullptr;
8293     Expr *MinLessMax =
8294         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8295     if (!MinLessMax)
8296       return nullptr;
8297     if (TestIsLessOp.getValue()) {
8298       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8299       // LB(MaxVal))
8300       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8301                                                     MinLessMax, LBMin, LBMax);
8302       if (!MinLB.isUsable())
8303         return nullptr;
8304       LBVal = MinLB.get();
8305     } else {
8306       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8307       // LB(MaxVal))
8308       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8309                                                     MinLessMax, LBMax, LBMin);
8310       if (!MaxLB.isUsable())
8311         return nullptr;
8312       LBVal = MaxLB.get();
8313     }
8314   }
8315   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8316   // min(UB(MinVal), UB(MaxVal))
8317   if (CondDependOnLC) {
8318     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8319     if (!IS.MinValue || !IS.MaxValue)
8320       return nullptr;
8321     // OuterVar = Min
8322     ExprResult MinValue =
8323         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8324     if (!MinValue.isUsable())
8325       return nullptr;
8326 
8327     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8328                                              IS.CounterVar, MinValue.get());
8329     if (!UBMinVal.isUsable())
8330       return nullptr;
8331     // OuterVar = Min, UBVal
8332     UBMinVal =
8333         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8334     if (!UBMinVal.isUsable())
8335       return nullptr;
8336     // (OuterVar = Min, UBVal)
8337     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8338     if (!UBMinVal.isUsable())
8339       return nullptr;
8340 
8341     // OuterVar = Max
8342     ExprResult MaxValue =
8343         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8344     if (!MaxValue.isUsable())
8345       return nullptr;
8346 
8347     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8348                                              IS.CounterVar, MaxValue.get());
8349     if (!UBMaxVal.isUsable())
8350       return nullptr;
8351     // OuterVar = Max, UBVal
8352     UBMaxVal =
8353         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8354     if (!UBMaxVal.isUsable())
8355       return nullptr;
8356     // (OuterVar = Max, UBVal)
8357     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8358     if (!UBMaxVal.isUsable())
8359       return nullptr;
8360 
8361     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8362     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8363     if (!UBMin || !UBMax)
8364       return nullptr;
8365     // UB(MinVal) > UB(MaxVal)
8366     ExprResult MinGreaterMaxRes =
8367         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8368     if (!MinGreaterMaxRes.isUsable())
8369       return nullptr;
8370     Expr *MinGreaterMax =
8371         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8372     if (!MinGreaterMax)
8373       return nullptr;
8374     if (TestIsLessOp.getValue()) {
8375       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8376       // UB(MaxVal))
8377       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8378           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8379       if (!MaxUB.isUsable())
8380         return nullptr;
8381       UBVal = MaxUB.get();
8382     } else {
8383       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8384       // UB(MaxVal))
8385       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8386           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8387       if (!MinUB.isUsable())
8388         return nullptr;
8389       UBVal = MinUB.get();
8390     }
8391   }
8392   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8393   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8394   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8395   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8396   if (!Upper || !Lower)
8397     return nullptr;
8398 
8399   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8400                                       Step, VarType, TestIsStrictOp,
8401                                       /*RoundToStep=*/true, Captures);
8402   if (!Diff.isUsable())
8403     return nullptr;
8404 
8405   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8406   QualType Type = Diff.get()->getType();
8407   ASTContext &C = SemaRef.Context;
8408   bool UseVarType = VarType->hasIntegerRepresentation() &&
8409                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8410   if (!Type->isIntegerType() || UseVarType) {
8411     unsigned NewSize =
8412         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8413     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8414                                : Type->hasSignedIntegerRepresentation();
8415     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8416     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8417       Diff = SemaRef.PerformImplicitConversion(
8418           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8419       if (!Diff.isUsable())
8420         return nullptr;
8421     }
8422   }
8423   if (LimitedType) {
8424     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8425     if (NewSize != C.getTypeSize(Type)) {
8426       if (NewSize < C.getTypeSize(Type)) {
8427         assert(NewSize == 64 && "incorrect loop var size");
8428         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8429             << InitSrcRange << ConditionSrcRange;
8430       }
8431       QualType NewType = C.getIntTypeForBitwidth(
8432           NewSize, Type->hasSignedIntegerRepresentation() ||
8433                        C.getTypeSize(Type) < NewSize);
8434       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8435         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8436                                                  Sema::AA_Converting, true);
8437         if (!Diff.isUsable())
8438           return nullptr;
8439       }
8440     }
8441   }
8442 
8443   return Diff.get();
8444 }
8445 
8446 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8447     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8448   // Do not build for iterators, they cannot be used in non-rectangular loop
8449   // nests.
8450   if (LCDecl->getType()->isRecordType())
8451     return std::make_pair(nullptr, nullptr);
8452   // If we subtract, the min is in the condition, otherwise the min is in the
8453   // init value.
8454   Expr *MinExpr = nullptr;
8455   Expr *MaxExpr = nullptr;
8456   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8457   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8458   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8459                                            : CondDependOnLC.hasValue();
8460   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8461                                            : InitDependOnLC.hasValue();
8462   Expr *Lower =
8463       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8464   Expr *Upper =
8465       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8466   if (!Upper || !Lower)
8467     return std::make_pair(nullptr, nullptr);
8468 
8469   if (TestIsLessOp.getValue())
8470     MinExpr = Lower;
8471   else
8472     MaxExpr = Upper;
8473 
8474   // Build minimum/maximum value based on number of iterations.
8475   QualType VarType = LCDecl->getType().getNonReferenceType();
8476 
8477   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8478                                       Step, VarType, TestIsStrictOp,
8479                                       /*RoundToStep=*/false, Captures);
8480   if (!Diff.isUsable())
8481     return std::make_pair(nullptr, nullptr);
8482 
8483   // ((Upper - Lower [- 1]) / Step) * Step
8484   // Parentheses (for dumping/debugging purposes only).
8485   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8486   if (!Diff.isUsable())
8487     return std::make_pair(nullptr, nullptr);
8488 
8489   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8490   if (!NewStep.isUsable())
8491     return std::make_pair(nullptr, nullptr);
8492   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8493   if (!Diff.isUsable())
8494     return std::make_pair(nullptr, nullptr);
8495 
8496   // Parentheses (for dumping/debugging purposes only).
8497   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8498   if (!Diff.isUsable())
8499     return std::make_pair(nullptr, nullptr);
8500 
8501   // Convert to the ptrdiff_t, if original type is pointer.
8502   if (VarType->isAnyPointerType() &&
8503       !SemaRef.Context.hasSameType(
8504           Diff.get()->getType(),
8505           SemaRef.Context.getUnsignedPointerDiffType())) {
8506     Diff = SemaRef.PerformImplicitConversion(
8507         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8508         Sema::AA_Converting, /*AllowExplicit=*/true);
8509   }
8510   if (!Diff.isUsable())
8511     return std::make_pair(nullptr, nullptr);
8512 
8513   if (TestIsLessOp.getValue()) {
8514     // MinExpr = Lower;
8515     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8516     Diff = SemaRef.BuildBinOp(
8517         S, DefaultLoc, BO_Add,
8518         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8519         Diff.get());
8520     if (!Diff.isUsable())
8521       return std::make_pair(nullptr, nullptr);
8522   } else {
8523     // MaxExpr = Upper;
8524     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8525     Diff = SemaRef.BuildBinOp(
8526         S, DefaultLoc, BO_Sub,
8527         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8528         Diff.get());
8529     if (!Diff.isUsable())
8530       return std::make_pair(nullptr, nullptr);
8531   }
8532 
8533   // Convert to the original type.
8534   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8535     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8536                                              Sema::AA_Converting,
8537                                              /*AllowExplicit=*/true);
8538   if (!Diff.isUsable())
8539     return std::make_pair(nullptr, nullptr);
8540 
8541   Sema::TentativeAnalysisScope Trap(SemaRef);
8542   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8543   if (!Diff.isUsable())
8544     return std::make_pair(nullptr, nullptr);
8545 
8546   if (TestIsLessOp.getValue())
8547     MaxExpr = Diff.get();
8548   else
8549     MinExpr = Diff.get();
8550 
8551   return std::make_pair(MinExpr, MaxExpr);
8552 }
8553 
8554 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8555   if (InitDependOnLC || CondDependOnLC)
8556     return Condition;
8557   return nullptr;
8558 }
8559 
8560 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8561     Scope *S, Expr *Cond,
8562     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8563   // Do not build a precondition when the condition/initialization is dependent
8564   // to prevent pessimistic early loop exit.
8565   // TODO: this can be improved by calculating min/max values but not sure that
8566   // it will be very effective.
8567   if (CondDependOnLC || InitDependOnLC)
8568     return SemaRef
8569         .PerformImplicitConversion(
8570             SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8571             SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8572             /*AllowExplicit=*/true)
8573         .get();
8574 
8575   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8576   Sema::TentativeAnalysisScope Trap(SemaRef);
8577 
8578   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8579   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8580   if (!NewLB.isUsable() || !NewUB.isUsable())
8581     return nullptr;
8582 
8583   ExprResult CondExpr = SemaRef.BuildBinOp(
8584       S, DefaultLoc,
8585       TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
8586                               : (TestIsStrictOp ? BO_GT : BO_GE),
8587       NewLB.get(), NewUB.get());
8588   if (CondExpr.isUsable()) {
8589     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8590                                                 SemaRef.Context.BoolTy))
8591       CondExpr = SemaRef.PerformImplicitConversion(
8592           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8593           /*AllowExplicit=*/true);
8594   }
8595 
8596   // Otherwise use original loop condition and evaluate it in runtime.
8597   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8598 }
8599 
8600 /// Build reference expression to the counter be used for codegen.
8601 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8602     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8603     DSAStackTy &DSA) const {
8604   auto *VD = dyn_cast<VarDecl>(LCDecl);
8605   if (!VD) {
8606     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8607     DeclRefExpr *Ref = buildDeclRefExpr(
8608         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8609     const DSAStackTy::DSAVarData Data =
8610         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8611     // If the loop control decl is explicitly marked as private, do not mark it
8612     // as captured again.
8613     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8614       Captures.insert(std::make_pair(LCRef, Ref));
8615     return Ref;
8616   }
8617   return cast<DeclRefExpr>(LCRef);
8618 }
8619 
8620 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8621   if (LCDecl && !LCDecl->isInvalidDecl()) {
8622     QualType Type = LCDecl->getType().getNonReferenceType();
8623     VarDecl *PrivateVar = buildVarDecl(
8624         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8625         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8626         isa<VarDecl>(LCDecl)
8627             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8628             : nullptr);
8629     if (PrivateVar->isInvalidDecl())
8630       return nullptr;
8631     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8632   }
8633   return nullptr;
8634 }
8635 
8636 /// Build initialization of the counter to be used for codegen.
8637 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8638 
8639 /// Build step of the counter be used for codegen.
8640 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8641 
8642 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8643     Scope *S, Expr *Counter,
8644     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8645     Expr *Inc, OverloadedOperatorKind OOK) {
8646   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8647   if (!Cnt)
8648     return nullptr;
8649   if (Inc) {
8650     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8651            "Expected only + or - operations for depend clauses.");
8652     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8653     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8654     if (!Cnt)
8655       return nullptr;
8656   }
8657   QualType VarType = LCDecl->getType().getNonReferenceType();
8658   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8659       !SemaRef.getLangOpts().CPlusPlus)
8660     return nullptr;
8661   // Upper - Lower
8662   Expr *Upper = TestIsLessOp.getValue()
8663                     ? Cnt
8664                     : tryBuildCapture(SemaRef, LB, Captures).get();
8665   Expr *Lower = TestIsLessOp.getValue()
8666                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8667                     : Cnt;
8668   if (!Upper || !Lower)
8669     return nullptr;
8670 
8671   ExprResult Diff = calculateNumIters(
8672       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8673       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8674   if (!Diff.isUsable())
8675     return nullptr;
8676 
8677   return Diff.get();
8678 }
8679 } // namespace
8680 
8681 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8682   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8683   assert(Init && "Expected loop in canonical form.");
8684   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8685   if (AssociatedLoops > 0 &&
8686       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8687     DSAStack->loopStart();
8688     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8689                                     *DSAStack, ForLoc);
8690     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8691       if (ValueDecl *D = ISC.getLoopDecl()) {
8692         auto *VD = dyn_cast<VarDecl>(D);
8693         DeclRefExpr *PrivateRef = nullptr;
8694         if (!VD) {
8695           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8696             VD = Private;
8697           } else {
8698             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8699                                       /*WithInit=*/false);
8700             VD = cast<VarDecl>(PrivateRef->getDecl());
8701           }
8702         }
8703         DSAStack->addLoopControlVariable(D, VD);
8704         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8705         if (LD != D->getCanonicalDecl()) {
8706           DSAStack->resetPossibleLoopCounter();
8707           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8708             MarkDeclarationsReferencedInExpr(
8709                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8710                                  Var->getType().getNonLValueExprType(Context),
8711                                  ForLoc, /*RefersToCapture=*/true));
8712         }
8713         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8714         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8715         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8716         // associated for-loop of a simd construct with just one associated
8717         // for-loop may be listed in a linear clause with a constant-linear-step
8718         // that is the increment of the associated for-loop. The loop iteration
8719         // variable(s) in the associated for-loop(s) of a for or parallel for
8720         // construct may be listed in a private or lastprivate clause.
8721         DSAStackTy::DSAVarData DVar =
8722             DSAStack->getTopDSA(D, /*FromParent=*/false);
8723         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8724         // is declared in the loop and it is predetermined as a private.
8725         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8726         OpenMPClauseKind PredeterminedCKind =
8727             isOpenMPSimdDirective(DKind)
8728                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8729                 : OMPC_private;
8730         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8731               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8732               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8733                                          DVar.CKind != OMPC_private))) ||
8734              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8735                DKind == OMPD_master_taskloop ||
8736                DKind == OMPD_parallel_master_taskloop ||
8737                isOpenMPDistributeDirective(DKind)) &&
8738               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8739               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8740             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8741           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8742               << getOpenMPClauseName(DVar.CKind)
8743               << getOpenMPDirectiveName(DKind)
8744               << getOpenMPClauseName(PredeterminedCKind);
8745           if (DVar.RefExpr == nullptr)
8746             DVar.CKind = PredeterminedCKind;
8747           reportOriginalDsa(*this, DSAStack, D, DVar,
8748                             /*IsLoopIterVar=*/true);
8749         } else if (LoopDeclRefExpr) {
8750           // Make the loop iteration variable private (for worksharing
8751           // constructs), linear (for simd directives with the only one
8752           // associated loop) or lastprivate (for simd directives with several
8753           // collapsed or ordered loops).
8754           if (DVar.CKind == OMPC_unknown)
8755             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8756                              PrivateRef);
8757         }
8758       }
8759     }
8760     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8761   }
8762 }
8763 
8764 /// Called on a for stmt to check and extract its iteration space
8765 /// for further processing (such as collapsing).
8766 static bool checkOpenMPIterationSpace(
8767     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8768     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8769     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8770     Expr *OrderedLoopCountExpr,
8771     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8772     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8773     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8774   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8775   // OpenMP [2.9.1, Canonical Loop Form]
8776   //   for (init-expr; test-expr; incr-expr) structured-block
8777   //   for (range-decl: range-expr) structured-block
8778   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8779     S = CanonLoop->getLoopStmt();
8780   auto *For = dyn_cast_or_null<ForStmt>(S);
8781   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8782   // Ranged for is supported only in OpenMP 5.0.
8783   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8784     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8785         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8786         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8787         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8788     if (TotalNestedLoopCount > 1) {
8789       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8790         SemaRef.Diag(DSA.getConstructLoc(),
8791                      diag::note_omp_collapse_ordered_expr)
8792             << 2 << CollapseLoopCountExpr->getSourceRange()
8793             << OrderedLoopCountExpr->getSourceRange();
8794       else if (CollapseLoopCountExpr)
8795         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8796                      diag::note_omp_collapse_ordered_expr)
8797             << 0 << CollapseLoopCountExpr->getSourceRange();
8798       else
8799         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8800                      diag::note_omp_collapse_ordered_expr)
8801             << 1 << OrderedLoopCountExpr->getSourceRange();
8802     }
8803     return true;
8804   }
8805   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8806          "No loop body.");
8807   // Postpone analysis in dependent contexts for ranged for loops.
8808   if (CXXFor && SemaRef.CurContext->isDependentContext())
8809     return false;
8810 
8811   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8812                                   For ? For->getForLoc() : CXXFor->getForLoc());
8813 
8814   // Check init.
8815   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8816   if (ISC.checkAndSetInit(Init))
8817     return true;
8818 
8819   bool HasErrors = false;
8820 
8821   // Check loop variable's type.
8822   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8823     // OpenMP [2.6, Canonical Loop Form]
8824     // Var is one of the following:
8825     //   A variable of signed or unsigned integer type.
8826     //   For C++, a variable of a random access iterator type.
8827     //   For C, a variable of a pointer type.
8828     QualType VarType = LCDecl->getType().getNonReferenceType();
8829     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8830         !VarType->isPointerType() &&
8831         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8832       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8833           << SemaRef.getLangOpts().CPlusPlus;
8834       HasErrors = true;
8835     }
8836 
8837     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8838     // a Construct
8839     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8840     // parallel for construct is (are) private.
8841     // The loop iteration variable in the associated for-loop of a simd
8842     // construct with just one associated for-loop is linear with a
8843     // constant-linear-step that is the increment of the associated for-loop.
8844     // Exclude loop var from the list of variables with implicitly defined data
8845     // sharing attributes.
8846     VarsWithImplicitDSA.erase(LCDecl);
8847 
8848     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8849 
8850     // Check test-expr.
8851     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8852 
8853     // Check incr-expr.
8854     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8855   }
8856 
8857   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8858     return HasErrors;
8859 
8860   // Build the loop's iteration space representation.
8861   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8862       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8863   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8864       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8865                              (isOpenMPWorksharingDirective(DKind) ||
8866                               isOpenMPGenericLoopDirective(DKind) ||
8867                               isOpenMPTaskLoopDirective(DKind) ||
8868                               isOpenMPDistributeDirective(DKind) ||
8869                               isOpenMPLoopTransformationDirective(DKind)),
8870                              Captures);
8871   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8872       ISC.buildCounterVar(Captures, DSA);
8873   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8874       ISC.buildPrivateCounterVar();
8875   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8876   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8877   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8878   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8879       ISC.getConditionSrcRange();
8880   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8881       ISC.getIncrementSrcRange();
8882   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8883   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8884       ISC.isStrictTestOp();
8885   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8886            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8887       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8888   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8889       ISC.buildFinalCondition(DSA.getCurScope());
8890   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8891       ISC.doesInitDependOnLC();
8892   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8893       ISC.doesCondDependOnLC();
8894   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8895       ISC.getLoopDependentIdx();
8896 
8897   HasErrors |=
8898       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8899        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8900        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8901        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8902        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8903        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8904   if (!HasErrors && DSA.isOrderedRegion()) {
8905     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8906       if (CurrentNestedLoopCount <
8907           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8908         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8909             CurrentNestedLoopCount,
8910             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8911         DSA.getOrderedRegionParam().second->setLoopCounter(
8912             CurrentNestedLoopCount,
8913             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8914       }
8915     }
8916     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8917       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8918         // Erroneous case - clause has some problems.
8919         continue;
8920       }
8921       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8922           Pair.second.size() <= CurrentNestedLoopCount) {
8923         // Erroneous case - clause has some problems.
8924         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8925         continue;
8926       }
8927       Expr *CntValue;
8928       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8929         CntValue = ISC.buildOrderedLoopData(
8930             DSA.getCurScope(),
8931             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8932             Pair.first->getDependencyLoc());
8933       else
8934         CntValue = ISC.buildOrderedLoopData(
8935             DSA.getCurScope(),
8936             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8937             Pair.first->getDependencyLoc(),
8938             Pair.second[CurrentNestedLoopCount].first,
8939             Pair.second[CurrentNestedLoopCount].second);
8940       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8941     }
8942   }
8943 
8944   return HasErrors;
8945 }
8946 
8947 /// Build 'VarRef = Start.
8948 static ExprResult
8949 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8950                  ExprResult Start, bool IsNonRectangularLB,
8951                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8952   // Build 'VarRef = Start.
8953   ExprResult NewStart = IsNonRectangularLB
8954                             ? Start.get()
8955                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8956   if (!NewStart.isUsable())
8957     return ExprError();
8958   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8959                                    VarRef.get()->getType())) {
8960     NewStart = SemaRef.PerformImplicitConversion(
8961         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8962         /*AllowExplicit=*/true);
8963     if (!NewStart.isUsable())
8964       return ExprError();
8965   }
8966 
8967   ExprResult Init =
8968       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8969   return Init;
8970 }
8971 
8972 /// Build 'VarRef = Start + Iter * Step'.
8973 static ExprResult buildCounterUpdate(
8974     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8975     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8976     bool IsNonRectangularLB,
8977     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8978   // Add parentheses (for debugging purposes only).
8979   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8980   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8981       !Step.isUsable())
8982     return ExprError();
8983 
8984   ExprResult NewStep = Step;
8985   if (Captures)
8986     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8987   if (NewStep.isInvalid())
8988     return ExprError();
8989   ExprResult Update =
8990       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8991   if (!Update.isUsable())
8992     return ExprError();
8993 
8994   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8995   // 'VarRef = Start (+|-) Iter * Step'.
8996   if (!Start.isUsable())
8997     return ExprError();
8998   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8999   if (!NewStart.isUsable())
9000     return ExprError();
9001   if (Captures && !IsNonRectangularLB)
9002     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
9003   if (NewStart.isInvalid())
9004     return ExprError();
9005 
9006   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
9007   ExprResult SavedUpdate = Update;
9008   ExprResult UpdateVal;
9009   if (VarRef.get()->getType()->isOverloadableType() ||
9010       NewStart.get()->getType()->isOverloadableType() ||
9011       Update.get()->getType()->isOverloadableType()) {
9012     Sema::TentativeAnalysisScope Trap(SemaRef);
9013 
9014     Update =
9015         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9016     if (Update.isUsable()) {
9017       UpdateVal =
9018           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
9019                              VarRef.get(), SavedUpdate.get());
9020       if (UpdateVal.isUsable()) {
9021         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
9022                                             UpdateVal.get());
9023       }
9024     }
9025   }
9026 
9027   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
9028   if (!Update.isUsable() || !UpdateVal.isUsable()) {
9029     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
9030                                 NewStart.get(), SavedUpdate.get());
9031     if (!Update.isUsable())
9032       return ExprError();
9033 
9034     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
9035                                      VarRef.get()->getType())) {
9036       Update = SemaRef.PerformImplicitConversion(
9037           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
9038       if (!Update.isUsable())
9039         return ExprError();
9040     }
9041 
9042     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
9043   }
9044   return Update;
9045 }
9046 
9047 /// Convert integer expression \a E to make it have at least \a Bits
9048 /// bits.
9049 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
9050   if (E == nullptr)
9051     return ExprError();
9052   ASTContext &C = SemaRef.Context;
9053   QualType OldType = E->getType();
9054   unsigned HasBits = C.getTypeSize(OldType);
9055   if (HasBits >= Bits)
9056     return ExprResult(E);
9057   // OK to convert to signed, because new type has more bits than old.
9058   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
9059   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
9060                                            true);
9061 }
9062 
9063 /// Check if the given expression \a E is a constant integer that fits
9064 /// into \a Bits bits.
9065 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
9066   if (E == nullptr)
9067     return false;
9068   if (Optional<llvm::APSInt> Result =
9069           E->getIntegerConstantExpr(SemaRef.Context))
9070     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
9071   return false;
9072 }
9073 
9074 /// Build preinits statement for the given declarations.
9075 static Stmt *buildPreInits(ASTContext &Context,
9076                            MutableArrayRef<Decl *> PreInits) {
9077   if (!PreInits.empty()) {
9078     return new (Context) DeclStmt(
9079         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
9080         SourceLocation(), SourceLocation());
9081   }
9082   return nullptr;
9083 }
9084 
9085 /// Build preinits statement for the given declarations.
9086 static Stmt *
9087 buildPreInits(ASTContext &Context,
9088               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9089   if (!Captures.empty()) {
9090     SmallVector<Decl *, 16> PreInits;
9091     for (const auto &Pair : Captures)
9092       PreInits.push_back(Pair.second->getDecl());
9093     return buildPreInits(Context, PreInits);
9094   }
9095   return nullptr;
9096 }
9097 
9098 /// Build postupdate expression for the given list of postupdates expressions.
9099 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
9100   Expr *PostUpdate = nullptr;
9101   if (!PostUpdates.empty()) {
9102     for (Expr *E : PostUpdates) {
9103       Expr *ConvE = S.BuildCStyleCastExpr(
9104                          E->getExprLoc(),
9105                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
9106                          E->getExprLoc(), E)
9107                         .get();
9108       PostUpdate = PostUpdate
9109                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
9110                                               PostUpdate, ConvE)
9111                              .get()
9112                        : ConvE;
9113     }
9114   }
9115   return PostUpdate;
9116 }
9117 
9118 /// Called on a for stmt to check itself and nested loops (if any).
9119 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
9120 /// number of collapsed loops otherwise.
9121 static unsigned
9122 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
9123                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
9124                 DSAStackTy &DSA,
9125                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
9126                 OMPLoopBasedDirective::HelperExprs &Built) {
9127   unsigned NestedLoopCount = 1;
9128   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
9129                                     !isOpenMPLoopTransformationDirective(DKind);
9130 
9131   if (CollapseLoopCountExpr) {
9132     // Found 'collapse' clause - calculate collapse number.
9133     Expr::EvalResult Result;
9134     if (!CollapseLoopCountExpr->isValueDependent() &&
9135         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
9136       NestedLoopCount = Result.Val.getInt().getLimitedValue();
9137     } else {
9138       Built.clear(/*Size=*/1);
9139       return 1;
9140     }
9141   }
9142   unsigned OrderedLoopCount = 1;
9143   if (OrderedLoopCountExpr) {
9144     // Found 'ordered' clause - calculate collapse number.
9145     Expr::EvalResult EVResult;
9146     if (!OrderedLoopCountExpr->isValueDependent() &&
9147         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
9148                                             SemaRef.getASTContext())) {
9149       llvm::APSInt Result = EVResult.Val.getInt();
9150       if (Result.getLimitedValue() < NestedLoopCount) {
9151         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
9152                      diag::err_omp_wrong_ordered_loop_count)
9153             << OrderedLoopCountExpr->getSourceRange();
9154         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9155                      diag::note_collapse_loop_count)
9156             << CollapseLoopCountExpr->getSourceRange();
9157       }
9158       OrderedLoopCount = Result.getLimitedValue();
9159     } else {
9160       Built.clear(/*Size=*/1);
9161       return 1;
9162     }
9163   }
9164   // This is helper routine for loop directives (e.g., 'for', 'simd',
9165   // 'for simd', etc.).
9166   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9167   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
9168   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
9169   if (!OMPLoopBasedDirective::doForAllLoops(
9170           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
9171           SupportsNonPerfectlyNested, NumLoops,
9172           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
9173            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
9174            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
9175             if (checkOpenMPIterationSpace(
9176                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
9177                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
9178                     VarsWithImplicitDSA, IterSpaces, Captures))
9179               return true;
9180             if (Cnt > 0 && Cnt >= NestedLoopCount &&
9181                 IterSpaces[Cnt].CounterVar) {
9182               // Handle initialization of captured loop iterator variables.
9183               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
9184               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
9185                 Captures[DRE] = DRE;
9186               }
9187             }
9188             return false;
9189           },
9190           [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
9191             Stmt *DependentPreInits = Transform->getPreInits();
9192             if (!DependentPreInits)
9193               return;
9194             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9195               auto *D = cast<VarDecl>(C);
9196               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9197                                                   Transform->getBeginLoc());
9198               Captures[Ref] = Ref;
9199             }
9200           }))
9201     return 0;
9202 
9203   Built.clear(/* size */ NestedLoopCount);
9204 
9205   if (SemaRef.CurContext->isDependentContext())
9206     return NestedLoopCount;
9207 
9208   // An example of what is generated for the following code:
9209   //
9210   //   #pragma omp simd collapse(2) ordered(2)
9211   //   for (i = 0; i < NI; ++i)
9212   //     for (k = 0; k < NK; ++k)
9213   //       for (j = J0; j < NJ; j+=2) {
9214   //         <loop body>
9215   //       }
9216   //
9217   // We generate the code below.
9218   // Note: the loop body may be outlined in CodeGen.
9219   // Note: some counters may be C++ classes, operator- is used to find number of
9220   // iterations and operator+= to calculate counter value.
9221   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9222   // or i64 is currently supported).
9223   //
9224   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9225   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9226   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9227   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9228   //     // similar updates for vars in clauses (e.g. 'linear')
9229   //     <loop body (using local i and j)>
9230   //   }
9231   //   i = NI; // assign final values of counters
9232   //   j = NJ;
9233   //
9234 
9235   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9236   // the iteration counts of the collapsed for loops.
9237   // Precondition tests if there is at least one iteration (all conditions are
9238   // true).
9239   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9240   Expr *N0 = IterSpaces[0].NumIterations;
9241   ExprResult LastIteration32 =
9242       widenIterationCount(/*Bits=*/32,
9243                           SemaRef
9244                               .PerformImplicitConversion(
9245                                   N0->IgnoreImpCasts(), N0->getType(),
9246                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9247                               .get(),
9248                           SemaRef);
9249   ExprResult LastIteration64 = widenIterationCount(
9250       /*Bits=*/64,
9251       SemaRef
9252           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9253                                      Sema::AA_Converting,
9254                                      /*AllowExplicit=*/true)
9255           .get(),
9256       SemaRef);
9257 
9258   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9259     return NestedLoopCount;
9260 
9261   ASTContext &C = SemaRef.Context;
9262   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9263 
9264   Scope *CurScope = DSA.getCurScope();
9265   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9266     if (PreCond.isUsable()) {
9267       PreCond =
9268           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9269                              PreCond.get(), IterSpaces[Cnt].PreCond);
9270     }
9271     Expr *N = IterSpaces[Cnt].NumIterations;
9272     SourceLocation Loc = N->getExprLoc();
9273     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9274     if (LastIteration32.isUsable())
9275       LastIteration32 = SemaRef.BuildBinOp(
9276           CurScope, Loc, BO_Mul, LastIteration32.get(),
9277           SemaRef
9278               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9279                                          Sema::AA_Converting,
9280                                          /*AllowExplicit=*/true)
9281               .get());
9282     if (LastIteration64.isUsable())
9283       LastIteration64 = SemaRef.BuildBinOp(
9284           CurScope, Loc, BO_Mul, LastIteration64.get(),
9285           SemaRef
9286               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9287                                          Sema::AA_Converting,
9288                                          /*AllowExplicit=*/true)
9289               .get());
9290   }
9291 
9292   // Choose either the 32-bit or 64-bit version.
9293   ExprResult LastIteration = LastIteration64;
9294   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9295       (LastIteration32.isUsable() &&
9296        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9297        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9298         fitsInto(
9299             /*Bits=*/32,
9300             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9301             LastIteration64.get(), SemaRef))))
9302     LastIteration = LastIteration32;
9303   QualType VType = LastIteration.get()->getType();
9304   QualType RealVType = VType;
9305   QualType StrideVType = VType;
9306   if (isOpenMPTaskLoopDirective(DKind)) {
9307     VType =
9308         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9309     StrideVType =
9310         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9311   }
9312 
9313   if (!LastIteration.isUsable())
9314     return 0;
9315 
9316   // Save the number of iterations.
9317   ExprResult NumIterations = LastIteration;
9318   {
9319     LastIteration = SemaRef.BuildBinOp(
9320         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9321         LastIteration.get(),
9322         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9323     if (!LastIteration.isUsable())
9324       return 0;
9325   }
9326 
9327   // Calculate the last iteration number beforehand instead of doing this on
9328   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9329   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9330   ExprResult CalcLastIteration;
9331   if (!IsConstant) {
9332     ExprResult SaveRef =
9333         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9334     LastIteration = SaveRef;
9335 
9336     // Prepare SaveRef + 1.
9337     NumIterations = SemaRef.BuildBinOp(
9338         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9339         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9340     if (!NumIterations.isUsable())
9341       return 0;
9342   }
9343 
9344   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9345 
9346   // Build variables passed into runtime, necessary for worksharing directives.
9347   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9348   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9349       isOpenMPDistributeDirective(DKind) ||
9350       isOpenMPGenericLoopDirective(DKind) ||
9351       isOpenMPLoopTransformationDirective(DKind)) {
9352     // Lower bound variable, initialized with zero.
9353     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9354     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9355     SemaRef.AddInitializerToDecl(LBDecl,
9356                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9357                                  /*DirectInit*/ false);
9358 
9359     // Upper bound variable, initialized with last iteration number.
9360     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9361     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9362     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9363                                  /*DirectInit*/ false);
9364 
9365     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9366     // This will be used to implement clause 'lastprivate'.
9367     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9368     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9369     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9370     SemaRef.AddInitializerToDecl(ILDecl,
9371                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9372                                  /*DirectInit*/ false);
9373 
9374     // Stride variable returned by runtime (we initialize it to 1 by default).
9375     VarDecl *STDecl =
9376         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9377     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9378     SemaRef.AddInitializerToDecl(STDecl,
9379                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9380                                  /*DirectInit*/ false);
9381 
9382     // Build expression: UB = min(UB, LastIteration)
9383     // It is necessary for CodeGen of directives with static scheduling.
9384     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9385                                                 UB.get(), LastIteration.get());
9386     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9387         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9388         LastIteration.get(), UB.get());
9389     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9390                              CondOp.get());
9391     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9392 
9393     // If we have a combined directive that combines 'distribute', 'for' or
9394     // 'simd' we need to be able to access the bounds of the schedule of the
9395     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9396     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9397     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9398       // Lower bound variable, initialized with zero.
9399       VarDecl *CombLBDecl =
9400           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9401       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9402       SemaRef.AddInitializerToDecl(
9403           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9404           /*DirectInit*/ false);
9405 
9406       // Upper bound variable, initialized with last iteration number.
9407       VarDecl *CombUBDecl =
9408           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9409       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9410       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9411                                    /*DirectInit*/ false);
9412 
9413       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9414           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9415       ExprResult CombCondOp =
9416           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9417                                      LastIteration.get(), CombUB.get());
9418       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9419                                    CombCondOp.get());
9420       CombEUB =
9421           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9422 
9423       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9424       // We expect to have at least 2 more parameters than the 'parallel'
9425       // directive does - the lower and upper bounds of the previous schedule.
9426       assert(CD->getNumParams() >= 4 &&
9427              "Unexpected number of parameters in loop combined directive");
9428 
9429       // Set the proper type for the bounds given what we learned from the
9430       // enclosed loops.
9431       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9432       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9433 
9434       // Previous lower and upper bounds are obtained from the region
9435       // parameters.
9436       PrevLB =
9437           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9438       PrevUB =
9439           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9440     }
9441   }
9442 
9443   // Build the iteration variable and its initialization before loop.
9444   ExprResult IV;
9445   ExprResult Init, CombInit;
9446   {
9447     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9448     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9449     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9450                  isOpenMPGenericLoopDirective(DKind) ||
9451                  isOpenMPTaskLoopDirective(DKind) ||
9452                  isOpenMPDistributeDirective(DKind) ||
9453                  isOpenMPLoopTransformationDirective(DKind))
9454                     ? LB.get()
9455                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9456     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9457     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9458 
9459     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9460       Expr *CombRHS =
9461           (isOpenMPWorksharingDirective(DKind) ||
9462            isOpenMPGenericLoopDirective(DKind) ||
9463            isOpenMPTaskLoopDirective(DKind) ||
9464            isOpenMPDistributeDirective(DKind))
9465               ? CombLB.get()
9466               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9467       CombInit =
9468           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9469       CombInit =
9470           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9471     }
9472   }
9473 
9474   bool UseStrictCompare =
9475       RealVType->hasUnsignedIntegerRepresentation() &&
9476       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9477         return LIS.IsStrictCompare;
9478       });
9479   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9480   // unsigned IV)) for worksharing loops.
9481   SourceLocation CondLoc = AStmt->getBeginLoc();
9482   Expr *BoundUB = UB.get();
9483   if (UseStrictCompare) {
9484     BoundUB =
9485         SemaRef
9486             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9487                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9488             .get();
9489     BoundUB =
9490         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9491   }
9492   ExprResult Cond =
9493       (isOpenMPWorksharingDirective(DKind) ||
9494        isOpenMPGenericLoopDirective(DKind) ||
9495        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9496        isOpenMPLoopTransformationDirective(DKind))
9497           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9498                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9499                                BoundUB)
9500           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9501                                NumIterations.get());
9502   ExprResult CombDistCond;
9503   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9504     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9505                                       NumIterations.get());
9506   }
9507 
9508   ExprResult CombCond;
9509   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9510     Expr *BoundCombUB = CombUB.get();
9511     if (UseStrictCompare) {
9512       BoundCombUB =
9513           SemaRef
9514               .BuildBinOp(
9515                   CurScope, CondLoc, BO_Add, BoundCombUB,
9516                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9517               .get();
9518       BoundCombUB =
9519           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9520               .get();
9521     }
9522     CombCond =
9523         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9524                            IV.get(), BoundCombUB);
9525   }
9526   // Loop increment (IV = IV + 1)
9527   SourceLocation IncLoc = AStmt->getBeginLoc();
9528   ExprResult Inc =
9529       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9530                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9531   if (!Inc.isUsable())
9532     return 0;
9533   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9534   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9535   if (!Inc.isUsable())
9536     return 0;
9537 
9538   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9539   // Used for directives with static scheduling.
9540   // In combined construct, add combined version that use CombLB and CombUB
9541   // base variables for the update
9542   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9543   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9544       isOpenMPGenericLoopDirective(DKind) ||
9545       isOpenMPDistributeDirective(DKind) ||
9546       isOpenMPLoopTransformationDirective(DKind)) {
9547     // LB + ST
9548     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9549     if (!NextLB.isUsable())
9550       return 0;
9551     // LB = LB + ST
9552     NextLB =
9553         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9554     NextLB =
9555         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9556     if (!NextLB.isUsable())
9557       return 0;
9558     // UB + ST
9559     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9560     if (!NextUB.isUsable())
9561       return 0;
9562     // UB = UB + ST
9563     NextUB =
9564         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9565     NextUB =
9566         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9567     if (!NextUB.isUsable())
9568       return 0;
9569     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9570       CombNextLB =
9571           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9572       if (!NextLB.isUsable())
9573         return 0;
9574       // LB = LB + ST
9575       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9576                                       CombNextLB.get());
9577       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9578                                                /*DiscardedValue*/ false);
9579       if (!CombNextLB.isUsable())
9580         return 0;
9581       // UB + ST
9582       CombNextUB =
9583           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9584       if (!CombNextUB.isUsable())
9585         return 0;
9586       // UB = UB + ST
9587       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9588                                       CombNextUB.get());
9589       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9590                                                /*DiscardedValue*/ false);
9591       if (!CombNextUB.isUsable())
9592         return 0;
9593     }
9594   }
9595 
9596   // Create increment expression for distribute loop when combined in a same
9597   // directive with for as IV = IV + ST; ensure upper bound expression based
9598   // on PrevUB instead of NumIterations - used to implement 'for' when found
9599   // in combination with 'distribute', like in 'distribute parallel for'
9600   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9601   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9602   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9603     DistCond = SemaRef.BuildBinOp(
9604         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9605     assert(DistCond.isUsable() && "distribute cond expr was not built");
9606 
9607     DistInc =
9608         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9609     assert(DistInc.isUsable() && "distribute inc expr was not built");
9610     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9611                                  DistInc.get());
9612     DistInc =
9613         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9614     assert(DistInc.isUsable() && "distribute inc expr was not built");
9615 
9616     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9617     // construct
9618     ExprResult NewPrevUB = PrevUB;
9619     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9620     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9621                                      PrevUB.get()->getType())) {
9622       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9623           DistEUBLoc,
9624           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9625           DistEUBLoc, NewPrevUB.get());
9626       if (!NewPrevUB.isUsable())
9627         return 0;
9628     }
9629     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9630                                                 UB.get(), NewPrevUB.get());
9631     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9632         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9633     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9634                                  CondOp.get());
9635     PrevEUB =
9636         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9637 
9638     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9639     // parallel for is in combination with a distribute directive with
9640     // schedule(static, 1)
9641     Expr *BoundPrevUB = PrevUB.get();
9642     if (UseStrictCompare) {
9643       BoundPrevUB =
9644           SemaRef
9645               .BuildBinOp(
9646                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9647                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9648               .get();
9649       BoundPrevUB =
9650           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9651               .get();
9652     }
9653     ParForInDistCond =
9654         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9655                            IV.get(), BoundPrevUB);
9656   }
9657 
9658   // Build updates and final values of the loop counters.
9659   bool HasErrors = false;
9660   Built.Counters.resize(NestedLoopCount);
9661   Built.Inits.resize(NestedLoopCount);
9662   Built.Updates.resize(NestedLoopCount);
9663   Built.Finals.resize(NestedLoopCount);
9664   Built.DependentCounters.resize(NestedLoopCount);
9665   Built.DependentInits.resize(NestedLoopCount);
9666   Built.FinalsConditions.resize(NestedLoopCount);
9667   {
9668     // We implement the following algorithm for obtaining the
9669     // original loop iteration variable values based on the
9670     // value of the collapsed loop iteration variable IV.
9671     //
9672     // Let n+1 be the number of collapsed loops in the nest.
9673     // Iteration variables (I0, I1, .... In)
9674     // Iteration counts (N0, N1, ... Nn)
9675     //
9676     // Acc = IV;
9677     //
9678     // To compute Ik for loop k, 0 <= k <= n, generate:
9679     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9680     //    Ik = Acc / Prod;
9681     //    Acc -= Ik * Prod;
9682     //
9683     ExprResult Acc = IV;
9684     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9685       LoopIterationSpace &IS = IterSpaces[Cnt];
9686       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9687       ExprResult Iter;
9688 
9689       // Compute prod
9690       ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9691       for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
9692         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9693                                   IterSpaces[K].NumIterations);
9694 
9695       // Iter = Acc / Prod
9696       // If there is at least one more inner loop to avoid
9697       // multiplication by 1.
9698       if (Cnt + 1 < NestedLoopCount)
9699         Iter =
9700             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
9701       else
9702         Iter = Acc;
9703       if (!Iter.isUsable()) {
9704         HasErrors = true;
9705         break;
9706       }
9707 
9708       // Update Acc:
9709       // Acc -= Iter * Prod
9710       // Check if there is at least one more inner loop to avoid
9711       // multiplication by 1.
9712       if (Cnt + 1 < NestedLoopCount)
9713         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
9714                                   Prod.get());
9715       else
9716         Prod = Iter;
9717       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
9718 
9719       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9720       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9721       DeclRefExpr *CounterVar = buildDeclRefExpr(
9722           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9723           /*RefersToCapture=*/true);
9724       ExprResult Init =
9725           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9726                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9727       if (!Init.isUsable()) {
9728         HasErrors = true;
9729         break;
9730       }
9731       ExprResult Update = buildCounterUpdate(
9732           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9733           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9734       if (!Update.isUsable()) {
9735         HasErrors = true;
9736         break;
9737       }
9738 
9739       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9740       ExprResult Final =
9741           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9742                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9743                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9744       if (!Final.isUsable()) {
9745         HasErrors = true;
9746         break;
9747       }
9748 
9749       if (!Update.isUsable() || !Final.isUsable()) {
9750         HasErrors = true;
9751         break;
9752       }
9753       // Save results
9754       Built.Counters[Cnt] = IS.CounterVar;
9755       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9756       Built.Inits[Cnt] = Init.get();
9757       Built.Updates[Cnt] = Update.get();
9758       Built.Finals[Cnt] = Final.get();
9759       Built.DependentCounters[Cnt] = nullptr;
9760       Built.DependentInits[Cnt] = nullptr;
9761       Built.FinalsConditions[Cnt] = nullptr;
9762       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9763         Built.DependentCounters[Cnt] =
9764             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9765         Built.DependentInits[Cnt] =
9766             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9767         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9768       }
9769     }
9770   }
9771 
9772   if (HasErrors)
9773     return 0;
9774 
9775   // Save results
9776   Built.IterationVarRef = IV.get();
9777   Built.LastIteration = LastIteration.get();
9778   Built.NumIterations = NumIterations.get();
9779   Built.CalcLastIteration = SemaRef
9780                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9781                                                      /*DiscardedValue=*/false)
9782                                 .get();
9783   Built.PreCond = PreCond.get();
9784   Built.PreInits = buildPreInits(C, Captures);
9785   Built.Cond = Cond.get();
9786   Built.Init = Init.get();
9787   Built.Inc = Inc.get();
9788   Built.LB = LB.get();
9789   Built.UB = UB.get();
9790   Built.IL = IL.get();
9791   Built.ST = ST.get();
9792   Built.EUB = EUB.get();
9793   Built.NLB = NextLB.get();
9794   Built.NUB = NextUB.get();
9795   Built.PrevLB = PrevLB.get();
9796   Built.PrevUB = PrevUB.get();
9797   Built.DistInc = DistInc.get();
9798   Built.PrevEUB = PrevEUB.get();
9799   Built.DistCombinedFields.LB = CombLB.get();
9800   Built.DistCombinedFields.UB = CombUB.get();
9801   Built.DistCombinedFields.EUB = CombEUB.get();
9802   Built.DistCombinedFields.Init = CombInit.get();
9803   Built.DistCombinedFields.Cond = CombCond.get();
9804   Built.DistCombinedFields.NLB = CombNextLB.get();
9805   Built.DistCombinedFields.NUB = CombNextUB.get();
9806   Built.DistCombinedFields.DistCond = CombDistCond.get();
9807   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9808 
9809   return NestedLoopCount;
9810 }
9811 
9812 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9813   auto CollapseClauses =
9814       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9815   if (CollapseClauses.begin() != CollapseClauses.end())
9816     return (*CollapseClauses.begin())->getNumForLoops();
9817   return nullptr;
9818 }
9819 
9820 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9821   auto OrderedClauses =
9822       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9823   if (OrderedClauses.begin() != OrderedClauses.end())
9824     return (*OrderedClauses.begin())->getNumForLoops();
9825   return nullptr;
9826 }
9827 
9828 static bool checkSimdlenSafelenSpecified(Sema &S,
9829                                          const ArrayRef<OMPClause *> Clauses) {
9830   const OMPSafelenClause *Safelen = nullptr;
9831   const OMPSimdlenClause *Simdlen = nullptr;
9832 
9833   for (const OMPClause *Clause : Clauses) {
9834     if (Clause->getClauseKind() == OMPC_safelen)
9835       Safelen = cast<OMPSafelenClause>(Clause);
9836     else if (Clause->getClauseKind() == OMPC_simdlen)
9837       Simdlen = cast<OMPSimdlenClause>(Clause);
9838     if (Safelen && Simdlen)
9839       break;
9840   }
9841 
9842   if (Simdlen && Safelen) {
9843     const Expr *SimdlenLength = Simdlen->getSimdlen();
9844     const Expr *SafelenLength = Safelen->getSafelen();
9845     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9846         SimdlenLength->isInstantiationDependent() ||
9847         SimdlenLength->containsUnexpandedParameterPack())
9848       return false;
9849     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9850         SafelenLength->isInstantiationDependent() ||
9851         SafelenLength->containsUnexpandedParameterPack())
9852       return false;
9853     Expr::EvalResult SimdlenResult, SafelenResult;
9854     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9855     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9856     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9857     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9858     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9859     // If both simdlen and safelen clauses are specified, the value of the
9860     // simdlen parameter must be less than or equal to the value of the safelen
9861     // parameter.
9862     if (SimdlenRes > SafelenRes) {
9863       S.Diag(SimdlenLength->getExprLoc(),
9864              diag::err_omp_wrong_simdlen_safelen_values)
9865           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9866       return true;
9867     }
9868   }
9869   return false;
9870 }
9871 
9872 StmtResult
9873 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9874                                SourceLocation StartLoc, SourceLocation EndLoc,
9875                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9876   if (!AStmt)
9877     return StmtError();
9878 
9879   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9880   OMPLoopBasedDirective::HelperExprs B;
9881   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9882   // define the nested loops number.
9883   unsigned NestedLoopCount = checkOpenMPLoop(
9884       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9885       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9886   if (NestedLoopCount == 0)
9887     return StmtError();
9888 
9889   assert((CurContext->isDependentContext() || B.builtAll()) &&
9890          "omp simd loop exprs were not built");
9891 
9892   if (!CurContext->isDependentContext()) {
9893     // Finalize the clauses that need pre-built expressions for CodeGen.
9894     for (OMPClause *C : Clauses) {
9895       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9896         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9897                                      B.NumIterations, *this, CurScope,
9898                                      DSAStack))
9899           return StmtError();
9900     }
9901   }
9902 
9903   if (checkSimdlenSafelenSpecified(*this, Clauses))
9904     return StmtError();
9905 
9906   setFunctionHasBranchProtectedScope();
9907   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9908                                   Clauses, AStmt, B);
9909 }
9910 
9911 StmtResult
9912 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9913                               SourceLocation StartLoc, SourceLocation EndLoc,
9914                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9915   if (!AStmt)
9916     return StmtError();
9917 
9918   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9919   OMPLoopBasedDirective::HelperExprs B;
9920   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9921   // define the nested loops number.
9922   unsigned NestedLoopCount = checkOpenMPLoop(
9923       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9924       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9925   if (NestedLoopCount == 0)
9926     return StmtError();
9927 
9928   assert((CurContext->isDependentContext() || B.builtAll()) &&
9929          "omp for loop exprs were not built");
9930 
9931   if (!CurContext->isDependentContext()) {
9932     // Finalize the clauses that need pre-built expressions for CodeGen.
9933     for (OMPClause *C : Clauses) {
9934       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9935         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9936                                      B.NumIterations, *this, CurScope,
9937                                      DSAStack))
9938           return StmtError();
9939     }
9940   }
9941 
9942   setFunctionHasBranchProtectedScope();
9943   return OMPForDirective::Create(
9944       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9945       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9946 }
9947 
9948 StmtResult Sema::ActOnOpenMPForSimdDirective(
9949     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9950     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9951   if (!AStmt)
9952     return StmtError();
9953 
9954   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9955   OMPLoopBasedDirective::HelperExprs B;
9956   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9957   // define the nested loops number.
9958   unsigned NestedLoopCount =
9959       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9960                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9961                       VarsWithImplicitDSA, B);
9962   if (NestedLoopCount == 0)
9963     return StmtError();
9964 
9965   assert((CurContext->isDependentContext() || B.builtAll()) &&
9966          "omp for simd loop exprs were not built");
9967 
9968   if (!CurContext->isDependentContext()) {
9969     // Finalize the clauses that need pre-built expressions for CodeGen.
9970     for (OMPClause *C : Clauses) {
9971       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9972         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9973                                      B.NumIterations, *this, CurScope,
9974                                      DSAStack))
9975           return StmtError();
9976     }
9977   }
9978 
9979   if (checkSimdlenSafelenSpecified(*this, Clauses))
9980     return StmtError();
9981 
9982   setFunctionHasBranchProtectedScope();
9983   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9984                                      Clauses, AStmt, B);
9985 }
9986 
9987 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9988                                               Stmt *AStmt,
9989                                               SourceLocation StartLoc,
9990                                               SourceLocation EndLoc) {
9991   if (!AStmt)
9992     return StmtError();
9993 
9994   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9995   auto BaseStmt = AStmt;
9996   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9997     BaseStmt = CS->getCapturedStmt();
9998   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9999     auto S = C->children();
10000     if (S.begin() == S.end())
10001       return StmtError();
10002     // All associated statements must be '#pragma omp section' except for
10003     // the first one.
10004     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10005       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10006         if (SectionStmt)
10007           Diag(SectionStmt->getBeginLoc(),
10008                diag::err_omp_sections_substmt_not_section);
10009         return StmtError();
10010       }
10011       cast<OMPSectionDirective>(SectionStmt)
10012           ->setHasCancel(DSAStack->isCancelRegion());
10013     }
10014   } else {
10015     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
10016     return StmtError();
10017   }
10018 
10019   setFunctionHasBranchProtectedScope();
10020 
10021   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10022                                       DSAStack->getTaskgroupReductionRef(),
10023                                       DSAStack->isCancelRegion());
10024 }
10025 
10026 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
10027                                              SourceLocation StartLoc,
10028                                              SourceLocation EndLoc) {
10029   if (!AStmt)
10030     return StmtError();
10031 
10032   setFunctionHasBranchProtectedScope();
10033   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
10034 
10035   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
10036                                      DSAStack->isCancelRegion());
10037 }
10038 
10039 static Expr *getDirectCallExpr(Expr *E) {
10040   E = E->IgnoreParenCasts()->IgnoreImplicit();
10041   if (auto *CE = dyn_cast<CallExpr>(E))
10042     if (CE->getDirectCallee())
10043       return E;
10044   return nullptr;
10045 }
10046 
10047 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10048                                               Stmt *AStmt,
10049                                               SourceLocation StartLoc,
10050                                               SourceLocation EndLoc) {
10051   if (!AStmt)
10052     return StmtError();
10053 
10054   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
10055 
10056   // 5.1 OpenMP
10057   // expression-stmt : an expression statement with one of the following forms:
10058   //   expression = target-call ( [expression-list] );
10059   //   target-call ( [expression-list] );
10060 
10061   SourceLocation TargetCallLoc;
10062 
10063   if (!CurContext->isDependentContext()) {
10064     Expr *TargetCall = nullptr;
10065 
10066     auto *E = dyn_cast<Expr>(S);
10067     if (!E) {
10068       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10069       return StmtError();
10070     }
10071 
10072     E = E->IgnoreParenCasts()->IgnoreImplicit();
10073 
10074     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
10075       if (BO->getOpcode() == BO_Assign)
10076         TargetCall = getDirectCallExpr(BO->getRHS());
10077     } else {
10078       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
10079         if (COCE->getOperator() == OO_Equal)
10080           TargetCall = getDirectCallExpr(COCE->getArg(1));
10081       if (!TargetCall)
10082         TargetCall = getDirectCallExpr(E);
10083     }
10084     if (!TargetCall) {
10085       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10086       return StmtError();
10087     }
10088     TargetCallLoc = TargetCall->getExprLoc();
10089   }
10090 
10091   setFunctionHasBranchProtectedScope();
10092 
10093   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10094                                       TargetCallLoc);
10095 }
10096 
10097 StmtResult Sema::ActOnOpenMPGenericLoopDirective(
10098     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10099     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10100   if (!AStmt)
10101     return StmtError();
10102 
10103   // OpenMP 5.1 [2.11.7, loop construct]
10104   // A list item may not appear in a lastprivate clause unless it is the
10105   // loop iteration variable of a loop that is associated with the construct.
10106   for (OMPClause *C : Clauses) {
10107     if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
10108       for (Expr *RefExpr : LPC->varlists()) {
10109         SourceLocation ELoc;
10110         SourceRange ERange;
10111         Expr *SimpleRefExpr = RefExpr;
10112         auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10113         if (ValueDecl *D = Res.first) {
10114           auto &&Info = DSAStack->isLoopControlVariable(D);
10115           if (!Info.first) {
10116             Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration);
10117             return StmtError();
10118           }
10119         }
10120       }
10121     }
10122   }
10123 
10124   auto *CS = cast<CapturedStmt>(AStmt);
10125   // 1.2.2 OpenMP Language Terminology
10126   // Structured block - An executable statement with a single entry at the
10127   // top and a single exit at the bottom.
10128   // The point of exit cannot be a branch out of the structured block.
10129   // longjmp() and throw() must not violate the entry/exit criteria.
10130   CS->getCapturedDecl()->setNothrow();
10131 
10132   OMPLoopDirective::HelperExprs B;
10133   // In presence of clause 'collapse', it will define the nested loops number.
10134   unsigned NestedLoopCount = checkOpenMPLoop(
10135       OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10136       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10137   if (NestedLoopCount == 0)
10138     return StmtError();
10139 
10140   assert((CurContext->isDependentContext() || B.builtAll()) &&
10141          "omp loop exprs were not built");
10142 
10143   setFunctionHasBranchProtectedScope();
10144   return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
10145                                          NestedLoopCount, Clauses, AStmt, B);
10146 }
10147 
10148 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10149                                             Stmt *AStmt,
10150                                             SourceLocation StartLoc,
10151                                             SourceLocation EndLoc) {
10152   if (!AStmt)
10153     return StmtError();
10154 
10155   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10156 
10157   setFunctionHasBranchProtectedScope();
10158 
10159   // OpenMP [2.7.3, single Construct, Restrictions]
10160   // The copyprivate clause must not be used with the nowait clause.
10161   const OMPClause *Nowait = nullptr;
10162   const OMPClause *Copyprivate = nullptr;
10163   for (const OMPClause *Clause : Clauses) {
10164     if (Clause->getClauseKind() == OMPC_nowait)
10165       Nowait = Clause;
10166     else if (Clause->getClauseKind() == OMPC_copyprivate)
10167       Copyprivate = Clause;
10168     if (Copyprivate && Nowait) {
10169       Diag(Copyprivate->getBeginLoc(),
10170            diag::err_omp_single_copyprivate_with_nowait);
10171       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
10172       return StmtError();
10173     }
10174   }
10175 
10176   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10177 }
10178 
10179 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
10180                                             SourceLocation StartLoc,
10181                                             SourceLocation EndLoc) {
10182   if (!AStmt)
10183     return StmtError();
10184 
10185   setFunctionHasBranchProtectedScope();
10186 
10187   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
10188 }
10189 
10190 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10191                                             Stmt *AStmt,
10192                                             SourceLocation StartLoc,
10193                                             SourceLocation EndLoc) {
10194   if (!AStmt)
10195     return StmtError();
10196 
10197   setFunctionHasBranchProtectedScope();
10198 
10199   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10200 }
10201 
10202 StmtResult Sema::ActOnOpenMPCriticalDirective(
10203     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
10204     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
10205   if (!AStmt)
10206     return StmtError();
10207 
10208   bool ErrorFound = false;
10209   llvm::APSInt Hint;
10210   SourceLocation HintLoc;
10211   bool DependentHint = false;
10212   for (const OMPClause *C : Clauses) {
10213     if (C->getClauseKind() == OMPC_hint) {
10214       if (!DirName.getName()) {
10215         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
10216         ErrorFound = true;
10217       }
10218       Expr *E = cast<OMPHintClause>(C)->getHint();
10219       if (E->isTypeDependent() || E->isValueDependent() ||
10220           E->isInstantiationDependent()) {
10221         DependentHint = true;
10222       } else {
10223         Hint = E->EvaluateKnownConstInt(Context);
10224         HintLoc = C->getBeginLoc();
10225       }
10226     }
10227   }
10228   if (ErrorFound)
10229     return StmtError();
10230   const auto Pair = DSAStack->getCriticalWithHint(DirName);
10231   if (Pair.first && DirName.getName() && !DependentHint) {
10232     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
10233       Diag(StartLoc, diag::err_omp_critical_with_hint);
10234       if (HintLoc.isValid())
10235         Diag(HintLoc, diag::note_omp_critical_hint_here)
10236             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
10237       else
10238         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10239       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10240         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10241             << 1
10242             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10243                         /*Radix=*/10, /*Signed=*/false);
10244       } else {
10245         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10246       }
10247     }
10248   }
10249 
10250   setFunctionHasBranchProtectedScope();
10251 
10252   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10253                                            Clauses, AStmt);
10254   if (!Pair.first && DirName.getName() && !DependentHint)
10255     DSAStack->addCriticalWithHint(Dir, Hint);
10256   return Dir;
10257 }
10258 
10259 StmtResult Sema::ActOnOpenMPParallelForDirective(
10260     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10261     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10262   if (!AStmt)
10263     return StmtError();
10264 
10265   auto *CS = cast<CapturedStmt>(AStmt);
10266   // 1.2.2 OpenMP Language Terminology
10267   // Structured block - An executable statement with a single entry at the
10268   // top and a single exit at the bottom.
10269   // The point of exit cannot be a branch out of the structured block.
10270   // longjmp() and throw() must not violate the entry/exit criteria.
10271   CS->getCapturedDecl()->setNothrow();
10272 
10273   OMPLoopBasedDirective::HelperExprs B;
10274   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10275   // define the nested loops number.
10276   unsigned NestedLoopCount =
10277       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10278                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10279                       VarsWithImplicitDSA, B);
10280   if (NestedLoopCount == 0)
10281     return StmtError();
10282 
10283   assert((CurContext->isDependentContext() || B.builtAll()) &&
10284          "omp parallel for loop exprs were not built");
10285 
10286   if (!CurContext->isDependentContext()) {
10287     // Finalize the clauses that need pre-built expressions for CodeGen.
10288     for (OMPClause *C : Clauses) {
10289       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10290         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10291                                      B.NumIterations, *this, CurScope,
10292                                      DSAStack))
10293           return StmtError();
10294     }
10295   }
10296 
10297   setFunctionHasBranchProtectedScope();
10298   return OMPParallelForDirective::Create(
10299       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10300       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10301 }
10302 
10303 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10304     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10305     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10306   if (!AStmt)
10307     return StmtError();
10308 
10309   auto *CS = cast<CapturedStmt>(AStmt);
10310   // 1.2.2 OpenMP Language Terminology
10311   // Structured block - An executable statement with a single entry at the
10312   // top and a single exit at the bottom.
10313   // The point of exit cannot be a branch out of the structured block.
10314   // longjmp() and throw() must not violate the entry/exit criteria.
10315   CS->getCapturedDecl()->setNothrow();
10316 
10317   OMPLoopBasedDirective::HelperExprs B;
10318   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10319   // define the nested loops number.
10320   unsigned NestedLoopCount =
10321       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10322                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10323                       VarsWithImplicitDSA, B);
10324   if (NestedLoopCount == 0)
10325     return StmtError();
10326 
10327   if (!CurContext->isDependentContext()) {
10328     // Finalize the clauses that need pre-built expressions for CodeGen.
10329     for (OMPClause *C : Clauses) {
10330       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10331         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10332                                      B.NumIterations, *this, CurScope,
10333                                      DSAStack))
10334           return StmtError();
10335     }
10336   }
10337 
10338   if (checkSimdlenSafelenSpecified(*this, Clauses))
10339     return StmtError();
10340 
10341   setFunctionHasBranchProtectedScope();
10342   return OMPParallelForSimdDirective::Create(
10343       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10344 }
10345 
10346 StmtResult
10347 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10348                                          Stmt *AStmt, SourceLocation StartLoc,
10349                                          SourceLocation EndLoc) {
10350   if (!AStmt)
10351     return StmtError();
10352 
10353   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10354   auto *CS = cast<CapturedStmt>(AStmt);
10355   // 1.2.2 OpenMP Language Terminology
10356   // Structured block - An executable statement with a single entry at the
10357   // top and a single exit at the bottom.
10358   // The point of exit cannot be a branch out of the structured block.
10359   // longjmp() and throw() must not violate the entry/exit criteria.
10360   CS->getCapturedDecl()->setNothrow();
10361 
10362   setFunctionHasBranchProtectedScope();
10363 
10364   return OMPParallelMasterDirective::Create(
10365       Context, StartLoc, EndLoc, Clauses, AStmt,
10366       DSAStack->getTaskgroupReductionRef());
10367 }
10368 
10369 StmtResult
10370 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10371                                            Stmt *AStmt, SourceLocation StartLoc,
10372                                            SourceLocation EndLoc) {
10373   if (!AStmt)
10374     return StmtError();
10375 
10376   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10377   auto BaseStmt = AStmt;
10378   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10379     BaseStmt = CS->getCapturedStmt();
10380   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10381     auto S = C->children();
10382     if (S.begin() == S.end())
10383       return StmtError();
10384     // All associated statements must be '#pragma omp section' except for
10385     // the first one.
10386     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10387       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10388         if (SectionStmt)
10389           Diag(SectionStmt->getBeginLoc(),
10390                diag::err_omp_parallel_sections_substmt_not_section);
10391         return StmtError();
10392       }
10393       cast<OMPSectionDirective>(SectionStmt)
10394           ->setHasCancel(DSAStack->isCancelRegion());
10395     }
10396   } else {
10397     Diag(AStmt->getBeginLoc(),
10398          diag::err_omp_parallel_sections_not_compound_stmt);
10399     return StmtError();
10400   }
10401 
10402   setFunctionHasBranchProtectedScope();
10403 
10404   return OMPParallelSectionsDirective::Create(
10405       Context, StartLoc, EndLoc, Clauses, AStmt,
10406       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10407 }
10408 
10409 /// Find and diagnose mutually exclusive clause kinds.
10410 static bool checkMutuallyExclusiveClauses(
10411     Sema &S, ArrayRef<OMPClause *> Clauses,
10412     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10413   const OMPClause *PrevClause = nullptr;
10414   bool ErrorFound = false;
10415   for (const OMPClause *C : Clauses) {
10416     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10417       if (!PrevClause) {
10418         PrevClause = C;
10419       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10420         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10421             << getOpenMPClauseName(C->getClauseKind())
10422             << getOpenMPClauseName(PrevClause->getClauseKind());
10423         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10424             << getOpenMPClauseName(PrevClause->getClauseKind());
10425         ErrorFound = true;
10426       }
10427     }
10428   }
10429   return ErrorFound;
10430 }
10431 
10432 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10433                                           Stmt *AStmt, SourceLocation StartLoc,
10434                                           SourceLocation EndLoc) {
10435   if (!AStmt)
10436     return StmtError();
10437 
10438   // OpenMP 5.0, 2.10.1 task Construct
10439   // If a detach clause appears on the directive, then a mergeable clause cannot
10440   // appear on the same directive.
10441   if (checkMutuallyExclusiveClauses(*this, Clauses,
10442                                     {OMPC_detach, OMPC_mergeable}))
10443     return StmtError();
10444 
10445   auto *CS = cast<CapturedStmt>(AStmt);
10446   // 1.2.2 OpenMP Language Terminology
10447   // Structured block - An executable statement with a single entry at the
10448   // top and a single exit at the bottom.
10449   // The point of exit cannot be a branch out of the structured block.
10450   // longjmp() and throw() must not violate the entry/exit criteria.
10451   CS->getCapturedDecl()->setNothrow();
10452 
10453   setFunctionHasBranchProtectedScope();
10454 
10455   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10456                                   DSAStack->isCancelRegion());
10457 }
10458 
10459 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10460                                                SourceLocation EndLoc) {
10461   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10462 }
10463 
10464 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10465                                              SourceLocation EndLoc) {
10466   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10467 }
10468 
10469 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10470                                               SourceLocation StartLoc,
10471                                               SourceLocation EndLoc) {
10472   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
10473 }
10474 
10475 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10476                                                Stmt *AStmt,
10477                                                SourceLocation StartLoc,
10478                                                SourceLocation EndLoc) {
10479   if (!AStmt)
10480     return StmtError();
10481 
10482   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10483 
10484   setFunctionHasBranchProtectedScope();
10485 
10486   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10487                                        AStmt,
10488                                        DSAStack->getTaskgroupReductionRef());
10489 }
10490 
10491 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10492                                            SourceLocation StartLoc,
10493                                            SourceLocation EndLoc) {
10494   OMPFlushClause *FC = nullptr;
10495   OMPClause *OrderClause = nullptr;
10496   for (OMPClause *C : Clauses) {
10497     if (C->getClauseKind() == OMPC_flush)
10498       FC = cast<OMPFlushClause>(C);
10499     else
10500       OrderClause = C;
10501   }
10502   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10503   SourceLocation MemOrderLoc;
10504   for (const OMPClause *C : Clauses) {
10505     if (C->getClauseKind() == OMPC_acq_rel ||
10506         C->getClauseKind() == OMPC_acquire ||
10507         C->getClauseKind() == OMPC_release) {
10508       if (MemOrderKind != OMPC_unknown) {
10509         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10510             << getOpenMPDirectiveName(OMPD_flush) << 1
10511             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10512         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10513             << getOpenMPClauseName(MemOrderKind);
10514       } else {
10515         MemOrderKind = C->getClauseKind();
10516         MemOrderLoc = C->getBeginLoc();
10517       }
10518     }
10519   }
10520   if (FC && OrderClause) {
10521     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10522         << getOpenMPClauseName(OrderClause->getClauseKind());
10523     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10524         << getOpenMPClauseName(OrderClause->getClauseKind());
10525     return StmtError();
10526   }
10527   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10528 }
10529 
10530 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10531                                             SourceLocation StartLoc,
10532                                             SourceLocation EndLoc) {
10533   if (Clauses.empty()) {
10534     Diag(StartLoc, diag::err_omp_depobj_expected);
10535     return StmtError();
10536   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10537     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10538     return StmtError();
10539   }
10540   // Only depobj expression and another single clause is allowed.
10541   if (Clauses.size() > 2) {
10542     Diag(Clauses[2]->getBeginLoc(),
10543          diag::err_omp_depobj_single_clause_expected);
10544     return StmtError();
10545   } else if (Clauses.size() < 1) {
10546     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10547     return StmtError();
10548   }
10549   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10550 }
10551 
10552 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10553                                           SourceLocation StartLoc,
10554                                           SourceLocation EndLoc) {
10555   // Check that exactly one clause is specified.
10556   if (Clauses.size() != 1) {
10557     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10558          diag::err_omp_scan_single_clause_expected);
10559     return StmtError();
10560   }
10561   // Check that scan directive is used in the scopeof the OpenMP loop body.
10562   if (Scope *S = DSAStack->getCurScope()) {
10563     Scope *ParentS = S->getParent();
10564     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10565         !ParentS->getBreakParent()->isOpenMPLoopScope())
10566       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10567                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10568   }
10569   // Check that only one instance of scan directives is used in the same outer
10570   // region.
10571   if (DSAStack->doesParentHasScanDirective()) {
10572     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10573     Diag(DSAStack->getParentScanDirectiveLoc(),
10574          diag::note_omp_previous_directive)
10575         << "scan";
10576     return StmtError();
10577   }
10578   DSAStack->setParentHasScanDirective(StartLoc);
10579   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10580 }
10581 
10582 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10583                                              Stmt *AStmt,
10584                                              SourceLocation StartLoc,
10585                                              SourceLocation EndLoc) {
10586   const OMPClause *DependFound = nullptr;
10587   const OMPClause *DependSourceClause = nullptr;
10588   const OMPClause *DependSinkClause = nullptr;
10589   bool ErrorFound = false;
10590   const OMPThreadsClause *TC = nullptr;
10591   const OMPSIMDClause *SC = nullptr;
10592   for (const OMPClause *C : Clauses) {
10593     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10594       DependFound = C;
10595       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10596         if (DependSourceClause) {
10597           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10598               << getOpenMPDirectiveName(OMPD_ordered)
10599               << getOpenMPClauseName(OMPC_depend) << 2;
10600           ErrorFound = true;
10601         } else {
10602           DependSourceClause = C;
10603         }
10604         if (DependSinkClause) {
10605           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10606               << 0;
10607           ErrorFound = true;
10608         }
10609       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10610         if (DependSourceClause) {
10611           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10612               << 1;
10613           ErrorFound = true;
10614         }
10615         DependSinkClause = C;
10616       }
10617     } else if (C->getClauseKind() == OMPC_threads) {
10618       TC = cast<OMPThreadsClause>(C);
10619     } else if (C->getClauseKind() == OMPC_simd) {
10620       SC = cast<OMPSIMDClause>(C);
10621     }
10622   }
10623   if (!ErrorFound && !SC &&
10624       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10625     // OpenMP [2.8.1,simd Construct, Restrictions]
10626     // An ordered construct with the simd clause is the only OpenMP construct
10627     // that can appear in the simd region.
10628     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10629         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10630     ErrorFound = true;
10631   } else if (DependFound && (TC || SC)) {
10632     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10633         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10634     ErrorFound = true;
10635   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10636     Diag(DependFound->getBeginLoc(),
10637          diag::err_omp_ordered_directive_without_param);
10638     ErrorFound = true;
10639   } else if (TC || Clauses.empty()) {
10640     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10641       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10642       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10643           << (TC != nullptr);
10644       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10645       ErrorFound = true;
10646     }
10647   }
10648   if ((!AStmt && !DependFound) || ErrorFound)
10649     return StmtError();
10650 
10651   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10652   // During execution of an iteration of a worksharing-loop or a loop nest
10653   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10654   // must not execute more than one ordered region corresponding to an ordered
10655   // construct without a depend clause.
10656   if (!DependFound) {
10657     if (DSAStack->doesParentHasOrderedDirective()) {
10658       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10659       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10660            diag::note_omp_previous_directive)
10661           << "ordered";
10662       return StmtError();
10663     }
10664     DSAStack->setParentHasOrderedDirective(StartLoc);
10665   }
10666 
10667   if (AStmt) {
10668     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10669 
10670     setFunctionHasBranchProtectedScope();
10671   }
10672 
10673   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10674 }
10675 
10676 namespace {
10677 /// Helper class for checking expression in 'omp atomic [update]'
10678 /// construct.
10679 class OpenMPAtomicUpdateChecker {
10680   /// Error results for atomic update expressions.
10681   enum ExprAnalysisErrorCode {
10682     /// A statement is not an expression statement.
10683     NotAnExpression,
10684     /// Expression is not builtin binary or unary operation.
10685     NotABinaryOrUnaryExpression,
10686     /// Unary operation is not post-/pre- increment/decrement operation.
10687     NotAnUnaryIncDecExpression,
10688     /// An expression is not of scalar type.
10689     NotAScalarType,
10690     /// A binary operation is not an assignment operation.
10691     NotAnAssignmentOp,
10692     /// RHS part of the binary operation is not a binary expression.
10693     NotABinaryExpression,
10694     /// RHS part is not additive/multiplicative/shift/biwise binary
10695     /// expression.
10696     NotABinaryOperator,
10697     /// RHS binary operation does not have reference to the updated LHS
10698     /// part.
10699     NotAnUpdateExpression,
10700     /// No errors is found.
10701     NoError
10702   };
10703   /// Reference to Sema.
10704   Sema &SemaRef;
10705   /// A location for note diagnostics (when error is found).
10706   SourceLocation NoteLoc;
10707   /// 'x' lvalue part of the source atomic expression.
10708   Expr *X;
10709   /// 'expr' rvalue part of the source atomic expression.
10710   Expr *E;
10711   /// Helper expression of the form
10712   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10713   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10714   Expr *UpdateExpr;
10715   /// Is 'x' a LHS in a RHS part of full update expression. It is
10716   /// important for non-associative operations.
10717   bool IsXLHSInRHSPart;
10718   BinaryOperatorKind Op;
10719   SourceLocation OpLoc;
10720   /// true if the source expression is a postfix unary operation, false
10721   /// if it is a prefix unary operation.
10722   bool IsPostfixUpdate;
10723 
10724 public:
10725   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10726       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10727         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10728   /// Check specified statement that it is suitable for 'atomic update'
10729   /// constructs and extract 'x', 'expr' and Operation from the original
10730   /// expression. If DiagId and NoteId == 0, then only check is performed
10731   /// without error notification.
10732   /// \param DiagId Diagnostic which should be emitted if error is found.
10733   /// \param NoteId Diagnostic note for the main error message.
10734   /// \return true if statement is not an update expression, false otherwise.
10735   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10736   /// Return the 'x' lvalue part of the source atomic expression.
10737   Expr *getX() const { return X; }
10738   /// Return the 'expr' rvalue part of the source atomic expression.
10739   Expr *getExpr() const { return E; }
10740   /// Return the update expression used in calculation of the updated
10741   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10742   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10743   Expr *getUpdateExpr() const { return UpdateExpr; }
10744   /// Return true if 'x' is LHS in RHS part of full update expression,
10745   /// false otherwise.
10746   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10747 
10748   /// true if the source expression is a postfix unary operation, false
10749   /// if it is a prefix unary operation.
10750   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10751 
10752 private:
10753   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10754                             unsigned NoteId = 0);
10755 };
10756 } // namespace
10757 
10758 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10759     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10760   ExprAnalysisErrorCode ErrorFound = NoError;
10761   SourceLocation ErrorLoc, NoteLoc;
10762   SourceRange ErrorRange, NoteRange;
10763   // Allowed constructs are:
10764   //  x = x binop expr;
10765   //  x = expr binop x;
10766   if (AtomicBinOp->getOpcode() == BO_Assign) {
10767     X = AtomicBinOp->getLHS();
10768     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10769             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10770       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10771           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10772           AtomicInnerBinOp->isBitwiseOp()) {
10773         Op = AtomicInnerBinOp->getOpcode();
10774         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10775         Expr *LHS = AtomicInnerBinOp->getLHS();
10776         Expr *RHS = AtomicInnerBinOp->getRHS();
10777         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10778         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10779                                           /*Canonical=*/true);
10780         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10781                                             /*Canonical=*/true);
10782         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10783                                             /*Canonical=*/true);
10784         if (XId == LHSId) {
10785           E = RHS;
10786           IsXLHSInRHSPart = true;
10787         } else if (XId == RHSId) {
10788           E = LHS;
10789           IsXLHSInRHSPart = false;
10790         } else {
10791           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10792           ErrorRange = AtomicInnerBinOp->getSourceRange();
10793           NoteLoc = X->getExprLoc();
10794           NoteRange = X->getSourceRange();
10795           ErrorFound = NotAnUpdateExpression;
10796         }
10797       } else {
10798         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10799         ErrorRange = AtomicInnerBinOp->getSourceRange();
10800         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10801         NoteRange = SourceRange(NoteLoc, NoteLoc);
10802         ErrorFound = NotABinaryOperator;
10803       }
10804     } else {
10805       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10806       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10807       ErrorFound = NotABinaryExpression;
10808     }
10809   } else {
10810     ErrorLoc = AtomicBinOp->getExprLoc();
10811     ErrorRange = AtomicBinOp->getSourceRange();
10812     NoteLoc = AtomicBinOp->getOperatorLoc();
10813     NoteRange = SourceRange(NoteLoc, NoteLoc);
10814     ErrorFound = NotAnAssignmentOp;
10815   }
10816   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10817     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10818     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10819     return true;
10820   }
10821   if (SemaRef.CurContext->isDependentContext())
10822     E = X = UpdateExpr = nullptr;
10823   return ErrorFound != NoError;
10824 }
10825 
10826 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10827                                                unsigned NoteId) {
10828   ExprAnalysisErrorCode ErrorFound = NoError;
10829   SourceLocation ErrorLoc, NoteLoc;
10830   SourceRange ErrorRange, NoteRange;
10831   // Allowed constructs are:
10832   //  x++;
10833   //  x--;
10834   //  ++x;
10835   //  --x;
10836   //  x binop= expr;
10837   //  x = x binop expr;
10838   //  x = expr binop x;
10839   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10840     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10841     if (AtomicBody->getType()->isScalarType() ||
10842         AtomicBody->isInstantiationDependent()) {
10843       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10844               AtomicBody->IgnoreParenImpCasts())) {
10845         // Check for Compound Assignment Operation
10846         Op = BinaryOperator::getOpForCompoundAssignment(
10847             AtomicCompAssignOp->getOpcode());
10848         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10849         E = AtomicCompAssignOp->getRHS();
10850         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10851         IsXLHSInRHSPart = true;
10852       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10853                      AtomicBody->IgnoreParenImpCasts())) {
10854         // Check for Binary Operation
10855         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10856           return true;
10857       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10858                      AtomicBody->IgnoreParenImpCasts())) {
10859         // Check for Unary Operation
10860         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10861           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10862           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10863           OpLoc = AtomicUnaryOp->getOperatorLoc();
10864           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10865           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10866           IsXLHSInRHSPart = true;
10867         } else {
10868           ErrorFound = NotAnUnaryIncDecExpression;
10869           ErrorLoc = AtomicUnaryOp->getExprLoc();
10870           ErrorRange = AtomicUnaryOp->getSourceRange();
10871           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10872           NoteRange = SourceRange(NoteLoc, NoteLoc);
10873         }
10874       } else if (!AtomicBody->isInstantiationDependent()) {
10875         ErrorFound = NotABinaryOrUnaryExpression;
10876         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10877         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10878       }
10879     } else {
10880       ErrorFound = NotAScalarType;
10881       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10882       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10883     }
10884   } else {
10885     ErrorFound = NotAnExpression;
10886     NoteLoc = ErrorLoc = S->getBeginLoc();
10887     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10888   }
10889   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10890     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10891     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10892     return true;
10893   }
10894   if (SemaRef.CurContext->isDependentContext())
10895     E = X = UpdateExpr = nullptr;
10896   if (ErrorFound == NoError && E && X) {
10897     // Build an update expression of form 'OpaqueValueExpr(x) binop
10898     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10899     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10900     auto *OVEX = new (SemaRef.getASTContext())
10901         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
10902     auto *OVEExpr = new (SemaRef.getASTContext())
10903         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
10904     ExprResult Update =
10905         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10906                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10907     if (Update.isInvalid())
10908       return true;
10909     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10910                                                Sema::AA_Casting);
10911     if (Update.isInvalid())
10912       return true;
10913     UpdateExpr = Update.get();
10914   }
10915   return ErrorFound != NoError;
10916 }
10917 
10918 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10919                                             Stmt *AStmt,
10920                                             SourceLocation StartLoc,
10921                                             SourceLocation EndLoc) {
10922   // Register location of the first atomic directive.
10923   DSAStack->addAtomicDirectiveLoc(StartLoc);
10924   if (!AStmt)
10925     return StmtError();
10926 
10927   // 1.2.2 OpenMP Language Terminology
10928   // Structured block - An executable statement with a single entry at the
10929   // top and a single exit at the bottom.
10930   // The point of exit cannot be a branch out of the structured block.
10931   // longjmp() and throw() must not violate the entry/exit criteria.
10932   OpenMPClauseKind AtomicKind = OMPC_unknown;
10933   SourceLocation AtomicKindLoc;
10934   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10935   SourceLocation MemOrderLoc;
10936   for (const OMPClause *C : Clauses) {
10937     switch (C->getClauseKind()) {
10938     case OMPC_read:
10939     case OMPC_write:
10940     case OMPC_update:
10941     case OMPC_capture: {
10942       if (AtomicKind != OMPC_unknown) {
10943         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10944             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10945         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10946             << getOpenMPClauseName(AtomicKind);
10947       } else {
10948         AtomicKind = C->getClauseKind();
10949         AtomicKindLoc = C->getBeginLoc();
10950       }
10951       break;
10952     }
10953     case OMPC_seq_cst:
10954     case OMPC_acq_rel:
10955     case OMPC_acquire:
10956     case OMPC_release:
10957     case OMPC_relaxed: {
10958       if (MemOrderKind != OMPC_unknown) {
10959         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10960             << getOpenMPDirectiveName(OMPD_atomic) << 0
10961             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10962         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10963             << getOpenMPClauseName(MemOrderKind);
10964       } else {
10965         MemOrderKind = C->getClauseKind();
10966         MemOrderLoc = C->getBeginLoc();
10967       }
10968       break;
10969     }
10970     // The following clauses are allowed, but we don't need to do anything here.
10971     case OMPC_hint:
10972       break;
10973     default:
10974       llvm_unreachable("unknown clause is encountered");
10975     }
10976   }
10977   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10978   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10979   // release.
10980   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10981   // acquire.
10982   // If atomic-clause is update or not present then memory-order-clause must not
10983   // be acq_rel or acquire.
10984   if ((AtomicKind == OMPC_read &&
10985        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10986       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10987         AtomicKind == OMPC_unknown) &&
10988        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10989     SourceLocation Loc = AtomicKindLoc;
10990     if (AtomicKind == OMPC_unknown)
10991       Loc = StartLoc;
10992     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10993         << getOpenMPClauseName(AtomicKind)
10994         << (AtomicKind == OMPC_unknown ? 1 : 0)
10995         << getOpenMPClauseName(MemOrderKind);
10996     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10997         << getOpenMPClauseName(MemOrderKind);
10998   }
10999 
11000   Stmt *Body = AStmt;
11001   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
11002     Body = EWC->getSubExpr();
11003 
11004   Expr *X = nullptr;
11005   Expr *V = nullptr;
11006   Expr *E = nullptr;
11007   Expr *UE = nullptr;
11008   bool IsXLHSInRHSPart = false;
11009   bool IsPostfixUpdate = false;
11010   // OpenMP [2.12.6, atomic Construct]
11011   // In the next expressions:
11012   // * x and v (as applicable) are both l-value expressions with scalar type.
11013   // * During the execution of an atomic region, multiple syntactic
11014   // occurrences of x must designate the same storage location.
11015   // * Neither of v and expr (as applicable) may access the storage location
11016   // designated by x.
11017   // * Neither of x and expr (as applicable) may access the storage location
11018   // designated by v.
11019   // * expr is an expression with scalar type.
11020   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
11021   // * binop, binop=, ++, and -- are not overloaded operators.
11022   // * The expression x binop expr must be numerically equivalent to x binop
11023   // (expr). This requirement is satisfied if the operators in expr have
11024   // precedence greater than binop, or by using parentheses around expr or
11025   // subexpressions of expr.
11026   // * The expression expr binop x must be numerically equivalent to (expr)
11027   // binop x. This requirement is satisfied if the operators in expr have
11028   // precedence equal to or greater than binop, or by using parentheses around
11029   // expr or subexpressions of expr.
11030   // * For forms that allow multiple occurrences of x, the number of times
11031   // that x is evaluated is unspecified.
11032   if (AtomicKind == OMPC_read) {
11033     enum {
11034       NotAnExpression,
11035       NotAnAssignmentOp,
11036       NotAScalarType,
11037       NotAnLValue,
11038       NoError
11039     } ErrorFound = NoError;
11040     SourceLocation ErrorLoc, NoteLoc;
11041     SourceRange ErrorRange, NoteRange;
11042     // If clause is read:
11043     //  v = x;
11044     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11045       const auto *AtomicBinOp =
11046           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11047       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11048         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11049         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
11050         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11051             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
11052           if (!X->isLValue() || !V->isLValue()) {
11053             const Expr *NotLValueExpr = X->isLValue() ? V : X;
11054             ErrorFound = NotAnLValue;
11055             ErrorLoc = AtomicBinOp->getExprLoc();
11056             ErrorRange = AtomicBinOp->getSourceRange();
11057             NoteLoc = NotLValueExpr->getExprLoc();
11058             NoteRange = NotLValueExpr->getSourceRange();
11059           }
11060         } else if (!X->isInstantiationDependent() ||
11061                    !V->isInstantiationDependent()) {
11062           const Expr *NotScalarExpr =
11063               (X->isInstantiationDependent() || X->getType()->isScalarType())
11064                   ? V
11065                   : X;
11066           ErrorFound = NotAScalarType;
11067           ErrorLoc = AtomicBinOp->getExprLoc();
11068           ErrorRange = AtomicBinOp->getSourceRange();
11069           NoteLoc = NotScalarExpr->getExprLoc();
11070           NoteRange = NotScalarExpr->getSourceRange();
11071         }
11072       } else if (!AtomicBody->isInstantiationDependent()) {
11073         ErrorFound = NotAnAssignmentOp;
11074         ErrorLoc = AtomicBody->getExprLoc();
11075         ErrorRange = AtomicBody->getSourceRange();
11076         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11077                               : AtomicBody->getExprLoc();
11078         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11079                                 : AtomicBody->getSourceRange();
11080       }
11081     } else {
11082       ErrorFound = NotAnExpression;
11083       NoteLoc = ErrorLoc = Body->getBeginLoc();
11084       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11085     }
11086     if (ErrorFound != NoError) {
11087       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
11088           << ErrorRange;
11089       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11090           << ErrorFound << NoteRange;
11091       return StmtError();
11092     }
11093     if (CurContext->isDependentContext())
11094       V = X = nullptr;
11095   } else if (AtomicKind == OMPC_write) {
11096     enum {
11097       NotAnExpression,
11098       NotAnAssignmentOp,
11099       NotAScalarType,
11100       NotAnLValue,
11101       NoError
11102     } ErrorFound = NoError;
11103     SourceLocation ErrorLoc, NoteLoc;
11104     SourceRange ErrorRange, NoteRange;
11105     // If clause is write:
11106     //  x = expr;
11107     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11108       const auto *AtomicBinOp =
11109           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11110       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11111         X = AtomicBinOp->getLHS();
11112         E = AtomicBinOp->getRHS();
11113         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11114             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
11115           if (!X->isLValue()) {
11116             ErrorFound = NotAnLValue;
11117             ErrorLoc = AtomicBinOp->getExprLoc();
11118             ErrorRange = AtomicBinOp->getSourceRange();
11119             NoteLoc = X->getExprLoc();
11120             NoteRange = X->getSourceRange();
11121           }
11122         } else if (!X->isInstantiationDependent() ||
11123                    !E->isInstantiationDependent()) {
11124           const Expr *NotScalarExpr =
11125               (X->isInstantiationDependent() || X->getType()->isScalarType())
11126                   ? E
11127                   : X;
11128           ErrorFound = NotAScalarType;
11129           ErrorLoc = AtomicBinOp->getExprLoc();
11130           ErrorRange = AtomicBinOp->getSourceRange();
11131           NoteLoc = NotScalarExpr->getExprLoc();
11132           NoteRange = NotScalarExpr->getSourceRange();
11133         }
11134       } else if (!AtomicBody->isInstantiationDependent()) {
11135         ErrorFound = NotAnAssignmentOp;
11136         ErrorLoc = AtomicBody->getExprLoc();
11137         ErrorRange = AtomicBody->getSourceRange();
11138         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11139                               : AtomicBody->getExprLoc();
11140         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11141                                 : AtomicBody->getSourceRange();
11142       }
11143     } else {
11144       ErrorFound = NotAnExpression;
11145       NoteLoc = ErrorLoc = Body->getBeginLoc();
11146       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11147     }
11148     if (ErrorFound != NoError) {
11149       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
11150           << ErrorRange;
11151       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11152           << ErrorFound << NoteRange;
11153       return StmtError();
11154     }
11155     if (CurContext->isDependentContext())
11156       E = X = nullptr;
11157   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
11158     // If clause is update:
11159     //  x++;
11160     //  x--;
11161     //  ++x;
11162     //  --x;
11163     //  x binop= expr;
11164     //  x = x binop expr;
11165     //  x = expr binop x;
11166     OpenMPAtomicUpdateChecker Checker(*this);
11167     if (Checker.checkStatement(
11168             Body,
11169             (AtomicKind == OMPC_update)
11170                 ? diag::err_omp_atomic_update_not_expression_statement
11171                 : diag::err_omp_atomic_not_expression_statement,
11172             diag::note_omp_atomic_update))
11173       return StmtError();
11174     if (!CurContext->isDependentContext()) {
11175       E = Checker.getExpr();
11176       X = Checker.getX();
11177       UE = Checker.getUpdateExpr();
11178       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11179     }
11180   } else if (AtomicKind == OMPC_capture) {
11181     enum {
11182       NotAnAssignmentOp,
11183       NotACompoundStatement,
11184       NotTwoSubstatements,
11185       NotASpecificExpression,
11186       NoError
11187     } ErrorFound = NoError;
11188     SourceLocation ErrorLoc, NoteLoc;
11189     SourceRange ErrorRange, NoteRange;
11190     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11191       // If clause is a capture:
11192       //  v = x++;
11193       //  v = x--;
11194       //  v = ++x;
11195       //  v = --x;
11196       //  v = x binop= expr;
11197       //  v = x = x binop expr;
11198       //  v = x = expr binop x;
11199       const auto *AtomicBinOp =
11200           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11201       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11202         V = AtomicBinOp->getLHS();
11203         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11204         OpenMPAtomicUpdateChecker Checker(*this);
11205         if (Checker.checkStatement(
11206                 Body, diag::err_omp_atomic_capture_not_expression_statement,
11207                 diag::note_omp_atomic_update))
11208           return StmtError();
11209         E = Checker.getExpr();
11210         X = Checker.getX();
11211         UE = Checker.getUpdateExpr();
11212         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11213         IsPostfixUpdate = Checker.isPostfixUpdate();
11214       } else if (!AtomicBody->isInstantiationDependent()) {
11215         ErrorLoc = AtomicBody->getExprLoc();
11216         ErrorRange = AtomicBody->getSourceRange();
11217         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11218                               : AtomicBody->getExprLoc();
11219         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11220                                 : AtomicBody->getSourceRange();
11221         ErrorFound = NotAnAssignmentOp;
11222       }
11223       if (ErrorFound != NoError) {
11224         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
11225             << ErrorRange;
11226         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11227         return StmtError();
11228       }
11229       if (CurContext->isDependentContext())
11230         UE = V = E = X = nullptr;
11231     } else {
11232       // If clause is a capture:
11233       //  { v = x; x = expr; }
11234       //  { v = x; x++; }
11235       //  { v = x; x--; }
11236       //  { v = x; ++x; }
11237       //  { v = x; --x; }
11238       //  { v = x; x binop= expr; }
11239       //  { v = x; x = x binop expr; }
11240       //  { v = x; x = expr binop x; }
11241       //  { x++; v = x; }
11242       //  { x--; v = x; }
11243       //  { ++x; v = x; }
11244       //  { --x; v = x; }
11245       //  { x binop= expr; v = x; }
11246       //  { x = x binop expr; v = x; }
11247       //  { x = expr binop x; v = x; }
11248       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
11249         // Check that this is { expr1; expr2; }
11250         if (CS->size() == 2) {
11251           Stmt *First = CS->body_front();
11252           Stmt *Second = CS->body_back();
11253           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
11254             First = EWC->getSubExpr()->IgnoreParenImpCasts();
11255           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
11256             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
11257           // Need to find what subexpression is 'v' and what is 'x'.
11258           OpenMPAtomicUpdateChecker Checker(*this);
11259           bool IsUpdateExprFound = !Checker.checkStatement(Second);
11260           BinaryOperator *BinOp = nullptr;
11261           if (IsUpdateExprFound) {
11262             BinOp = dyn_cast<BinaryOperator>(First);
11263             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11264           }
11265           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11266             //  { v = x; x++; }
11267             //  { v = x; x--; }
11268             //  { v = x; ++x; }
11269             //  { v = x; --x; }
11270             //  { v = x; x binop= expr; }
11271             //  { v = x; x = x binop expr; }
11272             //  { v = x; x = expr binop x; }
11273             // Check that the first expression has form v = x.
11274             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11275             llvm::FoldingSetNodeID XId, PossibleXId;
11276             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11277             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11278             IsUpdateExprFound = XId == PossibleXId;
11279             if (IsUpdateExprFound) {
11280               V = BinOp->getLHS();
11281               X = Checker.getX();
11282               E = Checker.getExpr();
11283               UE = Checker.getUpdateExpr();
11284               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11285               IsPostfixUpdate = true;
11286             }
11287           }
11288           if (!IsUpdateExprFound) {
11289             IsUpdateExprFound = !Checker.checkStatement(First);
11290             BinOp = nullptr;
11291             if (IsUpdateExprFound) {
11292               BinOp = dyn_cast<BinaryOperator>(Second);
11293               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11294             }
11295             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11296               //  { x++; v = x; }
11297               //  { x--; v = x; }
11298               //  { ++x; v = x; }
11299               //  { --x; v = x; }
11300               //  { x binop= expr; v = x; }
11301               //  { x = x binop expr; v = x; }
11302               //  { x = expr binop x; v = x; }
11303               // Check that the second expression has form v = x.
11304               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11305               llvm::FoldingSetNodeID XId, PossibleXId;
11306               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11307               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11308               IsUpdateExprFound = XId == PossibleXId;
11309               if (IsUpdateExprFound) {
11310                 V = BinOp->getLHS();
11311                 X = Checker.getX();
11312                 E = Checker.getExpr();
11313                 UE = Checker.getUpdateExpr();
11314                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11315                 IsPostfixUpdate = false;
11316               }
11317             }
11318           }
11319           if (!IsUpdateExprFound) {
11320             //  { v = x; x = expr; }
11321             auto *FirstExpr = dyn_cast<Expr>(First);
11322             auto *SecondExpr = dyn_cast<Expr>(Second);
11323             if (!FirstExpr || !SecondExpr ||
11324                 !(FirstExpr->isInstantiationDependent() ||
11325                   SecondExpr->isInstantiationDependent())) {
11326               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11327               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11328                 ErrorFound = NotAnAssignmentOp;
11329                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11330                                                 : First->getBeginLoc();
11331                 NoteRange = ErrorRange = FirstBinOp
11332                                              ? FirstBinOp->getSourceRange()
11333                                              : SourceRange(ErrorLoc, ErrorLoc);
11334               } else {
11335                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11336                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11337                   ErrorFound = NotAnAssignmentOp;
11338                   NoteLoc = ErrorLoc = SecondBinOp
11339                                            ? SecondBinOp->getOperatorLoc()
11340                                            : Second->getBeginLoc();
11341                   NoteRange = ErrorRange =
11342                       SecondBinOp ? SecondBinOp->getSourceRange()
11343                                   : SourceRange(ErrorLoc, ErrorLoc);
11344                 } else {
11345                   Expr *PossibleXRHSInFirst =
11346                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11347                   Expr *PossibleXLHSInSecond =
11348                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11349                   llvm::FoldingSetNodeID X1Id, X2Id;
11350                   PossibleXRHSInFirst->Profile(X1Id, Context,
11351                                                /*Canonical=*/true);
11352                   PossibleXLHSInSecond->Profile(X2Id, Context,
11353                                                 /*Canonical=*/true);
11354                   IsUpdateExprFound = X1Id == X2Id;
11355                   if (IsUpdateExprFound) {
11356                     V = FirstBinOp->getLHS();
11357                     X = SecondBinOp->getLHS();
11358                     E = SecondBinOp->getRHS();
11359                     UE = nullptr;
11360                     IsXLHSInRHSPart = false;
11361                     IsPostfixUpdate = true;
11362                   } else {
11363                     ErrorFound = NotASpecificExpression;
11364                     ErrorLoc = FirstBinOp->getExprLoc();
11365                     ErrorRange = FirstBinOp->getSourceRange();
11366                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11367                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11368                   }
11369                 }
11370               }
11371             }
11372           }
11373         } else {
11374           NoteLoc = ErrorLoc = Body->getBeginLoc();
11375           NoteRange = ErrorRange =
11376               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11377           ErrorFound = NotTwoSubstatements;
11378         }
11379       } else {
11380         NoteLoc = ErrorLoc = Body->getBeginLoc();
11381         NoteRange = ErrorRange =
11382             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11383         ErrorFound = NotACompoundStatement;
11384       }
11385       if (ErrorFound != NoError) {
11386         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11387             << ErrorRange;
11388         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11389         return StmtError();
11390       }
11391       if (CurContext->isDependentContext())
11392         UE = V = E = X = nullptr;
11393     }
11394   }
11395 
11396   setFunctionHasBranchProtectedScope();
11397 
11398   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11399                                     X, V, E, UE, IsXLHSInRHSPart,
11400                                     IsPostfixUpdate);
11401 }
11402 
11403 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11404                                             Stmt *AStmt,
11405                                             SourceLocation StartLoc,
11406                                             SourceLocation EndLoc) {
11407   if (!AStmt)
11408     return StmtError();
11409 
11410   auto *CS = cast<CapturedStmt>(AStmt);
11411   // 1.2.2 OpenMP Language Terminology
11412   // Structured block - An executable statement with a single entry at the
11413   // top and a single exit at the bottom.
11414   // The point of exit cannot be a branch out of the structured block.
11415   // longjmp() and throw() must not violate the entry/exit criteria.
11416   CS->getCapturedDecl()->setNothrow();
11417   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11418        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11419     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11420     // 1.2.2 OpenMP Language Terminology
11421     // Structured block - An executable statement with a single entry at the
11422     // top and a single exit at the bottom.
11423     // The point of exit cannot be a branch out of the structured block.
11424     // longjmp() and throw() must not violate the entry/exit criteria.
11425     CS->getCapturedDecl()->setNothrow();
11426   }
11427 
11428   // OpenMP [2.16, Nesting of Regions]
11429   // If specified, a teams construct must be contained within a target
11430   // construct. That target construct must contain no statements or directives
11431   // outside of the teams construct.
11432   if (DSAStack->hasInnerTeamsRegion()) {
11433     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11434     bool OMPTeamsFound = true;
11435     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11436       auto I = CS->body_begin();
11437       while (I != CS->body_end()) {
11438         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11439         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11440             OMPTeamsFound) {
11441 
11442           OMPTeamsFound = false;
11443           break;
11444         }
11445         ++I;
11446       }
11447       assert(I != CS->body_end() && "Not found statement");
11448       S = *I;
11449     } else {
11450       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11451       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11452     }
11453     if (!OMPTeamsFound) {
11454       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11455       Diag(DSAStack->getInnerTeamsRegionLoc(),
11456            diag::note_omp_nested_teams_construct_here);
11457       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11458           << isa<OMPExecutableDirective>(S);
11459       return StmtError();
11460     }
11461   }
11462 
11463   setFunctionHasBranchProtectedScope();
11464 
11465   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11466 }
11467 
11468 StmtResult
11469 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11470                                          Stmt *AStmt, SourceLocation StartLoc,
11471                                          SourceLocation EndLoc) {
11472   if (!AStmt)
11473     return StmtError();
11474 
11475   auto *CS = cast<CapturedStmt>(AStmt);
11476   // 1.2.2 OpenMP Language Terminology
11477   // Structured block - An executable statement with a single entry at the
11478   // top and a single exit at the bottom.
11479   // The point of exit cannot be a branch out of the structured block.
11480   // longjmp() and throw() must not violate the entry/exit criteria.
11481   CS->getCapturedDecl()->setNothrow();
11482   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11483        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11484     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11485     // 1.2.2 OpenMP Language Terminology
11486     // Structured block - An executable statement with a single entry at the
11487     // top and a single exit at the bottom.
11488     // The point of exit cannot be a branch out of the structured block.
11489     // longjmp() and throw() must not violate the entry/exit criteria.
11490     CS->getCapturedDecl()->setNothrow();
11491   }
11492 
11493   setFunctionHasBranchProtectedScope();
11494 
11495   return OMPTargetParallelDirective::Create(
11496       Context, StartLoc, EndLoc, Clauses, AStmt,
11497       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11498 }
11499 
11500 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11501     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11502     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11503   if (!AStmt)
11504     return StmtError();
11505 
11506   auto *CS = cast<CapturedStmt>(AStmt);
11507   // 1.2.2 OpenMP Language Terminology
11508   // Structured block - An executable statement with a single entry at the
11509   // top and a single exit at the bottom.
11510   // The point of exit cannot be a branch out of the structured block.
11511   // longjmp() and throw() must not violate the entry/exit criteria.
11512   CS->getCapturedDecl()->setNothrow();
11513   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11514        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11515     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11516     // 1.2.2 OpenMP Language Terminology
11517     // Structured block - An executable statement with a single entry at the
11518     // top and a single exit at the bottom.
11519     // The point of exit cannot be a branch out of the structured block.
11520     // longjmp() and throw() must not violate the entry/exit criteria.
11521     CS->getCapturedDecl()->setNothrow();
11522   }
11523 
11524   OMPLoopBasedDirective::HelperExprs B;
11525   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11526   // define the nested loops number.
11527   unsigned NestedLoopCount =
11528       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11529                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11530                       VarsWithImplicitDSA, B);
11531   if (NestedLoopCount == 0)
11532     return StmtError();
11533 
11534   assert((CurContext->isDependentContext() || B.builtAll()) &&
11535          "omp target parallel for loop exprs were not built");
11536 
11537   if (!CurContext->isDependentContext()) {
11538     // Finalize the clauses that need pre-built expressions for CodeGen.
11539     for (OMPClause *C : Clauses) {
11540       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11541         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11542                                      B.NumIterations, *this, CurScope,
11543                                      DSAStack))
11544           return StmtError();
11545     }
11546   }
11547 
11548   setFunctionHasBranchProtectedScope();
11549   return OMPTargetParallelForDirective::Create(
11550       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11551       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11552 }
11553 
11554 /// Check for existence of a map clause in the list of clauses.
11555 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11556                        const OpenMPClauseKind K) {
11557   return llvm::any_of(
11558       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11559 }
11560 
11561 template <typename... Params>
11562 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11563                        const Params... ClauseTypes) {
11564   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11565 }
11566 
11567 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11568                                                 Stmt *AStmt,
11569                                                 SourceLocation StartLoc,
11570                                                 SourceLocation EndLoc) {
11571   if (!AStmt)
11572     return StmtError();
11573 
11574   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11575 
11576   // OpenMP [2.12.2, target data Construct, Restrictions]
11577   // At least one map, use_device_addr or use_device_ptr clause must appear on
11578   // the directive.
11579   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11580       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11581     StringRef Expected;
11582     if (LangOpts.OpenMP < 50)
11583       Expected = "'map' or 'use_device_ptr'";
11584     else
11585       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11586     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11587         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11588     return StmtError();
11589   }
11590 
11591   setFunctionHasBranchProtectedScope();
11592 
11593   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11594                                         AStmt);
11595 }
11596 
11597 StmtResult
11598 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11599                                           SourceLocation StartLoc,
11600                                           SourceLocation EndLoc, Stmt *AStmt) {
11601   if (!AStmt)
11602     return StmtError();
11603 
11604   auto *CS = cast<CapturedStmt>(AStmt);
11605   // 1.2.2 OpenMP Language Terminology
11606   // Structured block - An executable statement with a single entry at the
11607   // top and a single exit at the bottom.
11608   // The point of exit cannot be a branch out of the structured block.
11609   // longjmp() and throw() must not violate the entry/exit criteria.
11610   CS->getCapturedDecl()->setNothrow();
11611   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11612        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11613     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11614     // 1.2.2 OpenMP Language Terminology
11615     // Structured block - An executable statement with a single entry at the
11616     // top and a single exit at the bottom.
11617     // The point of exit cannot be a branch out of the structured block.
11618     // longjmp() and throw() must not violate the entry/exit criteria.
11619     CS->getCapturedDecl()->setNothrow();
11620   }
11621 
11622   // OpenMP [2.10.2, Restrictions, p. 99]
11623   // At least one map clause must appear on the directive.
11624   if (!hasClauses(Clauses, OMPC_map)) {
11625     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11626         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11627     return StmtError();
11628   }
11629 
11630   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11631                                              AStmt);
11632 }
11633 
11634 StmtResult
11635 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11636                                          SourceLocation StartLoc,
11637                                          SourceLocation EndLoc, Stmt *AStmt) {
11638   if (!AStmt)
11639     return StmtError();
11640 
11641   auto *CS = cast<CapturedStmt>(AStmt);
11642   // 1.2.2 OpenMP Language Terminology
11643   // Structured block - An executable statement with a single entry at the
11644   // top and a single exit at the bottom.
11645   // The point of exit cannot be a branch out of the structured block.
11646   // longjmp() and throw() must not violate the entry/exit criteria.
11647   CS->getCapturedDecl()->setNothrow();
11648   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11649        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11650     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11651     // 1.2.2 OpenMP Language Terminology
11652     // Structured block - An executable statement with a single entry at the
11653     // top and a single exit at the bottom.
11654     // The point of exit cannot be a branch out of the structured block.
11655     // longjmp() and throw() must not violate the entry/exit criteria.
11656     CS->getCapturedDecl()->setNothrow();
11657   }
11658 
11659   // OpenMP [2.10.3, Restrictions, p. 102]
11660   // At least one map clause must appear on the directive.
11661   if (!hasClauses(Clauses, OMPC_map)) {
11662     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11663         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11664     return StmtError();
11665   }
11666 
11667   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11668                                             AStmt);
11669 }
11670 
11671 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11672                                                   SourceLocation StartLoc,
11673                                                   SourceLocation EndLoc,
11674                                                   Stmt *AStmt) {
11675   if (!AStmt)
11676     return StmtError();
11677 
11678   auto *CS = cast<CapturedStmt>(AStmt);
11679   // 1.2.2 OpenMP Language Terminology
11680   // Structured block - An executable statement with a single entry at the
11681   // top and a single exit at the bottom.
11682   // The point of exit cannot be a branch out of the structured block.
11683   // longjmp() and throw() must not violate the entry/exit criteria.
11684   CS->getCapturedDecl()->setNothrow();
11685   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11686        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11687     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11688     // 1.2.2 OpenMP Language Terminology
11689     // Structured block - An executable statement with a single entry at the
11690     // top and a single exit at the bottom.
11691     // The point of exit cannot be a branch out of the structured block.
11692     // longjmp() and throw() must not violate the entry/exit criteria.
11693     CS->getCapturedDecl()->setNothrow();
11694   }
11695 
11696   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11697     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11698     return StmtError();
11699   }
11700   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11701                                           AStmt);
11702 }
11703 
11704 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11705                                            Stmt *AStmt, SourceLocation StartLoc,
11706                                            SourceLocation EndLoc) {
11707   if (!AStmt)
11708     return StmtError();
11709 
11710   auto *CS = cast<CapturedStmt>(AStmt);
11711   // 1.2.2 OpenMP Language Terminology
11712   // Structured block - An executable statement with a single entry at the
11713   // top and a single exit at the bottom.
11714   // The point of exit cannot be a branch out of the structured block.
11715   // longjmp() and throw() must not violate the entry/exit criteria.
11716   CS->getCapturedDecl()->setNothrow();
11717 
11718   setFunctionHasBranchProtectedScope();
11719 
11720   DSAStack->setParentTeamsRegionLoc(StartLoc);
11721 
11722   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11723 }
11724 
11725 StmtResult
11726 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11727                                             SourceLocation EndLoc,
11728                                             OpenMPDirectiveKind CancelRegion) {
11729   if (DSAStack->isParentNowaitRegion()) {
11730     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11731     return StmtError();
11732   }
11733   if (DSAStack->isParentOrderedRegion()) {
11734     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11735     return StmtError();
11736   }
11737   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11738                                                CancelRegion);
11739 }
11740 
11741 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11742                                             SourceLocation StartLoc,
11743                                             SourceLocation EndLoc,
11744                                             OpenMPDirectiveKind CancelRegion) {
11745   if (DSAStack->isParentNowaitRegion()) {
11746     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11747     return StmtError();
11748   }
11749   if (DSAStack->isParentOrderedRegion()) {
11750     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11751     return StmtError();
11752   }
11753   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11754   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11755                                     CancelRegion);
11756 }
11757 
11758 static bool checkReductionClauseWithNogroup(Sema &S,
11759                                             ArrayRef<OMPClause *> Clauses) {
11760   const OMPClause *ReductionClause = nullptr;
11761   const OMPClause *NogroupClause = nullptr;
11762   for (const OMPClause *C : Clauses) {
11763     if (C->getClauseKind() == OMPC_reduction) {
11764       ReductionClause = C;
11765       if (NogroupClause)
11766         break;
11767       continue;
11768     }
11769     if (C->getClauseKind() == OMPC_nogroup) {
11770       NogroupClause = C;
11771       if (ReductionClause)
11772         break;
11773       continue;
11774     }
11775   }
11776   if (ReductionClause && NogroupClause) {
11777     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11778         << SourceRange(NogroupClause->getBeginLoc(),
11779                        NogroupClause->getEndLoc());
11780     return true;
11781   }
11782   return false;
11783 }
11784 
11785 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11786     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11787     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11788   if (!AStmt)
11789     return StmtError();
11790 
11791   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11792   OMPLoopBasedDirective::HelperExprs B;
11793   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11794   // define the nested loops number.
11795   unsigned NestedLoopCount =
11796       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11797                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11798                       VarsWithImplicitDSA, B);
11799   if (NestedLoopCount == 0)
11800     return StmtError();
11801 
11802   assert((CurContext->isDependentContext() || B.builtAll()) &&
11803          "omp for loop exprs were not built");
11804 
11805   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11806   // The grainsize clause and num_tasks clause are mutually exclusive and may
11807   // not appear on the same taskloop directive.
11808   if (checkMutuallyExclusiveClauses(*this, Clauses,
11809                                     {OMPC_grainsize, OMPC_num_tasks}))
11810     return StmtError();
11811   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11812   // If a reduction clause is present on the taskloop directive, the nogroup
11813   // clause must not be specified.
11814   if (checkReductionClauseWithNogroup(*this, Clauses))
11815     return StmtError();
11816 
11817   setFunctionHasBranchProtectedScope();
11818   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11819                                       NestedLoopCount, Clauses, AStmt, B,
11820                                       DSAStack->isCancelRegion());
11821 }
11822 
11823 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11824     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11825     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11826   if (!AStmt)
11827     return StmtError();
11828 
11829   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11830   OMPLoopBasedDirective::HelperExprs B;
11831   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11832   // define the nested loops number.
11833   unsigned NestedLoopCount =
11834       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11835                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11836                       VarsWithImplicitDSA, B);
11837   if (NestedLoopCount == 0)
11838     return StmtError();
11839 
11840   assert((CurContext->isDependentContext() || B.builtAll()) &&
11841          "omp for loop exprs were not built");
11842 
11843   if (!CurContext->isDependentContext()) {
11844     // Finalize the clauses that need pre-built expressions for CodeGen.
11845     for (OMPClause *C : Clauses) {
11846       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11847         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11848                                      B.NumIterations, *this, CurScope,
11849                                      DSAStack))
11850           return StmtError();
11851     }
11852   }
11853 
11854   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11855   // The grainsize clause and num_tasks clause are mutually exclusive and may
11856   // not appear on the same taskloop directive.
11857   if (checkMutuallyExclusiveClauses(*this, Clauses,
11858                                     {OMPC_grainsize, OMPC_num_tasks}))
11859     return StmtError();
11860   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11861   // If a reduction clause is present on the taskloop directive, the nogroup
11862   // clause must not be specified.
11863   if (checkReductionClauseWithNogroup(*this, Clauses))
11864     return StmtError();
11865   if (checkSimdlenSafelenSpecified(*this, Clauses))
11866     return StmtError();
11867 
11868   setFunctionHasBranchProtectedScope();
11869   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11870                                           NestedLoopCount, Clauses, AStmt, B);
11871 }
11872 
11873 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11874     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11875     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11876   if (!AStmt)
11877     return StmtError();
11878 
11879   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11880   OMPLoopBasedDirective::HelperExprs B;
11881   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11882   // define the nested loops number.
11883   unsigned NestedLoopCount =
11884       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11885                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11886                       VarsWithImplicitDSA, B);
11887   if (NestedLoopCount == 0)
11888     return StmtError();
11889 
11890   assert((CurContext->isDependentContext() || B.builtAll()) &&
11891          "omp for loop exprs were not built");
11892 
11893   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11894   // The grainsize clause and num_tasks clause are mutually exclusive and may
11895   // not appear on the same taskloop directive.
11896   if (checkMutuallyExclusiveClauses(*this, Clauses,
11897                                     {OMPC_grainsize, OMPC_num_tasks}))
11898     return StmtError();
11899   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11900   // If a reduction clause is present on the taskloop directive, the nogroup
11901   // clause must not be specified.
11902   if (checkReductionClauseWithNogroup(*this, Clauses))
11903     return StmtError();
11904 
11905   setFunctionHasBranchProtectedScope();
11906   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11907                                             NestedLoopCount, Clauses, AStmt, B,
11908                                             DSAStack->isCancelRegion());
11909 }
11910 
11911 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11912     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11913     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11914   if (!AStmt)
11915     return StmtError();
11916 
11917   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11918   OMPLoopBasedDirective::HelperExprs B;
11919   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11920   // define the nested loops number.
11921   unsigned NestedLoopCount =
11922       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11923                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11924                       VarsWithImplicitDSA, B);
11925   if (NestedLoopCount == 0)
11926     return StmtError();
11927 
11928   assert((CurContext->isDependentContext() || B.builtAll()) &&
11929          "omp for loop exprs were not built");
11930 
11931   if (!CurContext->isDependentContext()) {
11932     // Finalize the clauses that need pre-built expressions for CodeGen.
11933     for (OMPClause *C : Clauses) {
11934       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11935         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11936                                      B.NumIterations, *this, CurScope,
11937                                      DSAStack))
11938           return StmtError();
11939     }
11940   }
11941 
11942   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11943   // The grainsize clause and num_tasks clause are mutually exclusive and may
11944   // not appear on the same taskloop directive.
11945   if (checkMutuallyExclusiveClauses(*this, Clauses,
11946                                     {OMPC_grainsize, OMPC_num_tasks}))
11947     return StmtError();
11948   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11949   // If a reduction clause is present on the taskloop directive, the nogroup
11950   // clause must not be specified.
11951   if (checkReductionClauseWithNogroup(*this, Clauses))
11952     return StmtError();
11953   if (checkSimdlenSafelenSpecified(*this, Clauses))
11954     return StmtError();
11955 
11956   setFunctionHasBranchProtectedScope();
11957   return OMPMasterTaskLoopSimdDirective::Create(
11958       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11959 }
11960 
11961 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11962     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11963     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11964   if (!AStmt)
11965     return StmtError();
11966 
11967   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11968   auto *CS = cast<CapturedStmt>(AStmt);
11969   // 1.2.2 OpenMP Language Terminology
11970   // Structured block - An executable statement with a single entry at the
11971   // top and a single exit at the bottom.
11972   // The point of exit cannot be a branch out of the structured block.
11973   // longjmp() and throw() must not violate the entry/exit criteria.
11974   CS->getCapturedDecl()->setNothrow();
11975   for (int ThisCaptureLevel =
11976            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11977        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11978     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11979     // 1.2.2 OpenMP Language Terminology
11980     // Structured block - An executable statement with a single entry at the
11981     // top and a single exit at the bottom.
11982     // The point of exit cannot be a branch out of the structured block.
11983     // longjmp() and throw() must not violate the entry/exit criteria.
11984     CS->getCapturedDecl()->setNothrow();
11985   }
11986 
11987   OMPLoopBasedDirective::HelperExprs B;
11988   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11989   // define the nested loops number.
11990   unsigned NestedLoopCount = checkOpenMPLoop(
11991       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11992       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11993       VarsWithImplicitDSA, B);
11994   if (NestedLoopCount == 0)
11995     return StmtError();
11996 
11997   assert((CurContext->isDependentContext() || B.builtAll()) &&
11998          "omp for loop exprs were not built");
11999 
12000   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12001   // The grainsize clause and num_tasks clause are mutually exclusive and may
12002   // not appear on the same taskloop directive.
12003   if (checkMutuallyExclusiveClauses(*this, Clauses,
12004                                     {OMPC_grainsize, OMPC_num_tasks}))
12005     return StmtError();
12006   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12007   // If a reduction clause is present on the taskloop directive, the nogroup
12008   // clause must not be specified.
12009   if (checkReductionClauseWithNogroup(*this, Clauses))
12010     return StmtError();
12011 
12012   setFunctionHasBranchProtectedScope();
12013   return OMPParallelMasterTaskLoopDirective::Create(
12014       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12015       DSAStack->isCancelRegion());
12016 }
12017 
12018 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
12019     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12020     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12021   if (!AStmt)
12022     return StmtError();
12023 
12024   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12025   auto *CS = cast<CapturedStmt>(AStmt);
12026   // 1.2.2 OpenMP Language Terminology
12027   // Structured block - An executable statement with a single entry at the
12028   // top and a single exit at the bottom.
12029   // The point of exit cannot be a branch out of the structured block.
12030   // longjmp() and throw() must not violate the entry/exit criteria.
12031   CS->getCapturedDecl()->setNothrow();
12032   for (int ThisCaptureLevel =
12033            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
12034        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12035     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12036     // 1.2.2 OpenMP Language Terminology
12037     // Structured block - An executable statement with a single entry at the
12038     // top and a single exit at the bottom.
12039     // The point of exit cannot be a branch out of the structured block.
12040     // longjmp() and throw() must not violate the entry/exit criteria.
12041     CS->getCapturedDecl()->setNothrow();
12042   }
12043 
12044   OMPLoopBasedDirective::HelperExprs B;
12045   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12046   // define the nested loops number.
12047   unsigned NestedLoopCount = checkOpenMPLoop(
12048       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
12049       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
12050       VarsWithImplicitDSA, B);
12051   if (NestedLoopCount == 0)
12052     return StmtError();
12053 
12054   assert((CurContext->isDependentContext() || B.builtAll()) &&
12055          "omp for loop exprs were not built");
12056 
12057   if (!CurContext->isDependentContext()) {
12058     // Finalize the clauses that need pre-built expressions for CodeGen.
12059     for (OMPClause *C : Clauses) {
12060       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12061         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12062                                      B.NumIterations, *this, CurScope,
12063                                      DSAStack))
12064           return StmtError();
12065     }
12066   }
12067 
12068   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12069   // The grainsize clause and num_tasks clause are mutually exclusive and may
12070   // not appear on the same taskloop directive.
12071   if (checkMutuallyExclusiveClauses(*this, Clauses,
12072                                     {OMPC_grainsize, OMPC_num_tasks}))
12073     return StmtError();
12074   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12075   // If a reduction clause is present on the taskloop directive, the nogroup
12076   // clause must not be specified.
12077   if (checkReductionClauseWithNogroup(*this, Clauses))
12078     return StmtError();
12079   if (checkSimdlenSafelenSpecified(*this, Clauses))
12080     return StmtError();
12081 
12082   setFunctionHasBranchProtectedScope();
12083   return OMPParallelMasterTaskLoopSimdDirective::Create(
12084       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12085 }
12086 
12087 StmtResult Sema::ActOnOpenMPDistributeDirective(
12088     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12089     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12090   if (!AStmt)
12091     return StmtError();
12092 
12093   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12094   OMPLoopBasedDirective::HelperExprs B;
12095   // In presence of clause 'collapse' with number of loops, it will
12096   // define the nested loops number.
12097   unsigned NestedLoopCount =
12098       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
12099                       nullptr /*ordered not a clause on distribute*/, AStmt,
12100                       *this, *DSAStack, VarsWithImplicitDSA, B);
12101   if (NestedLoopCount == 0)
12102     return StmtError();
12103 
12104   assert((CurContext->isDependentContext() || B.builtAll()) &&
12105          "omp for loop exprs were not built");
12106 
12107   setFunctionHasBranchProtectedScope();
12108   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
12109                                         NestedLoopCount, Clauses, AStmt, B);
12110 }
12111 
12112 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
12113     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12114     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12115   if (!AStmt)
12116     return StmtError();
12117 
12118   auto *CS = cast<CapturedStmt>(AStmt);
12119   // 1.2.2 OpenMP Language Terminology
12120   // Structured block - An executable statement with a single entry at the
12121   // top and a single exit at the bottom.
12122   // The point of exit cannot be a branch out of the structured block.
12123   // longjmp() and throw() must not violate the entry/exit criteria.
12124   CS->getCapturedDecl()->setNothrow();
12125   for (int ThisCaptureLevel =
12126            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
12127        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12128     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12129     // 1.2.2 OpenMP Language Terminology
12130     // Structured block - An executable statement with a single entry at the
12131     // top and a single exit at the bottom.
12132     // The point of exit cannot be a branch out of the structured block.
12133     // longjmp() and throw() must not violate the entry/exit criteria.
12134     CS->getCapturedDecl()->setNothrow();
12135   }
12136 
12137   OMPLoopBasedDirective::HelperExprs B;
12138   // In presence of clause 'collapse' with number of loops, it will
12139   // define the nested loops number.
12140   unsigned NestedLoopCount = checkOpenMPLoop(
12141       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12142       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12143       VarsWithImplicitDSA, B);
12144   if (NestedLoopCount == 0)
12145     return StmtError();
12146 
12147   assert((CurContext->isDependentContext() || B.builtAll()) &&
12148          "omp for loop exprs were not built");
12149 
12150   setFunctionHasBranchProtectedScope();
12151   return OMPDistributeParallelForDirective::Create(
12152       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12153       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12154 }
12155 
12156 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
12157     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12158     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12159   if (!AStmt)
12160     return StmtError();
12161 
12162   auto *CS = cast<CapturedStmt>(AStmt);
12163   // 1.2.2 OpenMP Language Terminology
12164   // Structured block - An executable statement with a single entry at the
12165   // top and a single exit at the bottom.
12166   // The point of exit cannot be a branch out of the structured block.
12167   // longjmp() and throw() must not violate the entry/exit criteria.
12168   CS->getCapturedDecl()->setNothrow();
12169   for (int ThisCaptureLevel =
12170            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
12171        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12172     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12173     // 1.2.2 OpenMP Language Terminology
12174     // Structured block - An executable statement with a single entry at the
12175     // top and a single exit at the bottom.
12176     // The point of exit cannot be a branch out of the structured block.
12177     // longjmp() and throw() must not violate the entry/exit criteria.
12178     CS->getCapturedDecl()->setNothrow();
12179   }
12180 
12181   OMPLoopBasedDirective::HelperExprs B;
12182   // In presence of clause 'collapse' with number of loops, it will
12183   // define the nested loops number.
12184   unsigned NestedLoopCount = checkOpenMPLoop(
12185       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12186       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12187       VarsWithImplicitDSA, B);
12188   if (NestedLoopCount == 0)
12189     return StmtError();
12190 
12191   assert((CurContext->isDependentContext() || B.builtAll()) &&
12192          "omp for loop exprs were not built");
12193 
12194   if (!CurContext->isDependentContext()) {
12195     // Finalize the clauses that need pre-built expressions for CodeGen.
12196     for (OMPClause *C : Clauses) {
12197       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12198         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12199                                      B.NumIterations, *this, CurScope,
12200                                      DSAStack))
12201           return StmtError();
12202     }
12203   }
12204 
12205   if (checkSimdlenSafelenSpecified(*this, Clauses))
12206     return StmtError();
12207 
12208   setFunctionHasBranchProtectedScope();
12209   return OMPDistributeParallelForSimdDirective::Create(
12210       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12211 }
12212 
12213 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
12214     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12215     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12216   if (!AStmt)
12217     return StmtError();
12218 
12219   auto *CS = cast<CapturedStmt>(AStmt);
12220   // 1.2.2 OpenMP Language Terminology
12221   // Structured block - An executable statement with a single entry at the
12222   // top and a single exit at the bottom.
12223   // The point of exit cannot be a branch out of the structured block.
12224   // longjmp() and throw() must not violate the entry/exit criteria.
12225   CS->getCapturedDecl()->setNothrow();
12226   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
12227        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12228     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12229     // 1.2.2 OpenMP Language Terminology
12230     // Structured block - An executable statement with a single entry at the
12231     // top and a single exit at the bottom.
12232     // The point of exit cannot be a branch out of the structured block.
12233     // longjmp() and throw() must not violate the entry/exit criteria.
12234     CS->getCapturedDecl()->setNothrow();
12235   }
12236 
12237   OMPLoopBasedDirective::HelperExprs B;
12238   // In presence of clause 'collapse' with number of loops, it will
12239   // define the nested loops number.
12240   unsigned NestedLoopCount =
12241       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
12242                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12243                       *DSAStack, VarsWithImplicitDSA, B);
12244   if (NestedLoopCount == 0)
12245     return StmtError();
12246 
12247   assert((CurContext->isDependentContext() || B.builtAll()) &&
12248          "omp for loop exprs were not built");
12249 
12250   if (!CurContext->isDependentContext()) {
12251     // Finalize the clauses that need pre-built expressions for CodeGen.
12252     for (OMPClause *C : Clauses) {
12253       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12254         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12255                                      B.NumIterations, *this, CurScope,
12256                                      DSAStack))
12257           return StmtError();
12258     }
12259   }
12260 
12261   if (checkSimdlenSafelenSpecified(*this, Clauses))
12262     return StmtError();
12263 
12264   setFunctionHasBranchProtectedScope();
12265   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
12266                                             NestedLoopCount, Clauses, AStmt, B);
12267 }
12268 
12269 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
12270     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12271     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12272   if (!AStmt)
12273     return StmtError();
12274 
12275   auto *CS = cast<CapturedStmt>(AStmt);
12276   // 1.2.2 OpenMP Language Terminology
12277   // Structured block - An executable statement with a single entry at the
12278   // top and a single exit at the bottom.
12279   // The point of exit cannot be a branch out of the structured block.
12280   // longjmp() and throw() must not violate the entry/exit criteria.
12281   CS->getCapturedDecl()->setNothrow();
12282   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12283        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12284     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12285     // 1.2.2 OpenMP Language Terminology
12286     // Structured block - An executable statement with a single entry at the
12287     // top and a single exit at the bottom.
12288     // The point of exit cannot be a branch out of the structured block.
12289     // longjmp() and throw() must not violate the entry/exit criteria.
12290     CS->getCapturedDecl()->setNothrow();
12291   }
12292 
12293   OMPLoopBasedDirective::HelperExprs B;
12294   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12295   // define the nested loops number.
12296   unsigned NestedLoopCount = checkOpenMPLoop(
12297       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12298       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
12299       B);
12300   if (NestedLoopCount == 0)
12301     return StmtError();
12302 
12303   assert((CurContext->isDependentContext() || B.builtAll()) &&
12304          "omp target parallel for simd loop exprs were not built");
12305 
12306   if (!CurContext->isDependentContext()) {
12307     // Finalize the clauses that need pre-built expressions for CodeGen.
12308     for (OMPClause *C : Clauses) {
12309       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12310         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12311                                      B.NumIterations, *this, CurScope,
12312                                      DSAStack))
12313           return StmtError();
12314     }
12315   }
12316   if (checkSimdlenSafelenSpecified(*this, Clauses))
12317     return StmtError();
12318 
12319   setFunctionHasBranchProtectedScope();
12320   return OMPTargetParallelForSimdDirective::Create(
12321       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12322 }
12323 
12324 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12325     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12326     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12327   if (!AStmt)
12328     return StmtError();
12329 
12330   auto *CS = cast<CapturedStmt>(AStmt);
12331   // 1.2.2 OpenMP Language Terminology
12332   // Structured block - An executable statement with a single entry at the
12333   // top and a single exit at the bottom.
12334   // The point of exit cannot be a branch out of the structured block.
12335   // longjmp() and throw() must not violate the entry/exit criteria.
12336   CS->getCapturedDecl()->setNothrow();
12337   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12338        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12339     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12340     // 1.2.2 OpenMP Language Terminology
12341     // Structured block - An executable statement with a single entry at the
12342     // top and a single exit at the bottom.
12343     // The point of exit cannot be a branch out of the structured block.
12344     // longjmp() and throw() must not violate the entry/exit criteria.
12345     CS->getCapturedDecl()->setNothrow();
12346   }
12347 
12348   OMPLoopBasedDirective::HelperExprs B;
12349   // In presence of clause 'collapse' with number of loops, it will define the
12350   // nested loops number.
12351   unsigned NestedLoopCount =
12352       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12353                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12354                       VarsWithImplicitDSA, B);
12355   if (NestedLoopCount == 0)
12356     return StmtError();
12357 
12358   assert((CurContext->isDependentContext() || B.builtAll()) &&
12359          "omp target simd loop exprs were not built");
12360 
12361   if (!CurContext->isDependentContext()) {
12362     // Finalize the clauses that need pre-built expressions for CodeGen.
12363     for (OMPClause *C : Clauses) {
12364       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12365         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12366                                      B.NumIterations, *this, CurScope,
12367                                      DSAStack))
12368           return StmtError();
12369     }
12370   }
12371 
12372   if (checkSimdlenSafelenSpecified(*this, Clauses))
12373     return StmtError();
12374 
12375   setFunctionHasBranchProtectedScope();
12376   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12377                                         NestedLoopCount, Clauses, AStmt, B);
12378 }
12379 
12380 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12381     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12382     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12383   if (!AStmt)
12384     return StmtError();
12385 
12386   auto *CS = cast<CapturedStmt>(AStmt);
12387   // 1.2.2 OpenMP Language Terminology
12388   // Structured block - An executable statement with a single entry at the
12389   // top and a single exit at the bottom.
12390   // The point of exit cannot be a branch out of the structured block.
12391   // longjmp() and throw() must not violate the entry/exit criteria.
12392   CS->getCapturedDecl()->setNothrow();
12393   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12394        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12395     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12396     // 1.2.2 OpenMP Language Terminology
12397     // Structured block - An executable statement with a single entry at the
12398     // top and a single exit at the bottom.
12399     // The point of exit cannot be a branch out of the structured block.
12400     // longjmp() and throw() must not violate the entry/exit criteria.
12401     CS->getCapturedDecl()->setNothrow();
12402   }
12403 
12404   OMPLoopBasedDirective::HelperExprs B;
12405   // In presence of clause 'collapse' with number of loops, it will
12406   // define the nested loops number.
12407   unsigned NestedLoopCount =
12408       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12409                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12410                       *DSAStack, VarsWithImplicitDSA, B);
12411   if (NestedLoopCount == 0)
12412     return StmtError();
12413 
12414   assert((CurContext->isDependentContext() || B.builtAll()) &&
12415          "omp teams distribute loop exprs were not built");
12416 
12417   setFunctionHasBranchProtectedScope();
12418 
12419   DSAStack->setParentTeamsRegionLoc(StartLoc);
12420 
12421   return OMPTeamsDistributeDirective::Create(
12422       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12423 }
12424 
12425 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12426     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12427     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12428   if (!AStmt)
12429     return StmtError();
12430 
12431   auto *CS = cast<CapturedStmt>(AStmt);
12432   // 1.2.2 OpenMP Language Terminology
12433   // Structured block - An executable statement with a single entry at the
12434   // top and a single exit at the bottom.
12435   // The point of exit cannot be a branch out of the structured block.
12436   // longjmp() and throw() must not violate the entry/exit criteria.
12437   CS->getCapturedDecl()->setNothrow();
12438   for (int ThisCaptureLevel =
12439            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12440        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12441     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12442     // 1.2.2 OpenMP Language Terminology
12443     // Structured block - An executable statement with a single entry at the
12444     // top and a single exit at the bottom.
12445     // The point of exit cannot be a branch out of the structured block.
12446     // longjmp() and throw() must not violate the entry/exit criteria.
12447     CS->getCapturedDecl()->setNothrow();
12448   }
12449 
12450   OMPLoopBasedDirective::HelperExprs B;
12451   // In presence of clause 'collapse' with number of loops, it will
12452   // define the nested loops number.
12453   unsigned NestedLoopCount = checkOpenMPLoop(
12454       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12455       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12456       VarsWithImplicitDSA, B);
12457 
12458   if (NestedLoopCount == 0)
12459     return StmtError();
12460 
12461   assert((CurContext->isDependentContext() || B.builtAll()) &&
12462          "omp teams distribute simd loop exprs were not built");
12463 
12464   if (!CurContext->isDependentContext()) {
12465     // Finalize the clauses that need pre-built expressions for CodeGen.
12466     for (OMPClause *C : Clauses) {
12467       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12468         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12469                                      B.NumIterations, *this, CurScope,
12470                                      DSAStack))
12471           return StmtError();
12472     }
12473   }
12474 
12475   if (checkSimdlenSafelenSpecified(*this, Clauses))
12476     return StmtError();
12477 
12478   setFunctionHasBranchProtectedScope();
12479 
12480   DSAStack->setParentTeamsRegionLoc(StartLoc);
12481 
12482   return OMPTeamsDistributeSimdDirective::Create(
12483       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12484 }
12485 
12486 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12487     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12488     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12489   if (!AStmt)
12490     return StmtError();
12491 
12492   auto *CS = cast<CapturedStmt>(AStmt);
12493   // 1.2.2 OpenMP Language Terminology
12494   // Structured block - An executable statement with a single entry at the
12495   // top and a single exit at the bottom.
12496   // The point of exit cannot be a branch out of the structured block.
12497   // longjmp() and throw() must not violate the entry/exit criteria.
12498   CS->getCapturedDecl()->setNothrow();
12499 
12500   for (int ThisCaptureLevel =
12501            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12502        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12503     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12504     // 1.2.2 OpenMP Language Terminology
12505     // Structured block - An executable statement with a single entry at the
12506     // top and a single exit at the bottom.
12507     // The point of exit cannot be a branch out of the structured block.
12508     // longjmp() and throw() must not violate the entry/exit criteria.
12509     CS->getCapturedDecl()->setNothrow();
12510   }
12511 
12512   OMPLoopBasedDirective::HelperExprs B;
12513   // In presence of clause 'collapse' with number of loops, it will
12514   // define the nested loops number.
12515   unsigned NestedLoopCount = checkOpenMPLoop(
12516       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12517       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12518       VarsWithImplicitDSA, B);
12519 
12520   if (NestedLoopCount == 0)
12521     return StmtError();
12522 
12523   assert((CurContext->isDependentContext() || B.builtAll()) &&
12524          "omp for loop exprs were not built");
12525 
12526   if (!CurContext->isDependentContext()) {
12527     // Finalize the clauses that need pre-built expressions for CodeGen.
12528     for (OMPClause *C : Clauses) {
12529       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12530         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12531                                      B.NumIterations, *this, CurScope,
12532                                      DSAStack))
12533           return StmtError();
12534     }
12535   }
12536 
12537   if (checkSimdlenSafelenSpecified(*this, Clauses))
12538     return StmtError();
12539 
12540   setFunctionHasBranchProtectedScope();
12541 
12542   DSAStack->setParentTeamsRegionLoc(StartLoc);
12543 
12544   return OMPTeamsDistributeParallelForSimdDirective::Create(
12545       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12546 }
12547 
12548 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12549     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12550     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12551   if (!AStmt)
12552     return StmtError();
12553 
12554   auto *CS = cast<CapturedStmt>(AStmt);
12555   // 1.2.2 OpenMP Language Terminology
12556   // Structured block - An executable statement with a single entry at the
12557   // top and a single exit at the bottom.
12558   // The point of exit cannot be a branch out of the structured block.
12559   // longjmp() and throw() must not violate the entry/exit criteria.
12560   CS->getCapturedDecl()->setNothrow();
12561 
12562   for (int ThisCaptureLevel =
12563            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12564        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12565     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12566     // 1.2.2 OpenMP Language Terminology
12567     // Structured block - An executable statement with a single entry at the
12568     // top and a single exit at the bottom.
12569     // The point of exit cannot be a branch out of the structured block.
12570     // longjmp() and throw() must not violate the entry/exit criteria.
12571     CS->getCapturedDecl()->setNothrow();
12572   }
12573 
12574   OMPLoopBasedDirective::HelperExprs B;
12575   // In presence of clause 'collapse' with number of loops, it will
12576   // define the nested loops number.
12577   unsigned NestedLoopCount = checkOpenMPLoop(
12578       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12579       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12580       VarsWithImplicitDSA, B);
12581 
12582   if (NestedLoopCount == 0)
12583     return StmtError();
12584 
12585   assert((CurContext->isDependentContext() || B.builtAll()) &&
12586          "omp for loop exprs were not built");
12587 
12588   setFunctionHasBranchProtectedScope();
12589 
12590   DSAStack->setParentTeamsRegionLoc(StartLoc);
12591 
12592   return OMPTeamsDistributeParallelForDirective::Create(
12593       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12594       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12595 }
12596 
12597 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12598                                                  Stmt *AStmt,
12599                                                  SourceLocation StartLoc,
12600                                                  SourceLocation EndLoc) {
12601   if (!AStmt)
12602     return StmtError();
12603 
12604   auto *CS = cast<CapturedStmt>(AStmt);
12605   // 1.2.2 OpenMP Language Terminology
12606   // Structured block - An executable statement with a single entry at the
12607   // top and a single exit at the bottom.
12608   // The point of exit cannot be a branch out of the structured block.
12609   // longjmp() and throw() must not violate the entry/exit criteria.
12610   CS->getCapturedDecl()->setNothrow();
12611 
12612   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12613        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12614     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12615     // 1.2.2 OpenMP Language Terminology
12616     // Structured block - An executable statement with a single entry at the
12617     // top and a single exit at the bottom.
12618     // The point of exit cannot be a branch out of the structured block.
12619     // longjmp() and throw() must not violate the entry/exit criteria.
12620     CS->getCapturedDecl()->setNothrow();
12621   }
12622   setFunctionHasBranchProtectedScope();
12623 
12624   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12625                                          AStmt);
12626 }
12627 
12628 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12629     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12630     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12631   if (!AStmt)
12632     return StmtError();
12633 
12634   auto *CS = cast<CapturedStmt>(AStmt);
12635   // 1.2.2 OpenMP Language Terminology
12636   // Structured block - An executable statement with a single entry at the
12637   // top and a single exit at the bottom.
12638   // The point of exit cannot be a branch out of the structured block.
12639   // longjmp() and throw() must not violate the entry/exit criteria.
12640   CS->getCapturedDecl()->setNothrow();
12641   for (int ThisCaptureLevel =
12642            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12643        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12644     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12645     // 1.2.2 OpenMP Language Terminology
12646     // Structured block - An executable statement with a single entry at the
12647     // top and a single exit at the bottom.
12648     // The point of exit cannot be a branch out of the structured block.
12649     // longjmp() and throw() must not violate the entry/exit criteria.
12650     CS->getCapturedDecl()->setNothrow();
12651   }
12652 
12653   OMPLoopBasedDirective::HelperExprs B;
12654   // In presence of clause 'collapse' with number of loops, it will
12655   // define the nested loops number.
12656   unsigned NestedLoopCount = checkOpenMPLoop(
12657       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12658       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12659       VarsWithImplicitDSA, B);
12660   if (NestedLoopCount == 0)
12661     return StmtError();
12662 
12663   assert((CurContext->isDependentContext() || B.builtAll()) &&
12664          "omp target teams distribute loop exprs were not built");
12665 
12666   setFunctionHasBranchProtectedScope();
12667   return OMPTargetTeamsDistributeDirective::Create(
12668       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12669 }
12670 
12671 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12672     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12673     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12674   if (!AStmt)
12675     return StmtError();
12676 
12677   auto *CS = cast<CapturedStmt>(AStmt);
12678   // 1.2.2 OpenMP Language Terminology
12679   // Structured block - An executable statement with a single entry at the
12680   // top and a single exit at the bottom.
12681   // The point of exit cannot be a branch out of the structured block.
12682   // longjmp() and throw() must not violate the entry/exit criteria.
12683   CS->getCapturedDecl()->setNothrow();
12684   for (int ThisCaptureLevel =
12685            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12686        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12687     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12688     // 1.2.2 OpenMP Language Terminology
12689     // Structured block - An executable statement with a single entry at the
12690     // top and a single exit at the bottom.
12691     // The point of exit cannot be a branch out of the structured block.
12692     // longjmp() and throw() must not violate the entry/exit criteria.
12693     CS->getCapturedDecl()->setNothrow();
12694   }
12695 
12696   OMPLoopBasedDirective::HelperExprs B;
12697   // In presence of clause 'collapse' with number of loops, it will
12698   // define the nested loops number.
12699   unsigned NestedLoopCount = checkOpenMPLoop(
12700       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12701       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12702       VarsWithImplicitDSA, B);
12703   if (NestedLoopCount == 0)
12704     return StmtError();
12705 
12706   assert((CurContext->isDependentContext() || B.builtAll()) &&
12707          "omp target teams distribute parallel for loop exprs were not built");
12708 
12709   if (!CurContext->isDependentContext()) {
12710     // Finalize the clauses that need pre-built expressions for CodeGen.
12711     for (OMPClause *C : Clauses) {
12712       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12713         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12714                                      B.NumIterations, *this, CurScope,
12715                                      DSAStack))
12716           return StmtError();
12717     }
12718   }
12719 
12720   setFunctionHasBranchProtectedScope();
12721   return OMPTargetTeamsDistributeParallelForDirective::Create(
12722       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12723       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12724 }
12725 
12726 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12727     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12728     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12729   if (!AStmt)
12730     return StmtError();
12731 
12732   auto *CS = cast<CapturedStmt>(AStmt);
12733   // 1.2.2 OpenMP Language Terminology
12734   // Structured block - An executable statement with a single entry at the
12735   // top and a single exit at the bottom.
12736   // The point of exit cannot be a branch out of the structured block.
12737   // longjmp() and throw() must not violate the entry/exit criteria.
12738   CS->getCapturedDecl()->setNothrow();
12739   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12740            OMPD_target_teams_distribute_parallel_for_simd);
12741        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12742     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12743     // 1.2.2 OpenMP Language Terminology
12744     // Structured block - An executable statement with a single entry at the
12745     // top and a single exit at the bottom.
12746     // The point of exit cannot be a branch out of the structured block.
12747     // longjmp() and throw() must not violate the entry/exit criteria.
12748     CS->getCapturedDecl()->setNothrow();
12749   }
12750 
12751   OMPLoopBasedDirective::HelperExprs B;
12752   // In presence of clause 'collapse' with number of loops, it will
12753   // define the nested loops number.
12754   unsigned NestedLoopCount =
12755       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12756                       getCollapseNumberExpr(Clauses),
12757                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12758                       *DSAStack, VarsWithImplicitDSA, B);
12759   if (NestedLoopCount == 0)
12760     return StmtError();
12761 
12762   assert((CurContext->isDependentContext() || B.builtAll()) &&
12763          "omp target teams distribute parallel for simd loop exprs were not "
12764          "built");
12765 
12766   if (!CurContext->isDependentContext()) {
12767     // Finalize the clauses that need pre-built expressions for CodeGen.
12768     for (OMPClause *C : Clauses) {
12769       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12770         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12771                                      B.NumIterations, *this, CurScope,
12772                                      DSAStack))
12773           return StmtError();
12774     }
12775   }
12776 
12777   if (checkSimdlenSafelenSpecified(*this, Clauses))
12778     return StmtError();
12779 
12780   setFunctionHasBranchProtectedScope();
12781   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12782       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12783 }
12784 
12785 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12786     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12787     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12788   if (!AStmt)
12789     return StmtError();
12790 
12791   auto *CS = cast<CapturedStmt>(AStmt);
12792   // 1.2.2 OpenMP Language Terminology
12793   // Structured block - An executable statement with a single entry at the
12794   // top and a single exit at the bottom.
12795   // The point of exit cannot be a branch out of the structured block.
12796   // longjmp() and throw() must not violate the entry/exit criteria.
12797   CS->getCapturedDecl()->setNothrow();
12798   for (int ThisCaptureLevel =
12799            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12800        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12801     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12802     // 1.2.2 OpenMP Language Terminology
12803     // Structured block - An executable statement with a single entry at the
12804     // top and a single exit at the bottom.
12805     // The point of exit cannot be a branch out of the structured block.
12806     // longjmp() and throw() must not violate the entry/exit criteria.
12807     CS->getCapturedDecl()->setNothrow();
12808   }
12809 
12810   OMPLoopBasedDirective::HelperExprs B;
12811   // In presence of clause 'collapse' with number of loops, it will
12812   // define the nested loops number.
12813   unsigned NestedLoopCount = checkOpenMPLoop(
12814       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12815       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12816       VarsWithImplicitDSA, B);
12817   if (NestedLoopCount == 0)
12818     return StmtError();
12819 
12820   assert((CurContext->isDependentContext() || B.builtAll()) &&
12821          "omp target teams distribute simd loop exprs were not built");
12822 
12823   if (!CurContext->isDependentContext()) {
12824     // Finalize the clauses that need pre-built expressions for CodeGen.
12825     for (OMPClause *C : Clauses) {
12826       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12827         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12828                                      B.NumIterations, *this, CurScope,
12829                                      DSAStack))
12830           return StmtError();
12831     }
12832   }
12833 
12834   if (checkSimdlenSafelenSpecified(*this, Clauses))
12835     return StmtError();
12836 
12837   setFunctionHasBranchProtectedScope();
12838   return OMPTargetTeamsDistributeSimdDirective::Create(
12839       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12840 }
12841 
12842 bool Sema::checkTransformableLoopNest(
12843     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
12844     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
12845     Stmt *&Body,
12846     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
12847         &OriginalInits) {
12848   OriginalInits.emplace_back();
12849   bool Result = OMPLoopBasedDirective::doForAllLoops(
12850       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
12851       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
12852                                                         Stmt *CurStmt) {
12853         VarsWithInheritedDSAType TmpDSA;
12854         unsigned SingleNumLoops =
12855             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
12856                             TmpDSA, LoopHelpers[Cnt]);
12857         if (SingleNumLoops == 0)
12858           return true;
12859         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12860         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12861           OriginalInits.back().push_back(For->getInit());
12862           Body = For->getBody();
12863         } else {
12864           assert(isa<CXXForRangeStmt>(CurStmt) &&
12865                  "Expected canonical for or range-based for loops.");
12866           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12867           OriginalInits.back().push_back(CXXFor->getBeginStmt());
12868           Body = CXXFor->getBody();
12869         }
12870         OriginalInits.emplace_back();
12871         return false;
12872       },
12873       [&OriginalInits](OMPLoopBasedDirective *Transform) {
12874         Stmt *DependentPreInits;
12875         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
12876           DependentPreInits = Dir->getPreInits();
12877         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
12878           DependentPreInits = Dir->getPreInits();
12879         else
12880           llvm_unreachable("Unhandled loop transformation");
12881         if (!DependentPreInits)
12882           return;
12883         for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
12884           OriginalInits.back().push_back(C);
12885       });
12886   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
12887   OriginalInits.pop_back();
12888   return Result;
12889 }
12890 
12891 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12892                                           Stmt *AStmt, SourceLocation StartLoc,
12893                                           SourceLocation EndLoc) {
12894   auto SizesClauses =
12895       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12896   if (SizesClauses.empty()) {
12897     // A missing 'sizes' clause is already reported by the parser.
12898     return StmtError();
12899   }
12900   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12901   unsigned NumLoops = SizesClause->getNumSizes();
12902 
12903   // Empty statement should only be possible if there already was an error.
12904   if (!AStmt)
12905     return StmtError();
12906 
12907   // Verify and diagnose loop nest.
12908   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12909   Stmt *Body = nullptr;
12910   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
12911       OriginalInits;
12912   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
12913                                   OriginalInits))
12914     return StmtError();
12915 
12916   // Delay tiling to when template is completely instantiated.
12917   if (CurContext->isDependentContext())
12918     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12919                                     NumLoops, AStmt, nullptr, nullptr);
12920 
12921   SmallVector<Decl *, 4> PreInits;
12922 
12923   // Create iteration variables for the generated loops.
12924   SmallVector<VarDecl *, 4> FloorIndVars;
12925   SmallVector<VarDecl *, 4> TileIndVars;
12926   FloorIndVars.resize(NumLoops);
12927   TileIndVars.resize(NumLoops);
12928   for (unsigned I = 0; I < NumLoops; ++I) {
12929     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12930 
12931     assert(LoopHelper.Counters.size() == 1 &&
12932            "Expect single-dimensional loop iteration space");
12933     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12934     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12935     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12936     QualType CntTy = IterVarRef->getType();
12937 
12938     // Iteration variable for the floor (i.e. outer) loop.
12939     {
12940       std::string FloorCntName =
12941           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12942       VarDecl *FloorCntDecl =
12943           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12944       FloorIndVars[I] = FloorCntDecl;
12945     }
12946 
12947     // Iteration variable for the tile (i.e. inner) loop.
12948     {
12949       std::string TileCntName =
12950           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12951 
12952       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12953       // used by the expressions to derive the original iteration variable's
12954       // value from the logical iteration number.
12955       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12956       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12957       TileIndVars[I] = TileCntDecl;
12958     }
12959     for (auto &P : OriginalInits[I]) {
12960       if (auto *D = P.dyn_cast<Decl *>())
12961         PreInits.push_back(D);
12962       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12963         PreInits.append(PI->decl_begin(), PI->decl_end());
12964     }
12965     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12966       PreInits.append(PI->decl_begin(), PI->decl_end());
12967     // Gather declarations for the data members used as counters.
12968     for (Expr *CounterRef : LoopHelper.Counters) {
12969       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12970       if (isa<OMPCapturedExprDecl>(CounterDecl))
12971         PreInits.push_back(CounterDecl);
12972     }
12973   }
12974 
12975   // Once the original iteration values are set, append the innermost body.
12976   Stmt *Inner = Body;
12977 
12978   // Create tile loops from the inside to the outside.
12979   for (int I = NumLoops - 1; I >= 0; --I) {
12980     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12981     Expr *NumIterations = LoopHelper.NumIterations;
12982     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12983     QualType CntTy = OrigCntVar->getType();
12984     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12985     Scope *CurScope = getCurScope();
12986 
12987     // Commonly used variables.
12988     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12989                                            OrigCntVar->getExprLoc());
12990     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12991                                             OrigCntVar->getExprLoc());
12992 
12993     // For init-statement: auto .tile.iv = .floor.iv
12994     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12995                          /*DirectInit=*/false);
12996     Decl *CounterDecl = TileIndVars[I];
12997     StmtResult InitStmt = new (Context)
12998         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12999                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13000     if (!InitStmt.isUsable())
13001       return StmtError();
13002 
13003     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
13004     // NumIterations)
13005     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13006                                       BO_Add, FloorIV, DimTileSize);
13007     if (!EndOfTile.isUsable())
13008       return StmtError();
13009     ExprResult IsPartialTile =
13010         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
13011                    NumIterations, EndOfTile.get());
13012     if (!IsPartialTile.isUsable())
13013       return StmtError();
13014     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
13015         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
13016         IsPartialTile.get(), NumIterations, EndOfTile.get());
13017     if (!MinTileAndIterSpace.isUsable())
13018       return StmtError();
13019     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13020                                      BO_LT, TileIV, MinTileAndIterSpace.get());
13021     if (!CondExpr.isUsable())
13022       return StmtError();
13023 
13024     // For incr-statement: ++.tile.iv
13025     ExprResult IncrStmt =
13026         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
13027     if (!IncrStmt.isUsable())
13028       return StmtError();
13029 
13030     // Statements to set the original iteration variable's value from the
13031     // logical iteration number.
13032     // Generated for loop is:
13033     // Original_for_init;
13034     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
13035     // NumIterations); ++.tile.iv) {
13036     //   Original_Body;
13037     //   Original_counter_update;
13038     // }
13039     // FIXME: If the innermost body is an loop itself, inserting these
13040     // statements stops it being recognized  as a perfectly nested loop (e.g.
13041     // for applying tiling again). If this is the case, sink the expressions
13042     // further into the inner loop.
13043     SmallVector<Stmt *, 4> BodyParts;
13044     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13045     BodyParts.push_back(Inner);
13046     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
13047                                  Inner->getEndLoc());
13048     Inner = new (Context)
13049         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13050                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13051                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13052   }
13053 
13054   // Create floor loops from the inside to the outside.
13055   for (int I = NumLoops - 1; I >= 0; --I) {
13056     auto &LoopHelper = LoopHelpers[I];
13057     Expr *NumIterations = LoopHelper.NumIterations;
13058     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
13059     QualType CntTy = OrigCntVar->getType();
13060     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
13061     Scope *CurScope = getCurScope();
13062 
13063     // Commonly used variables.
13064     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
13065                                             OrigCntVar->getExprLoc());
13066 
13067     // For init-statement: auto .floor.iv = 0
13068     AddInitializerToDecl(
13069         FloorIndVars[I],
13070         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13071         /*DirectInit=*/false);
13072     Decl *CounterDecl = FloorIndVars[I];
13073     StmtResult InitStmt = new (Context)
13074         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
13075                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13076     if (!InitStmt.isUsable())
13077       return StmtError();
13078 
13079     // For cond-expression: .floor.iv < NumIterations
13080     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13081                                      BO_LT, FloorIV, NumIterations);
13082     if (!CondExpr.isUsable())
13083       return StmtError();
13084 
13085     // For incr-statement: .floor.iv += DimTileSize
13086     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
13087                                      BO_AddAssign, FloorIV, DimTileSize);
13088     if (!IncrStmt.isUsable())
13089       return StmtError();
13090 
13091     Inner = new (Context)
13092         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13093                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13094                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13095   }
13096 
13097   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
13098                                   AStmt, Inner,
13099                                   buildPreInits(Context, PreInits));
13100 }
13101 
13102 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
13103                                             Stmt *AStmt,
13104                                             SourceLocation StartLoc,
13105                                             SourceLocation EndLoc) {
13106   // Empty statement should only be possible if there already was an error.
13107   if (!AStmt)
13108     return StmtError();
13109 
13110   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
13111     return StmtError();
13112 
13113   const OMPFullClause *FullClause =
13114       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
13115   const OMPPartialClause *PartialClause =
13116       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
13117   assert(!(FullClause && PartialClause) &&
13118          "mutual exclusivity must have been checked before");
13119 
13120   constexpr unsigned NumLoops = 1;
13121   Stmt *Body = nullptr;
13122   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
13123       NumLoops);
13124   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
13125       OriginalInits;
13126   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
13127                                   Body, OriginalInits))
13128     return StmtError();
13129 
13130   unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
13131 
13132   // Delay unrolling to when template is completely instantiated.
13133   if (CurContext->isDependentContext())
13134     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13135                                       NumGeneratedLoops, nullptr, nullptr);
13136 
13137   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
13138 
13139   if (FullClause) {
13140     if (!VerifyPositiveIntegerConstantInClause(
13141              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
13142              /*SuppressExprDigs=*/true)
13143              .isUsable()) {
13144       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
13145       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
13146           << "#pragma omp unroll full";
13147       return StmtError();
13148     }
13149   }
13150 
13151   // The generated loop may only be passed to other loop-associated directive
13152   // when a partial clause is specified. Without the requirement it is
13153   // sufficient to generate loop unroll metadata at code-generation.
13154   if (NumGeneratedLoops == 0)
13155     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13156                                       NumGeneratedLoops, nullptr, nullptr);
13157 
13158   // Otherwise, we need to provide a de-sugared/transformed AST that can be
13159   // associated with another loop directive.
13160   //
13161   // The canonical loop analysis return by checkTransformableLoopNest assumes
13162   // the following structure to be the same loop without transformations or
13163   // directives applied: \code OriginalInits; LoopHelper.PreInits;
13164   // LoopHelper.Counters;
13165   // for (; IV < LoopHelper.NumIterations; ++IV) {
13166   //   LoopHelper.Updates;
13167   //   Body;
13168   // }
13169   // \endcode
13170   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
13171   // and referenced by LoopHelper.IterationVarRef.
13172   //
13173   // The unrolling directive transforms this into the following loop:
13174   // \code
13175   // OriginalInits;         \
13176   // LoopHelper.PreInits;    > NewPreInits
13177   // LoopHelper.Counters;   /
13178   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
13179   //   #pragma clang loop unroll_count(Factor)
13180   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
13181   //   {
13182   //     LoopHelper.Updates;
13183   //     Body;
13184   //   }
13185   // }
13186   // \endcode
13187   // where UIV is a new logical iteration counter. IV must be the same VarDecl
13188   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
13189   // references it. If the partially unrolled loop is associated with another
13190   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
13191   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
13192   // OpenMP canonical loop. The inner loop is not an associable canonical loop
13193   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
13194   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
13195   // property of the OMPLoopBasedDirective instead of statements in
13196   // CompoundStatement. This is to allow the loop to become a non-outermost loop
13197   // of a canonical loop nest where these PreInits are emitted before the
13198   // outermost directive.
13199 
13200   // Determine the PreInit declarations.
13201   SmallVector<Decl *, 4> PreInits;
13202   assert(OriginalInits.size() == 1 &&
13203          "Expecting a single-dimensional loop iteration space");
13204   for (auto &P : OriginalInits[0]) {
13205     if (auto *D = P.dyn_cast<Decl *>())
13206       PreInits.push_back(D);
13207     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
13208       PreInits.append(PI->decl_begin(), PI->decl_end());
13209   }
13210   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
13211     PreInits.append(PI->decl_begin(), PI->decl_end());
13212   // Gather declarations for the data members used as counters.
13213   for (Expr *CounterRef : LoopHelper.Counters) {
13214     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
13215     if (isa<OMPCapturedExprDecl>(CounterDecl))
13216       PreInits.push_back(CounterDecl);
13217   }
13218 
13219   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
13220   QualType IVTy = IterationVarRef->getType();
13221   assert(LoopHelper.Counters.size() == 1 &&
13222          "Expecting a single-dimensional loop iteration space");
13223   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
13224 
13225   // Determine the unroll factor.
13226   uint64_t Factor;
13227   SourceLocation FactorLoc;
13228   if (Expr *FactorVal = PartialClause->getFactor()) {
13229     Factor =
13230         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
13231     FactorLoc = FactorVal->getExprLoc();
13232   } else {
13233     // TODO: Use a better profitability model.
13234     Factor = 2;
13235   }
13236   assert(Factor > 0 && "Expected positive unroll factor");
13237   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
13238     return IntegerLiteral::Create(
13239         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
13240         FactorLoc);
13241   };
13242 
13243   // Iteration variable SourceLocations.
13244   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
13245   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
13246   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
13247 
13248   // Internal variable names.
13249   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
13250   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
13251   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
13252   std::string InnerTripCountName =
13253       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
13254 
13255   // Create the iteration variable for the unrolled loop.
13256   VarDecl *OuterIVDecl =
13257       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
13258   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
13259     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
13260   };
13261 
13262   // Iteration variable for the inner loop: Reuse the iteration variable created
13263   // by checkOpenMPLoop.
13264   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
13265   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
13266   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
13267     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
13268   };
13269 
13270   // Make a copy of the NumIterations expression for each use: By the AST
13271   // constraints, every expression object in a DeclContext must be unique.
13272   CaptureVars CopyTransformer(*this);
13273   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
13274     return AssertSuccess(
13275         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
13276   };
13277 
13278   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
13279   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
13280   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
13281   StmtResult InnerInit = new (Context)
13282       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13283   if (!InnerInit.isUsable())
13284     return StmtError();
13285 
13286   // Inner For cond-expression:
13287   // \code
13288   //   .unroll_inner.iv < .unrolled.iv + Factor &&
13289   //   .unroll_inner.iv < NumIterations
13290   // \endcode
13291   // This conjunction of two conditions allows ScalarEvolution to derive the
13292   // maximum trip count of the inner loop.
13293   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13294                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
13295   if (!EndOfTile.isUsable())
13296     return StmtError();
13297   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13298                                      BO_LE, MakeInnerRef(), EndOfTile.get());
13299   if (!InnerCond1.isUsable())
13300     return StmtError();
13301   ExprResult InnerCond2 =
13302       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
13303                  MakeNumIterations());
13304   if (!InnerCond2.isUsable())
13305     return StmtError();
13306   ExprResult InnerCond =
13307       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
13308                  InnerCond1.get(), InnerCond2.get());
13309   if (!InnerCond.isUsable())
13310     return StmtError();
13311 
13312   // Inner For incr-statement: ++.unroll_inner.iv
13313   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
13314                                       UO_PreInc, MakeInnerRef());
13315   if (!InnerIncr.isUsable())
13316     return StmtError();
13317 
13318   // Inner For statement.
13319   SmallVector<Stmt *> InnerBodyStmts;
13320   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13321   InnerBodyStmts.push_back(Body);
13322   CompoundStmt *InnerBody = CompoundStmt::Create(
13323       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
13324   ForStmt *InnerFor = new (Context)
13325       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
13326               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
13327               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13328 
13329   // Unroll metadata for the inner loop.
13330   // This needs to take into account the remainder portion of the unrolled loop,
13331   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
13332   // supports multiple loop exits. Instead, unroll using a factor equivalent to
13333   // the maximum trip count, which will also generate a remainder loop. Just
13334   // `unroll(enable)` (which could have been useful if the user has not
13335   // specified a concrete factor; even though the outer loop cannot be
13336   // influenced anymore, would avoid more code bloat than necessary) will refuse
13337   // the loop because "Won't unroll; remainder loop could not be generated when
13338   // assuming runtime trip count". Even if it did work, it must not choose a
13339   // larger unroll factor than the maximum loop length, or it would always just
13340   // execute the remainder loop.
13341   LoopHintAttr *UnrollHintAttr =
13342       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
13343                                    LoopHintAttr::Numeric, MakeFactorExpr());
13344   AttributedStmt *InnerUnrolled =
13345       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
13346 
13347   // Outer For init-statement: auto .unrolled.iv = 0
13348   AddInitializerToDecl(
13349       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13350       /*DirectInit=*/false);
13351   StmtResult OuterInit = new (Context)
13352       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13353   if (!OuterInit.isUsable())
13354     return StmtError();
13355 
13356   // Outer For cond-expression: .unrolled.iv < NumIterations
13357   ExprResult OuterConde =
13358       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
13359                  MakeNumIterations());
13360   if (!OuterConde.isUsable())
13361     return StmtError();
13362 
13363   // Outer For incr-statement: .unrolled.iv += Factor
13364   ExprResult OuterIncr =
13365       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
13366                  MakeOuterRef(), MakeFactorExpr());
13367   if (!OuterIncr.isUsable())
13368     return StmtError();
13369 
13370   // Outer For statement.
13371   ForStmt *OuterFor = new (Context)
13372       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
13373               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
13374               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13375 
13376   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13377                                     NumGeneratedLoops, OuterFor,
13378                                     buildPreInits(Context, PreInits));
13379 }
13380 
13381 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
13382                                              SourceLocation StartLoc,
13383                                              SourceLocation LParenLoc,
13384                                              SourceLocation EndLoc) {
13385   OMPClause *Res = nullptr;
13386   switch (Kind) {
13387   case OMPC_final:
13388     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
13389     break;
13390   case OMPC_num_threads:
13391     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
13392     break;
13393   case OMPC_safelen:
13394     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
13395     break;
13396   case OMPC_simdlen:
13397     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
13398     break;
13399   case OMPC_allocator:
13400     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
13401     break;
13402   case OMPC_collapse:
13403     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
13404     break;
13405   case OMPC_ordered:
13406     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
13407     break;
13408   case OMPC_num_teams:
13409     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
13410     break;
13411   case OMPC_thread_limit:
13412     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
13413     break;
13414   case OMPC_priority:
13415     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
13416     break;
13417   case OMPC_grainsize:
13418     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
13419     break;
13420   case OMPC_num_tasks:
13421     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
13422     break;
13423   case OMPC_hint:
13424     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
13425     break;
13426   case OMPC_depobj:
13427     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
13428     break;
13429   case OMPC_detach:
13430     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
13431     break;
13432   case OMPC_novariants:
13433     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
13434     break;
13435   case OMPC_nocontext:
13436     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
13437     break;
13438   case OMPC_filter:
13439     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
13440     break;
13441   case OMPC_partial:
13442     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
13443     break;
13444   case OMPC_align:
13445     Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
13446     break;
13447   case OMPC_device:
13448   case OMPC_if:
13449   case OMPC_default:
13450   case OMPC_proc_bind:
13451   case OMPC_schedule:
13452   case OMPC_private:
13453   case OMPC_firstprivate:
13454   case OMPC_lastprivate:
13455   case OMPC_shared:
13456   case OMPC_reduction:
13457   case OMPC_task_reduction:
13458   case OMPC_in_reduction:
13459   case OMPC_linear:
13460   case OMPC_aligned:
13461   case OMPC_copyin:
13462   case OMPC_copyprivate:
13463   case OMPC_nowait:
13464   case OMPC_untied:
13465   case OMPC_mergeable:
13466   case OMPC_threadprivate:
13467   case OMPC_sizes:
13468   case OMPC_allocate:
13469   case OMPC_flush:
13470   case OMPC_read:
13471   case OMPC_write:
13472   case OMPC_update:
13473   case OMPC_capture:
13474   case OMPC_seq_cst:
13475   case OMPC_acq_rel:
13476   case OMPC_acquire:
13477   case OMPC_release:
13478   case OMPC_relaxed:
13479   case OMPC_depend:
13480   case OMPC_threads:
13481   case OMPC_simd:
13482   case OMPC_map:
13483   case OMPC_nogroup:
13484   case OMPC_dist_schedule:
13485   case OMPC_defaultmap:
13486   case OMPC_unknown:
13487   case OMPC_uniform:
13488   case OMPC_to:
13489   case OMPC_from:
13490   case OMPC_use_device_ptr:
13491   case OMPC_use_device_addr:
13492   case OMPC_is_device_ptr:
13493   case OMPC_unified_address:
13494   case OMPC_unified_shared_memory:
13495   case OMPC_reverse_offload:
13496   case OMPC_dynamic_allocators:
13497   case OMPC_atomic_default_mem_order:
13498   case OMPC_device_type:
13499   case OMPC_match:
13500   case OMPC_nontemporal:
13501   case OMPC_order:
13502   case OMPC_destroy:
13503   case OMPC_inclusive:
13504   case OMPC_exclusive:
13505   case OMPC_uses_allocators:
13506   case OMPC_affinity:
13507   case OMPC_when:
13508   case OMPC_bind:
13509   default:
13510     llvm_unreachable("Clause is not allowed.");
13511   }
13512   return Res;
13513 }
13514 
13515 // An OpenMP directive such as 'target parallel' has two captured regions:
13516 // for the 'target' and 'parallel' respectively.  This function returns
13517 // the region in which to capture expressions associated with a clause.
13518 // A return value of OMPD_unknown signifies that the expression should not
13519 // be captured.
13520 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
13521     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
13522     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
13523   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13524   switch (CKind) {
13525   case OMPC_if:
13526     switch (DKind) {
13527     case OMPD_target_parallel_for_simd:
13528       if (OpenMPVersion >= 50 &&
13529           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13530         CaptureRegion = OMPD_parallel;
13531         break;
13532       }
13533       LLVM_FALLTHROUGH;
13534     case OMPD_target_parallel:
13535     case OMPD_target_parallel_for:
13536       // If this clause applies to the nested 'parallel' region, capture within
13537       // the 'target' region, otherwise do not capture.
13538       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13539         CaptureRegion = OMPD_target;
13540       break;
13541     case OMPD_target_teams_distribute_parallel_for_simd:
13542       if (OpenMPVersion >= 50 &&
13543           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13544         CaptureRegion = OMPD_parallel;
13545         break;
13546       }
13547       LLVM_FALLTHROUGH;
13548     case OMPD_target_teams_distribute_parallel_for:
13549       // If this clause applies to the nested 'parallel' region, capture within
13550       // the 'teams' region, otherwise do not capture.
13551       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13552         CaptureRegion = OMPD_teams;
13553       break;
13554     case OMPD_teams_distribute_parallel_for_simd:
13555       if (OpenMPVersion >= 50 &&
13556           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13557         CaptureRegion = OMPD_parallel;
13558         break;
13559       }
13560       LLVM_FALLTHROUGH;
13561     case OMPD_teams_distribute_parallel_for:
13562       CaptureRegion = OMPD_teams;
13563       break;
13564     case OMPD_target_update:
13565     case OMPD_target_enter_data:
13566     case OMPD_target_exit_data:
13567       CaptureRegion = OMPD_task;
13568       break;
13569     case OMPD_parallel_master_taskloop:
13570       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
13571         CaptureRegion = OMPD_parallel;
13572       break;
13573     case OMPD_parallel_master_taskloop_simd:
13574       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
13575           NameModifier == OMPD_taskloop) {
13576         CaptureRegion = OMPD_parallel;
13577         break;
13578       }
13579       if (OpenMPVersion <= 45)
13580         break;
13581       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13582         CaptureRegion = OMPD_taskloop;
13583       break;
13584     case OMPD_parallel_for_simd:
13585       if (OpenMPVersion <= 45)
13586         break;
13587       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13588         CaptureRegion = OMPD_parallel;
13589       break;
13590     case OMPD_taskloop_simd:
13591     case OMPD_master_taskloop_simd:
13592       if (OpenMPVersion <= 45)
13593         break;
13594       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13595         CaptureRegion = OMPD_taskloop;
13596       break;
13597     case OMPD_distribute_parallel_for_simd:
13598       if (OpenMPVersion <= 45)
13599         break;
13600       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13601         CaptureRegion = OMPD_parallel;
13602       break;
13603     case OMPD_target_simd:
13604       if (OpenMPVersion >= 50 &&
13605           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13606         CaptureRegion = OMPD_target;
13607       break;
13608     case OMPD_teams_distribute_simd:
13609     case OMPD_target_teams_distribute_simd:
13610       if (OpenMPVersion >= 50 &&
13611           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13612         CaptureRegion = OMPD_teams;
13613       break;
13614     case OMPD_cancel:
13615     case OMPD_parallel:
13616     case OMPD_parallel_master:
13617     case OMPD_parallel_sections:
13618     case OMPD_parallel_for:
13619     case OMPD_target:
13620     case OMPD_target_teams:
13621     case OMPD_target_teams_distribute:
13622     case OMPD_distribute_parallel_for:
13623     case OMPD_task:
13624     case OMPD_taskloop:
13625     case OMPD_master_taskloop:
13626     case OMPD_target_data:
13627     case OMPD_simd:
13628     case OMPD_for_simd:
13629     case OMPD_distribute_simd:
13630       // Do not capture if-clause expressions.
13631       break;
13632     case OMPD_threadprivate:
13633     case OMPD_allocate:
13634     case OMPD_taskyield:
13635     case OMPD_barrier:
13636     case OMPD_taskwait:
13637     case OMPD_cancellation_point:
13638     case OMPD_flush:
13639     case OMPD_depobj:
13640     case OMPD_scan:
13641     case OMPD_declare_reduction:
13642     case OMPD_declare_mapper:
13643     case OMPD_declare_simd:
13644     case OMPD_declare_variant:
13645     case OMPD_begin_declare_variant:
13646     case OMPD_end_declare_variant:
13647     case OMPD_declare_target:
13648     case OMPD_end_declare_target:
13649     case OMPD_loop:
13650     case OMPD_teams:
13651     case OMPD_tile:
13652     case OMPD_unroll:
13653     case OMPD_for:
13654     case OMPD_sections:
13655     case OMPD_section:
13656     case OMPD_single:
13657     case OMPD_master:
13658     case OMPD_masked:
13659     case OMPD_critical:
13660     case OMPD_taskgroup:
13661     case OMPD_distribute:
13662     case OMPD_ordered:
13663     case OMPD_atomic:
13664     case OMPD_teams_distribute:
13665     case OMPD_requires:
13666     case OMPD_metadirective:
13667       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13668     case OMPD_unknown:
13669     default:
13670       llvm_unreachable("Unknown OpenMP directive");
13671     }
13672     break;
13673   case OMPC_num_threads:
13674     switch (DKind) {
13675     case OMPD_target_parallel:
13676     case OMPD_target_parallel_for:
13677     case OMPD_target_parallel_for_simd:
13678       CaptureRegion = OMPD_target;
13679       break;
13680     case OMPD_teams_distribute_parallel_for:
13681     case OMPD_teams_distribute_parallel_for_simd:
13682     case OMPD_target_teams_distribute_parallel_for:
13683     case OMPD_target_teams_distribute_parallel_for_simd:
13684       CaptureRegion = OMPD_teams;
13685       break;
13686     case OMPD_parallel:
13687     case OMPD_parallel_master:
13688     case OMPD_parallel_sections:
13689     case OMPD_parallel_for:
13690     case OMPD_parallel_for_simd:
13691     case OMPD_distribute_parallel_for:
13692     case OMPD_distribute_parallel_for_simd:
13693     case OMPD_parallel_master_taskloop:
13694     case OMPD_parallel_master_taskloop_simd:
13695       // Do not capture num_threads-clause expressions.
13696       break;
13697     case OMPD_target_data:
13698     case OMPD_target_enter_data:
13699     case OMPD_target_exit_data:
13700     case OMPD_target_update:
13701     case OMPD_target:
13702     case OMPD_target_simd:
13703     case OMPD_target_teams:
13704     case OMPD_target_teams_distribute:
13705     case OMPD_target_teams_distribute_simd:
13706     case OMPD_cancel:
13707     case OMPD_task:
13708     case OMPD_taskloop:
13709     case OMPD_taskloop_simd:
13710     case OMPD_master_taskloop:
13711     case OMPD_master_taskloop_simd:
13712     case OMPD_threadprivate:
13713     case OMPD_allocate:
13714     case OMPD_taskyield:
13715     case OMPD_barrier:
13716     case OMPD_taskwait:
13717     case OMPD_cancellation_point:
13718     case OMPD_flush:
13719     case OMPD_depobj:
13720     case OMPD_scan:
13721     case OMPD_declare_reduction:
13722     case OMPD_declare_mapper:
13723     case OMPD_declare_simd:
13724     case OMPD_declare_variant:
13725     case OMPD_begin_declare_variant:
13726     case OMPD_end_declare_variant:
13727     case OMPD_declare_target:
13728     case OMPD_end_declare_target:
13729     case OMPD_loop:
13730     case OMPD_teams:
13731     case OMPD_simd:
13732     case OMPD_tile:
13733     case OMPD_unroll:
13734     case OMPD_for:
13735     case OMPD_for_simd:
13736     case OMPD_sections:
13737     case OMPD_section:
13738     case OMPD_single:
13739     case OMPD_master:
13740     case OMPD_masked:
13741     case OMPD_critical:
13742     case OMPD_taskgroup:
13743     case OMPD_distribute:
13744     case OMPD_ordered:
13745     case OMPD_atomic:
13746     case OMPD_distribute_simd:
13747     case OMPD_teams_distribute:
13748     case OMPD_teams_distribute_simd:
13749     case OMPD_requires:
13750     case OMPD_metadirective:
13751       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13752     case OMPD_unknown:
13753     default:
13754       llvm_unreachable("Unknown OpenMP directive");
13755     }
13756     break;
13757   case OMPC_num_teams:
13758     switch (DKind) {
13759     case OMPD_target_teams:
13760     case OMPD_target_teams_distribute:
13761     case OMPD_target_teams_distribute_simd:
13762     case OMPD_target_teams_distribute_parallel_for:
13763     case OMPD_target_teams_distribute_parallel_for_simd:
13764       CaptureRegion = OMPD_target;
13765       break;
13766     case OMPD_teams_distribute_parallel_for:
13767     case OMPD_teams_distribute_parallel_for_simd:
13768     case OMPD_teams:
13769     case OMPD_teams_distribute:
13770     case OMPD_teams_distribute_simd:
13771       // Do not capture num_teams-clause expressions.
13772       break;
13773     case OMPD_distribute_parallel_for:
13774     case OMPD_distribute_parallel_for_simd:
13775     case OMPD_task:
13776     case OMPD_taskloop:
13777     case OMPD_taskloop_simd:
13778     case OMPD_master_taskloop:
13779     case OMPD_master_taskloop_simd:
13780     case OMPD_parallel_master_taskloop:
13781     case OMPD_parallel_master_taskloop_simd:
13782     case OMPD_target_data:
13783     case OMPD_target_enter_data:
13784     case OMPD_target_exit_data:
13785     case OMPD_target_update:
13786     case OMPD_cancel:
13787     case OMPD_parallel:
13788     case OMPD_parallel_master:
13789     case OMPD_parallel_sections:
13790     case OMPD_parallel_for:
13791     case OMPD_parallel_for_simd:
13792     case OMPD_target:
13793     case OMPD_target_simd:
13794     case OMPD_target_parallel:
13795     case OMPD_target_parallel_for:
13796     case OMPD_target_parallel_for_simd:
13797     case OMPD_threadprivate:
13798     case OMPD_allocate:
13799     case OMPD_taskyield:
13800     case OMPD_barrier:
13801     case OMPD_taskwait:
13802     case OMPD_cancellation_point:
13803     case OMPD_flush:
13804     case OMPD_depobj:
13805     case OMPD_scan:
13806     case OMPD_declare_reduction:
13807     case OMPD_declare_mapper:
13808     case OMPD_declare_simd:
13809     case OMPD_declare_variant:
13810     case OMPD_begin_declare_variant:
13811     case OMPD_end_declare_variant:
13812     case OMPD_declare_target:
13813     case OMPD_end_declare_target:
13814     case OMPD_loop:
13815     case OMPD_simd:
13816     case OMPD_tile:
13817     case OMPD_unroll:
13818     case OMPD_for:
13819     case OMPD_for_simd:
13820     case OMPD_sections:
13821     case OMPD_section:
13822     case OMPD_single:
13823     case OMPD_master:
13824     case OMPD_masked:
13825     case OMPD_critical:
13826     case OMPD_taskgroup:
13827     case OMPD_distribute:
13828     case OMPD_ordered:
13829     case OMPD_atomic:
13830     case OMPD_distribute_simd:
13831     case OMPD_requires:
13832     case OMPD_metadirective:
13833       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13834     case OMPD_unknown:
13835     default:
13836       llvm_unreachable("Unknown OpenMP directive");
13837     }
13838     break;
13839   case OMPC_thread_limit:
13840     switch (DKind) {
13841     case OMPD_target_teams:
13842     case OMPD_target_teams_distribute:
13843     case OMPD_target_teams_distribute_simd:
13844     case OMPD_target_teams_distribute_parallel_for:
13845     case OMPD_target_teams_distribute_parallel_for_simd:
13846       CaptureRegion = OMPD_target;
13847       break;
13848     case OMPD_teams_distribute_parallel_for:
13849     case OMPD_teams_distribute_parallel_for_simd:
13850     case OMPD_teams:
13851     case OMPD_teams_distribute:
13852     case OMPD_teams_distribute_simd:
13853       // Do not capture thread_limit-clause expressions.
13854       break;
13855     case OMPD_distribute_parallel_for:
13856     case OMPD_distribute_parallel_for_simd:
13857     case OMPD_task:
13858     case OMPD_taskloop:
13859     case OMPD_taskloop_simd:
13860     case OMPD_master_taskloop:
13861     case OMPD_master_taskloop_simd:
13862     case OMPD_parallel_master_taskloop:
13863     case OMPD_parallel_master_taskloop_simd:
13864     case OMPD_target_data:
13865     case OMPD_target_enter_data:
13866     case OMPD_target_exit_data:
13867     case OMPD_target_update:
13868     case OMPD_cancel:
13869     case OMPD_parallel:
13870     case OMPD_parallel_master:
13871     case OMPD_parallel_sections:
13872     case OMPD_parallel_for:
13873     case OMPD_parallel_for_simd:
13874     case OMPD_target:
13875     case OMPD_target_simd:
13876     case OMPD_target_parallel:
13877     case OMPD_target_parallel_for:
13878     case OMPD_target_parallel_for_simd:
13879     case OMPD_threadprivate:
13880     case OMPD_allocate:
13881     case OMPD_taskyield:
13882     case OMPD_barrier:
13883     case OMPD_taskwait:
13884     case OMPD_cancellation_point:
13885     case OMPD_flush:
13886     case OMPD_depobj:
13887     case OMPD_scan:
13888     case OMPD_declare_reduction:
13889     case OMPD_declare_mapper:
13890     case OMPD_declare_simd:
13891     case OMPD_declare_variant:
13892     case OMPD_begin_declare_variant:
13893     case OMPD_end_declare_variant:
13894     case OMPD_declare_target:
13895     case OMPD_end_declare_target:
13896     case OMPD_loop:
13897     case OMPD_simd:
13898     case OMPD_tile:
13899     case OMPD_unroll:
13900     case OMPD_for:
13901     case OMPD_for_simd:
13902     case OMPD_sections:
13903     case OMPD_section:
13904     case OMPD_single:
13905     case OMPD_master:
13906     case OMPD_masked:
13907     case OMPD_critical:
13908     case OMPD_taskgroup:
13909     case OMPD_distribute:
13910     case OMPD_ordered:
13911     case OMPD_atomic:
13912     case OMPD_distribute_simd:
13913     case OMPD_requires:
13914     case OMPD_metadirective:
13915       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13916     case OMPD_unknown:
13917     default:
13918       llvm_unreachable("Unknown OpenMP directive");
13919     }
13920     break;
13921   case OMPC_schedule:
13922     switch (DKind) {
13923     case OMPD_parallel_for:
13924     case OMPD_parallel_for_simd:
13925     case OMPD_distribute_parallel_for:
13926     case OMPD_distribute_parallel_for_simd:
13927     case OMPD_teams_distribute_parallel_for:
13928     case OMPD_teams_distribute_parallel_for_simd:
13929     case OMPD_target_parallel_for:
13930     case OMPD_target_parallel_for_simd:
13931     case OMPD_target_teams_distribute_parallel_for:
13932     case OMPD_target_teams_distribute_parallel_for_simd:
13933       CaptureRegion = OMPD_parallel;
13934       break;
13935     case OMPD_for:
13936     case OMPD_for_simd:
13937       // Do not capture schedule-clause expressions.
13938       break;
13939     case OMPD_task:
13940     case OMPD_taskloop:
13941     case OMPD_taskloop_simd:
13942     case OMPD_master_taskloop:
13943     case OMPD_master_taskloop_simd:
13944     case OMPD_parallel_master_taskloop:
13945     case OMPD_parallel_master_taskloop_simd:
13946     case OMPD_target_data:
13947     case OMPD_target_enter_data:
13948     case OMPD_target_exit_data:
13949     case OMPD_target_update:
13950     case OMPD_teams:
13951     case OMPD_teams_distribute:
13952     case OMPD_teams_distribute_simd:
13953     case OMPD_target_teams_distribute:
13954     case OMPD_target_teams_distribute_simd:
13955     case OMPD_target:
13956     case OMPD_target_simd:
13957     case OMPD_target_parallel:
13958     case OMPD_cancel:
13959     case OMPD_parallel:
13960     case OMPD_parallel_master:
13961     case OMPD_parallel_sections:
13962     case OMPD_threadprivate:
13963     case OMPD_allocate:
13964     case OMPD_taskyield:
13965     case OMPD_barrier:
13966     case OMPD_taskwait:
13967     case OMPD_cancellation_point:
13968     case OMPD_flush:
13969     case OMPD_depobj:
13970     case OMPD_scan:
13971     case OMPD_declare_reduction:
13972     case OMPD_declare_mapper:
13973     case OMPD_declare_simd:
13974     case OMPD_declare_variant:
13975     case OMPD_begin_declare_variant:
13976     case OMPD_end_declare_variant:
13977     case OMPD_declare_target:
13978     case OMPD_end_declare_target:
13979     case OMPD_loop:
13980     case OMPD_simd:
13981     case OMPD_tile:
13982     case OMPD_unroll:
13983     case OMPD_sections:
13984     case OMPD_section:
13985     case OMPD_single:
13986     case OMPD_master:
13987     case OMPD_masked:
13988     case OMPD_critical:
13989     case OMPD_taskgroup:
13990     case OMPD_distribute:
13991     case OMPD_ordered:
13992     case OMPD_atomic:
13993     case OMPD_distribute_simd:
13994     case OMPD_target_teams:
13995     case OMPD_requires:
13996     case OMPD_metadirective:
13997       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13998     case OMPD_unknown:
13999     default:
14000       llvm_unreachable("Unknown OpenMP directive");
14001     }
14002     break;
14003   case OMPC_dist_schedule:
14004     switch (DKind) {
14005     case OMPD_teams_distribute_parallel_for:
14006     case OMPD_teams_distribute_parallel_for_simd:
14007     case OMPD_teams_distribute:
14008     case OMPD_teams_distribute_simd:
14009     case OMPD_target_teams_distribute_parallel_for:
14010     case OMPD_target_teams_distribute_parallel_for_simd:
14011     case OMPD_target_teams_distribute:
14012     case OMPD_target_teams_distribute_simd:
14013       CaptureRegion = OMPD_teams;
14014       break;
14015     case OMPD_distribute_parallel_for:
14016     case OMPD_distribute_parallel_for_simd:
14017     case OMPD_distribute:
14018     case OMPD_distribute_simd:
14019       // Do not capture dist_schedule-clause expressions.
14020       break;
14021     case OMPD_parallel_for:
14022     case OMPD_parallel_for_simd:
14023     case OMPD_target_parallel_for_simd:
14024     case OMPD_target_parallel_for:
14025     case OMPD_task:
14026     case OMPD_taskloop:
14027     case OMPD_taskloop_simd:
14028     case OMPD_master_taskloop:
14029     case OMPD_master_taskloop_simd:
14030     case OMPD_parallel_master_taskloop:
14031     case OMPD_parallel_master_taskloop_simd:
14032     case OMPD_target_data:
14033     case OMPD_target_enter_data:
14034     case OMPD_target_exit_data:
14035     case OMPD_target_update:
14036     case OMPD_teams:
14037     case OMPD_target:
14038     case OMPD_target_simd:
14039     case OMPD_target_parallel:
14040     case OMPD_cancel:
14041     case OMPD_parallel:
14042     case OMPD_parallel_master:
14043     case OMPD_parallel_sections:
14044     case OMPD_threadprivate:
14045     case OMPD_allocate:
14046     case OMPD_taskyield:
14047     case OMPD_barrier:
14048     case OMPD_taskwait:
14049     case OMPD_cancellation_point:
14050     case OMPD_flush:
14051     case OMPD_depobj:
14052     case OMPD_scan:
14053     case OMPD_declare_reduction:
14054     case OMPD_declare_mapper:
14055     case OMPD_declare_simd:
14056     case OMPD_declare_variant:
14057     case OMPD_begin_declare_variant:
14058     case OMPD_end_declare_variant:
14059     case OMPD_declare_target:
14060     case OMPD_end_declare_target:
14061     case OMPD_loop:
14062     case OMPD_simd:
14063     case OMPD_tile:
14064     case OMPD_unroll:
14065     case OMPD_for:
14066     case OMPD_for_simd:
14067     case OMPD_sections:
14068     case OMPD_section:
14069     case OMPD_single:
14070     case OMPD_master:
14071     case OMPD_masked:
14072     case OMPD_critical:
14073     case OMPD_taskgroup:
14074     case OMPD_ordered:
14075     case OMPD_atomic:
14076     case OMPD_target_teams:
14077     case OMPD_requires:
14078     case OMPD_metadirective:
14079       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
14080     case OMPD_unknown:
14081     default:
14082       llvm_unreachable("Unknown OpenMP directive");
14083     }
14084     break;
14085   case OMPC_device:
14086     switch (DKind) {
14087     case OMPD_target_update:
14088     case OMPD_target_enter_data:
14089     case OMPD_target_exit_data:
14090     case OMPD_target:
14091     case OMPD_target_simd:
14092     case OMPD_target_teams:
14093     case OMPD_target_parallel:
14094     case OMPD_target_teams_distribute:
14095     case OMPD_target_teams_distribute_simd:
14096     case OMPD_target_parallel_for:
14097     case OMPD_target_parallel_for_simd:
14098     case OMPD_target_teams_distribute_parallel_for:
14099     case OMPD_target_teams_distribute_parallel_for_simd:
14100     case OMPD_dispatch:
14101       CaptureRegion = OMPD_task;
14102       break;
14103     case OMPD_target_data:
14104     case OMPD_interop:
14105       // Do not capture device-clause expressions.
14106       break;
14107     case OMPD_teams_distribute_parallel_for:
14108     case OMPD_teams_distribute_parallel_for_simd:
14109     case OMPD_teams:
14110     case OMPD_teams_distribute:
14111     case OMPD_teams_distribute_simd:
14112     case OMPD_distribute_parallel_for:
14113     case OMPD_distribute_parallel_for_simd:
14114     case OMPD_task:
14115     case OMPD_taskloop:
14116     case OMPD_taskloop_simd:
14117     case OMPD_master_taskloop:
14118     case OMPD_master_taskloop_simd:
14119     case OMPD_parallel_master_taskloop:
14120     case OMPD_parallel_master_taskloop_simd:
14121     case OMPD_cancel:
14122     case OMPD_parallel:
14123     case OMPD_parallel_master:
14124     case OMPD_parallel_sections:
14125     case OMPD_parallel_for:
14126     case OMPD_parallel_for_simd:
14127     case OMPD_threadprivate:
14128     case OMPD_allocate:
14129     case OMPD_taskyield:
14130     case OMPD_barrier:
14131     case OMPD_taskwait:
14132     case OMPD_cancellation_point:
14133     case OMPD_flush:
14134     case OMPD_depobj:
14135     case OMPD_scan:
14136     case OMPD_declare_reduction:
14137     case OMPD_declare_mapper:
14138     case OMPD_declare_simd:
14139     case OMPD_declare_variant:
14140     case OMPD_begin_declare_variant:
14141     case OMPD_end_declare_variant:
14142     case OMPD_declare_target:
14143     case OMPD_end_declare_target:
14144     case OMPD_loop:
14145     case OMPD_simd:
14146     case OMPD_tile:
14147     case OMPD_unroll:
14148     case OMPD_for:
14149     case OMPD_for_simd:
14150     case OMPD_sections:
14151     case OMPD_section:
14152     case OMPD_single:
14153     case OMPD_master:
14154     case OMPD_masked:
14155     case OMPD_critical:
14156     case OMPD_taskgroup:
14157     case OMPD_distribute:
14158     case OMPD_ordered:
14159     case OMPD_atomic:
14160     case OMPD_distribute_simd:
14161     case OMPD_requires:
14162     case OMPD_metadirective:
14163       llvm_unreachable("Unexpected OpenMP directive with device-clause");
14164     case OMPD_unknown:
14165     default:
14166       llvm_unreachable("Unknown OpenMP directive");
14167     }
14168     break;
14169   case OMPC_grainsize:
14170   case OMPC_num_tasks:
14171   case OMPC_final:
14172   case OMPC_priority:
14173     switch (DKind) {
14174     case OMPD_task:
14175     case OMPD_taskloop:
14176     case OMPD_taskloop_simd:
14177     case OMPD_master_taskloop:
14178     case OMPD_master_taskloop_simd:
14179       break;
14180     case OMPD_parallel_master_taskloop:
14181     case OMPD_parallel_master_taskloop_simd:
14182       CaptureRegion = OMPD_parallel;
14183       break;
14184     case OMPD_target_update:
14185     case OMPD_target_enter_data:
14186     case OMPD_target_exit_data:
14187     case OMPD_target:
14188     case OMPD_target_simd:
14189     case OMPD_target_teams:
14190     case OMPD_target_parallel:
14191     case OMPD_target_teams_distribute:
14192     case OMPD_target_teams_distribute_simd:
14193     case OMPD_target_parallel_for:
14194     case OMPD_target_parallel_for_simd:
14195     case OMPD_target_teams_distribute_parallel_for:
14196     case OMPD_target_teams_distribute_parallel_for_simd:
14197     case OMPD_target_data:
14198     case OMPD_teams_distribute_parallel_for:
14199     case OMPD_teams_distribute_parallel_for_simd:
14200     case OMPD_teams:
14201     case OMPD_teams_distribute:
14202     case OMPD_teams_distribute_simd:
14203     case OMPD_distribute_parallel_for:
14204     case OMPD_distribute_parallel_for_simd:
14205     case OMPD_cancel:
14206     case OMPD_parallel:
14207     case OMPD_parallel_master:
14208     case OMPD_parallel_sections:
14209     case OMPD_parallel_for:
14210     case OMPD_parallel_for_simd:
14211     case OMPD_threadprivate:
14212     case OMPD_allocate:
14213     case OMPD_taskyield:
14214     case OMPD_barrier:
14215     case OMPD_taskwait:
14216     case OMPD_cancellation_point:
14217     case OMPD_flush:
14218     case OMPD_depobj:
14219     case OMPD_scan:
14220     case OMPD_declare_reduction:
14221     case OMPD_declare_mapper:
14222     case OMPD_declare_simd:
14223     case OMPD_declare_variant:
14224     case OMPD_begin_declare_variant:
14225     case OMPD_end_declare_variant:
14226     case OMPD_declare_target:
14227     case OMPD_end_declare_target:
14228     case OMPD_loop:
14229     case OMPD_simd:
14230     case OMPD_tile:
14231     case OMPD_unroll:
14232     case OMPD_for:
14233     case OMPD_for_simd:
14234     case OMPD_sections:
14235     case OMPD_section:
14236     case OMPD_single:
14237     case OMPD_master:
14238     case OMPD_masked:
14239     case OMPD_critical:
14240     case OMPD_taskgroup:
14241     case OMPD_distribute:
14242     case OMPD_ordered:
14243     case OMPD_atomic:
14244     case OMPD_distribute_simd:
14245     case OMPD_requires:
14246     case OMPD_metadirective:
14247       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
14248     case OMPD_unknown:
14249     default:
14250       llvm_unreachable("Unknown OpenMP directive");
14251     }
14252     break;
14253   case OMPC_novariants:
14254   case OMPC_nocontext:
14255     switch (DKind) {
14256     case OMPD_dispatch:
14257       CaptureRegion = OMPD_task;
14258       break;
14259     default:
14260       llvm_unreachable("Unexpected OpenMP directive");
14261     }
14262     break;
14263   case OMPC_filter:
14264     // Do not capture filter-clause expressions.
14265     break;
14266   case OMPC_when:
14267     if (DKind == OMPD_metadirective) {
14268       CaptureRegion = OMPD_metadirective;
14269     } else if (DKind == OMPD_unknown) {
14270       llvm_unreachable("Unknown OpenMP directive");
14271     } else {
14272       llvm_unreachable("Unexpected OpenMP directive with when clause");
14273     }
14274     break;
14275   case OMPC_firstprivate:
14276   case OMPC_lastprivate:
14277   case OMPC_reduction:
14278   case OMPC_task_reduction:
14279   case OMPC_in_reduction:
14280   case OMPC_linear:
14281   case OMPC_default:
14282   case OMPC_proc_bind:
14283   case OMPC_safelen:
14284   case OMPC_simdlen:
14285   case OMPC_sizes:
14286   case OMPC_allocator:
14287   case OMPC_collapse:
14288   case OMPC_private:
14289   case OMPC_shared:
14290   case OMPC_aligned:
14291   case OMPC_copyin:
14292   case OMPC_copyprivate:
14293   case OMPC_ordered:
14294   case OMPC_nowait:
14295   case OMPC_untied:
14296   case OMPC_mergeable:
14297   case OMPC_threadprivate:
14298   case OMPC_allocate:
14299   case OMPC_flush:
14300   case OMPC_depobj:
14301   case OMPC_read:
14302   case OMPC_write:
14303   case OMPC_update:
14304   case OMPC_capture:
14305   case OMPC_seq_cst:
14306   case OMPC_acq_rel:
14307   case OMPC_acquire:
14308   case OMPC_release:
14309   case OMPC_relaxed:
14310   case OMPC_depend:
14311   case OMPC_threads:
14312   case OMPC_simd:
14313   case OMPC_map:
14314   case OMPC_nogroup:
14315   case OMPC_hint:
14316   case OMPC_defaultmap:
14317   case OMPC_unknown:
14318   case OMPC_uniform:
14319   case OMPC_to:
14320   case OMPC_from:
14321   case OMPC_use_device_ptr:
14322   case OMPC_use_device_addr:
14323   case OMPC_is_device_ptr:
14324   case OMPC_unified_address:
14325   case OMPC_unified_shared_memory:
14326   case OMPC_reverse_offload:
14327   case OMPC_dynamic_allocators:
14328   case OMPC_atomic_default_mem_order:
14329   case OMPC_device_type:
14330   case OMPC_match:
14331   case OMPC_nontemporal:
14332   case OMPC_order:
14333   case OMPC_destroy:
14334   case OMPC_detach:
14335   case OMPC_inclusive:
14336   case OMPC_exclusive:
14337   case OMPC_uses_allocators:
14338   case OMPC_affinity:
14339   case OMPC_bind:
14340   default:
14341     llvm_unreachable("Unexpected OpenMP clause.");
14342   }
14343   return CaptureRegion;
14344 }
14345 
14346 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
14347                                      Expr *Condition, SourceLocation StartLoc,
14348                                      SourceLocation LParenLoc,
14349                                      SourceLocation NameModifierLoc,
14350                                      SourceLocation ColonLoc,
14351                                      SourceLocation EndLoc) {
14352   Expr *ValExpr = Condition;
14353   Stmt *HelperValStmt = nullptr;
14354   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14355   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14356       !Condition->isInstantiationDependent() &&
14357       !Condition->containsUnexpandedParameterPack()) {
14358     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14359     if (Val.isInvalid())
14360       return nullptr;
14361 
14362     ValExpr = Val.get();
14363 
14364     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14365     CaptureRegion = getOpenMPCaptureRegionForClause(
14366         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
14367     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14368       ValExpr = MakeFullExpr(ValExpr).get();
14369       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14370       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14371       HelperValStmt = buildPreInits(Context, Captures);
14372     }
14373   }
14374 
14375   return new (Context)
14376       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
14377                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
14378 }
14379 
14380 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
14381                                         SourceLocation StartLoc,
14382                                         SourceLocation LParenLoc,
14383                                         SourceLocation EndLoc) {
14384   Expr *ValExpr = Condition;
14385   Stmt *HelperValStmt = nullptr;
14386   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14387   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14388       !Condition->isInstantiationDependent() &&
14389       !Condition->containsUnexpandedParameterPack()) {
14390     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14391     if (Val.isInvalid())
14392       return nullptr;
14393 
14394     ValExpr = MakeFullExpr(Val.get()).get();
14395 
14396     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14397     CaptureRegion =
14398         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
14399     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14400       ValExpr = MakeFullExpr(ValExpr).get();
14401       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14402       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14403       HelperValStmt = buildPreInits(Context, Captures);
14404     }
14405   }
14406 
14407   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
14408                                       StartLoc, LParenLoc, EndLoc);
14409 }
14410 
14411 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
14412                                                         Expr *Op) {
14413   if (!Op)
14414     return ExprError();
14415 
14416   class IntConvertDiagnoser : public ICEConvertDiagnoser {
14417   public:
14418     IntConvertDiagnoser()
14419         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
14420     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14421                                          QualType T) override {
14422       return S.Diag(Loc, diag::err_omp_not_integral) << T;
14423     }
14424     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
14425                                              QualType T) override {
14426       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
14427     }
14428     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
14429                                                QualType T,
14430                                                QualType ConvTy) override {
14431       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
14432     }
14433     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
14434                                            QualType ConvTy) override {
14435       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14436              << ConvTy->isEnumeralType() << ConvTy;
14437     }
14438     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
14439                                             QualType T) override {
14440       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
14441     }
14442     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
14443                                         QualType ConvTy) override {
14444       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14445              << ConvTy->isEnumeralType() << ConvTy;
14446     }
14447     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
14448                                              QualType) override {
14449       llvm_unreachable("conversion functions are permitted");
14450     }
14451   } ConvertDiagnoser;
14452   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
14453 }
14454 
14455 static bool
14456 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
14457                           bool StrictlyPositive, bool BuildCapture = false,
14458                           OpenMPDirectiveKind DKind = OMPD_unknown,
14459                           OpenMPDirectiveKind *CaptureRegion = nullptr,
14460                           Stmt **HelperValStmt = nullptr) {
14461   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
14462       !ValExpr->isInstantiationDependent()) {
14463     SourceLocation Loc = ValExpr->getExprLoc();
14464     ExprResult Value =
14465         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
14466     if (Value.isInvalid())
14467       return false;
14468 
14469     ValExpr = Value.get();
14470     // The expression must evaluate to a non-negative integer value.
14471     if (Optional<llvm::APSInt> Result =
14472             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
14473       if (Result->isSigned() &&
14474           !((!StrictlyPositive && Result->isNonNegative()) ||
14475             (StrictlyPositive && Result->isStrictlyPositive()))) {
14476         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
14477             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14478             << ValExpr->getSourceRange();
14479         return false;
14480       }
14481     }
14482     if (!BuildCapture)
14483       return true;
14484     *CaptureRegion =
14485         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
14486     if (*CaptureRegion != OMPD_unknown &&
14487         !SemaRef.CurContext->isDependentContext()) {
14488       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
14489       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14490       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
14491       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
14492     }
14493   }
14494   return true;
14495 }
14496 
14497 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
14498                                              SourceLocation StartLoc,
14499                                              SourceLocation LParenLoc,
14500                                              SourceLocation EndLoc) {
14501   Expr *ValExpr = NumThreads;
14502   Stmt *HelperValStmt = nullptr;
14503 
14504   // OpenMP [2.5, Restrictions]
14505   //  The num_threads expression must evaluate to a positive integer value.
14506   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
14507                                  /*StrictlyPositive=*/true))
14508     return nullptr;
14509 
14510   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14511   OpenMPDirectiveKind CaptureRegion =
14512       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
14513   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14514     ValExpr = MakeFullExpr(ValExpr).get();
14515     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14516     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14517     HelperValStmt = buildPreInits(Context, Captures);
14518   }
14519 
14520   return new (Context) OMPNumThreadsClause(
14521       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14522 }
14523 
14524 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
14525                                                        OpenMPClauseKind CKind,
14526                                                        bool StrictlyPositive,
14527                                                        bool SuppressExprDiags) {
14528   if (!E)
14529     return ExprError();
14530   if (E->isValueDependent() || E->isTypeDependent() ||
14531       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14532     return E;
14533 
14534   llvm::APSInt Result;
14535   ExprResult ICE;
14536   if (SuppressExprDiags) {
14537     // Use a custom diagnoser that suppresses 'note' diagnostics about the
14538     // expression.
14539     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
14540       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
14541       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
14542                                                  SourceLocation Loc) override {
14543         llvm_unreachable("Diagnostic suppressed");
14544       }
14545     } Diagnoser;
14546     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
14547   } else {
14548     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
14549   }
14550   if (ICE.isInvalid())
14551     return ExprError();
14552 
14553   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
14554       (!StrictlyPositive && !Result.isNonNegative())) {
14555     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
14556         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14557         << E->getSourceRange();
14558     return ExprError();
14559   }
14560   if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
14561     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
14562         << E->getSourceRange();
14563     return ExprError();
14564   }
14565   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
14566     DSAStack->setAssociatedLoops(Result.getExtValue());
14567   else if (CKind == OMPC_ordered)
14568     DSAStack->setAssociatedLoops(Result.getExtValue());
14569   return ICE;
14570 }
14571 
14572 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
14573                                           SourceLocation LParenLoc,
14574                                           SourceLocation EndLoc) {
14575   // OpenMP [2.8.1, simd construct, Description]
14576   // The parameter of the safelen clause must be a constant
14577   // positive integer expression.
14578   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
14579   if (Safelen.isInvalid())
14580     return nullptr;
14581   return new (Context)
14582       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
14583 }
14584 
14585 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
14586                                           SourceLocation LParenLoc,
14587                                           SourceLocation EndLoc) {
14588   // OpenMP [2.8.1, simd construct, Description]
14589   // The parameter of the simdlen clause must be a constant
14590   // positive integer expression.
14591   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
14592   if (Simdlen.isInvalid())
14593     return nullptr;
14594   return new (Context)
14595       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
14596 }
14597 
14598 /// Tries to find omp_allocator_handle_t type.
14599 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
14600                                     DSAStackTy *Stack) {
14601   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
14602   if (!OMPAllocatorHandleT.isNull())
14603     return true;
14604   // Build the predefined allocator expressions.
14605   bool ErrorFound = false;
14606   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
14607     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
14608     StringRef Allocator =
14609         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
14610     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
14611     auto *VD = dyn_cast_or_null<ValueDecl>(
14612         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
14613     if (!VD) {
14614       ErrorFound = true;
14615       break;
14616     }
14617     QualType AllocatorType =
14618         VD->getType().getNonLValueExprType(S.getASTContext());
14619     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
14620     if (!Res.isUsable()) {
14621       ErrorFound = true;
14622       break;
14623     }
14624     if (OMPAllocatorHandleT.isNull())
14625       OMPAllocatorHandleT = AllocatorType;
14626     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
14627       ErrorFound = true;
14628       break;
14629     }
14630     Stack->setAllocator(AllocatorKind, Res.get());
14631   }
14632   if (ErrorFound) {
14633     S.Diag(Loc, diag::err_omp_implied_type_not_found)
14634         << "omp_allocator_handle_t";
14635     return false;
14636   }
14637   OMPAllocatorHandleT.addConst();
14638   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
14639   return true;
14640 }
14641 
14642 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
14643                                             SourceLocation LParenLoc,
14644                                             SourceLocation EndLoc) {
14645   // OpenMP [2.11.3, allocate Directive, Description]
14646   // allocator is an expression of omp_allocator_handle_t type.
14647   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
14648     return nullptr;
14649 
14650   ExprResult Allocator = DefaultLvalueConversion(A);
14651   if (Allocator.isInvalid())
14652     return nullptr;
14653   Allocator = PerformImplicitConversion(Allocator.get(),
14654                                         DSAStack->getOMPAllocatorHandleT(),
14655                                         Sema::AA_Initializing,
14656                                         /*AllowExplicit=*/true);
14657   if (Allocator.isInvalid())
14658     return nullptr;
14659   return new (Context)
14660       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
14661 }
14662 
14663 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
14664                                            SourceLocation StartLoc,
14665                                            SourceLocation LParenLoc,
14666                                            SourceLocation EndLoc) {
14667   // OpenMP [2.7.1, loop construct, Description]
14668   // OpenMP [2.8.1, simd construct, Description]
14669   // OpenMP [2.9.6, distribute construct, Description]
14670   // The parameter of the collapse clause must be a constant
14671   // positive integer expression.
14672   ExprResult NumForLoopsResult =
14673       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
14674   if (NumForLoopsResult.isInvalid())
14675     return nullptr;
14676   return new (Context)
14677       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
14678 }
14679 
14680 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
14681                                           SourceLocation EndLoc,
14682                                           SourceLocation LParenLoc,
14683                                           Expr *NumForLoops) {
14684   // OpenMP [2.7.1, loop construct, Description]
14685   // OpenMP [2.8.1, simd construct, Description]
14686   // OpenMP [2.9.6, distribute construct, Description]
14687   // The parameter of the ordered clause must be a constant
14688   // positive integer expression if any.
14689   if (NumForLoops && LParenLoc.isValid()) {
14690     ExprResult NumForLoopsResult =
14691         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
14692     if (NumForLoopsResult.isInvalid())
14693       return nullptr;
14694     NumForLoops = NumForLoopsResult.get();
14695   } else {
14696     NumForLoops = nullptr;
14697   }
14698   auto *Clause = OMPOrderedClause::Create(
14699       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
14700       StartLoc, LParenLoc, EndLoc);
14701   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
14702   return Clause;
14703 }
14704 
14705 OMPClause *Sema::ActOnOpenMPSimpleClause(
14706     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
14707     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14708   OMPClause *Res = nullptr;
14709   switch (Kind) {
14710   case OMPC_default:
14711     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
14712                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14713     break;
14714   case OMPC_proc_bind:
14715     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14716                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14717     break;
14718   case OMPC_atomic_default_mem_order:
14719     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14720         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14721         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14722     break;
14723   case OMPC_order:
14724     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14725                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14726     break;
14727   case OMPC_update:
14728     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14729                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14730     break;
14731   case OMPC_bind:
14732     Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
14733                                 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14734     break;
14735   case OMPC_if:
14736   case OMPC_final:
14737   case OMPC_num_threads:
14738   case OMPC_safelen:
14739   case OMPC_simdlen:
14740   case OMPC_sizes:
14741   case OMPC_allocator:
14742   case OMPC_collapse:
14743   case OMPC_schedule:
14744   case OMPC_private:
14745   case OMPC_firstprivate:
14746   case OMPC_lastprivate:
14747   case OMPC_shared:
14748   case OMPC_reduction:
14749   case OMPC_task_reduction:
14750   case OMPC_in_reduction:
14751   case OMPC_linear:
14752   case OMPC_aligned:
14753   case OMPC_copyin:
14754   case OMPC_copyprivate:
14755   case OMPC_ordered:
14756   case OMPC_nowait:
14757   case OMPC_untied:
14758   case OMPC_mergeable:
14759   case OMPC_threadprivate:
14760   case OMPC_allocate:
14761   case OMPC_flush:
14762   case OMPC_depobj:
14763   case OMPC_read:
14764   case OMPC_write:
14765   case OMPC_capture:
14766   case OMPC_seq_cst:
14767   case OMPC_acq_rel:
14768   case OMPC_acquire:
14769   case OMPC_release:
14770   case OMPC_relaxed:
14771   case OMPC_depend:
14772   case OMPC_device:
14773   case OMPC_threads:
14774   case OMPC_simd:
14775   case OMPC_map:
14776   case OMPC_num_teams:
14777   case OMPC_thread_limit:
14778   case OMPC_priority:
14779   case OMPC_grainsize:
14780   case OMPC_nogroup:
14781   case OMPC_num_tasks:
14782   case OMPC_hint:
14783   case OMPC_dist_schedule:
14784   case OMPC_defaultmap:
14785   case OMPC_unknown:
14786   case OMPC_uniform:
14787   case OMPC_to:
14788   case OMPC_from:
14789   case OMPC_use_device_ptr:
14790   case OMPC_use_device_addr:
14791   case OMPC_is_device_ptr:
14792   case OMPC_unified_address:
14793   case OMPC_unified_shared_memory:
14794   case OMPC_reverse_offload:
14795   case OMPC_dynamic_allocators:
14796   case OMPC_device_type:
14797   case OMPC_match:
14798   case OMPC_nontemporal:
14799   case OMPC_destroy:
14800   case OMPC_novariants:
14801   case OMPC_nocontext:
14802   case OMPC_detach:
14803   case OMPC_inclusive:
14804   case OMPC_exclusive:
14805   case OMPC_uses_allocators:
14806   case OMPC_affinity:
14807   case OMPC_when:
14808   default:
14809     llvm_unreachable("Clause is not allowed.");
14810   }
14811   return Res;
14812 }
14813 
14814 static std::string
14815 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14816                         ArrayRef<unsigned> Exclude = llvm::None) {
14817   SmallString<256> Buffer;
14818   llvm::raw_svector_ostream Out(Buffer);
14819   unsigned Skipped = Exclude.size();
14820   auto S = Exclude.begin(), E = Exclude.end();
14821   for (unsigned I = First; I < Last; ++I) {
14822     if (std::find(S, E, I) != E) {
14823       --Skipped;
14824       continue;
14825     }
14826     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14827     if (I + Skipped + 2 == Last)
14828       Out << " or ";
14829     else if (I + Skipped + 1 != Last)
14830       Out << ", ";
14831   }
14832   return std::string(Out.str());
14833 }
14834 
14835 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14836                                           SourceLocation KindKwLoc,
14837                                           SourceLocation StartLoc,
14838                                           SourceLocation LParenLoc,
14839                                           SourceLocation EndLoc) {
14840   if (Kind == OMP_DEFAULT_unknown) {
14841     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14842         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14843                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14844         << getOpenMPClauseName(OMPC_default);
14845     return nullptr;
14846   }
14847 
14848   switch (Kind) {
14849   case OMP_DEFAULT_none:
14850     DSAStack->setDefaultDSANone(KindKwLoc);
14851     break;
14852   case OMP_DEFAULT_shared:
14853     DSAStack->setDefaultDSAShared(KindKwLoc);
14854     break;
14855   case OMP_DEFAULT_firstprivate:
14856     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14857     break;
14858   default:
14859     llvm_unreachable("DSA unexpected in OpenMP default clause");
14860   }
14861 
14862   return new (Context)
14863       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14864 }
14865 
14866 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14867                                            SourceLocation KindKwLoc,
14868                                            SourceLocation StartLoc,
14869                                            SourceLocation LParenLoc,
14870                                            SourceLocation EndLoc) {
14871   if (Kind == OMP_PROC_BIND_unknown) {
14872     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14873         << getListOfPossibleValues(OMPC_proc_bind,
14874                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14875                                    /*Last=*/
14876                                    unsigned(LangOpts.OpenMP > 50
14877                                                 ? OMP_PROC_BIND_primary
14878                                                 : OMP_PROC_BIND_spread) +
14879                                        1)
14880         << getOpenMPClauseName(OMPC_proc_bind);
14881     return nullptr;
14882   }
14883   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14884     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14885         << getListOfPossibleValues(OMPC_proc_bind,
14886                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14887                                    /*Last=*/
14888                                    unsigned(OMP_PROC_BIND_spread) + 1)
14889         << getOpenMPClauseName(OMPC_proc_bind);
14890   return new (Context)
14891       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14892 }
14893 
14894 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14895     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14896     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14897   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14898     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14899         << getListOfPossibleValues(
14900                OMPC_atomic_default_mem_order, /*First=*/0,
14901                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14902         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14903     return nullptr;
14904   }
14905   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14906                                                       LParenLoc, EndLoc);
14907 }
14908 
14909 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14910                                         SourceLocation KindKwLoc,
14911                                         SourceLocation StartLoc,
14912                                         SourceLocation LParenLoc,
14913                                         SourceLocation EndLoc) {
14914   if (Kind == OMPC_ORDER_unknown) {
14915     static_assert(OMPC_ORDER_unknown > 0,
14916                   "OMPC_ORDER_unknown not greater than 0");
14917     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14918         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14919                                    /*Last=*/OMPC_ORDER_unknown)
14920         << getOpenMPClauseName(OMPC_order);
14921     return nullptr;
14922   }
14923   return new (Context)
14924       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14925 }
14926 
14927 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14928                                          SourceLocation KindKwLoc,
14929                                          SourceLocation StartLoc,
14930                                          SourceLocation LParenLoc,
14931                                          SourceLocation EndLoc) {
14932   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14933       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14934     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14935                          OMPC_DEPEND_depobj};
14936     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14937         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14938                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14939         << getOpenMPClauseName(OMPC_update);
14940     return nullptr;
14941   }
14942   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14943                                  EndLoc);
14944 }
14945 
14946 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14947                                         SourceLocation StartLoc,
14948                                         SourceLocation LParenLoc,
14949                                         SourceLocation EndLoc) {
14950   for (Expr *SizeExpr : SizeExprs) {
14951     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14952         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14953     if (!NumForLoopsResult.isUsable())
14954       return nullptr;
14955   }
14956 
14957   DSAStack->setAssociatedLoops(SizeExprs.size());
14958   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14959                                 SizeExprs);
14960 }
14961 
14962 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
14963                                        SourceLocation EndLoc) {
14964   return OMPFullClause::Create(Context, StartLoc, EndLoc);
14965 }
14966 
14967 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
14968                                           SourceLocation StartLoc,
14969                                           SourceLocation LParenLoc,
14970                                           SourceLocation EndLoc) {
14971   if (FactorExpr) {
14972     // If an argument is specified, it must be a constant (or an unevaluated
14973     // template expression).
14974     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
14975         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
14976     if (FactorResult.isInvalid())
14977       return nullptr;
14978     FactorExpr = FactorResult.get();
14979   }
14980 
14981   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14982                                   FactorExpr);
14983 }
14984 
14985 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
14986                                         SourceLocation LParenLoc,
14987                                         SourceLocation EndLoc) {
14988   ExprResult AlignVal;
14989   AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
14990   if (AlignVal.isInvalid())
14991     return nullptr;
14992   return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
14993                                 EndLoc);
14994 }
14995 
14996 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14997     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14998     SourceLocation StartLoc, SourceLocation LParenLoc,
14999     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
15000     SourceLocation EndLoc) {
15001   OMPClause *Res = nullptr;
15002   switch (Kind) {
15003   case OMPC_schedule:
15004     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
15005     assert(Argument.size() == NumberOfElements &&
15006            ArgumentLoc.size() == NumberOfElements);
15007     Res = ActOnOpenMPScheduleClause(
15008         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
15009         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
15010         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
15011         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
15012         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
15013     break;
15014   case OMPC_if:
15015     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15016     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
15017                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
15018                               DelimLoc, EndLoc);
15019     break;
15020   case OMPC_dist_schedule:
15021     Res = ActOnOpenMPDistScheduleClause(
15022         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
15023         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
15024     break;
15025   case OMPC_defaultmap:
15026     enum { Modifier, DefaultmapKind };
15027     Res = ActOnOpenMPDefaultmapClause(
15028         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
15029         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
15030         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
15031         EndLoc);
15032     break;
15033   case OMPC_device:
15034     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15035     Res = ActOnOpenMPDeviceClause(
15036         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
15037         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
15038     break;
15039   case OMPC_final:
15040   case OMPC_num_threads:
15041   case OMPC_safelen:
15042   case OMPC_simdlen:
15043   case OMPC_sizes:
15044   case OMPC_allocator:
15045   case OMPC_collapse:
15046   case OMPC_default:
15047   case OMPC_proc_bind:
15048   case OMPC_private:
15049   case OMPC_firstprivate:
15050   case OMPC_lastprivate:
15051   case OMPC_shared:
15052   case OMPC_reduction:
15053   case OMPC_task_reduction:
15054   case OMPC_in_reduction:
15055   case OMPC_linear:
15056   case OMPC_aligned:
15057   case OMPC_copyin:
15058   case OMPC_copyprivate:
15059   case OMPC_ordered:
15060   case OMPC_nowait:
15061   case OMPC_untied:
15062   case OMPC_mergeable:
15063   case OMPC_threadprivate:
15064   case OMPC_allocate:
15065   case OMPC_flush:
15066   case OMPC_depobj:
15067   case OMPC_read:
15068   case OMPC_write:
15069   case OMPC_update:
15070   case OMPC_capture:
15071   case OMPC_seq_cst:
15072   case OMPC_acq_rel:
15073   case OMPC_acquire:
15074   case OMPC_release:
15075   case OMPC_relaxed:
15076   case OMPC_depend:
15077   case OMPC_threads:
15078   case OMPC_simd:
15079   case OMPC_map:
15080   case OMPC_num_teams:
15081   case OMPC_thread_limit:
15082   case OMPC_priority:
15083   case OMPC_grainsize:
15084   case OMPC_nogroup:
15085   case OMPC_num_tasks:
15086   case OMPC_hint:
15087   case OMPC_unknown:
15088   case OMPC_uniform:
15089   case OMPC_to:
15090   case OMPC_from:
15091   case OMPC_use_device_ptr:
15092   case OMPC_use_device_addr:
15093   case OMPC_is_device_ptr:
15094   case OMPC_unified_address:
15095   case OMPC_unified_shared_memory:
15096   case OMPC_reverse_offload:
15097   case OMPC_dynamic_allocators:
15098   case OMPC_atomic_default_mem_order:
15099   case OMPC_device_type:
15100   case OMPC_match:
15101   case OMPC_nontemporal:
15102   case OMPC_order:
15103   case OMPC_destroy:
15104   case OMPC_novariants:
15105   case OMPC_nocontext:
15106   case OMPC_detach:
15107   case OMPC_inclusive:
15108   case OMPC_exclusive:
15109   case OMPC_uses_allocators:
15110   case OMPC_affinity:
15111   case OMPC_when:
15112   case OMPC_bind:
15113   default:
15114     llvm_unreachable("Clause is not allowed.");
15115   }
15116   return Res;
15117 }
15118 
15119 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
15120                                    OpenMPScheduleClauseModifier M2,
15121                                    SourceLocation M1Loc, SourceLocation M2Loc) {
15122   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
15123     SmallVector<unsigned, 2> Excluded;
15124     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
15125       Excluded.push_back(M2);
15126     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
15127       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
15128     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
15129       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
15130     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
15131         << getListOfPossibleValues(OMPC_schedule,
15132                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
15133                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15134                                    Excluded)
15135         << getOpenMPClauseName(OMPC_schedule);
15136     return true;
15137   }
15138   return false;
15139 }
15140 
15141 OMPClause *Sema::ActOnOpenMPScheduleClause(
15142     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
15143     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15144     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
15145     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
15146   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
15147       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
15148     return nullptr;
15149   // OpenMP, 2.7.1, Loop Construct, Restrictions
15150   // Either the monotonic modifier or the nonmonotonic modifier can be specified
15151   // but not both.
15152   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
15153       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
15154        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
15155       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
15156        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
15157     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
15158         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
15159         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
15160     return nullptr;
15161   }
15162   if (Kind == OMPC_SCHEDULE_unknown) {
15163     std::string Values;
15164     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
15165       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
15166       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15167                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15168                                        Exclude);
15169     } else {
15170       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15171                                        /*Last=*/OMPC_SCHEDULE_unknown);
15172     }
15173     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15174         << Values << getOpenMPClauseName(OMPC_schedule);
15175     return nullptr;
15176   }
15177   // OpenMP, 2.7.1, Loop Construct, Restrictions
15178   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
15179   // schedule(guided).
15180   // OpenMP 5.0 does not have this restriction.
15181   if (LangOpts.OpenMP < 50 &&
15182       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
15183        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
15184       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
15185     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
15186          diag::err_omp_schedule_nonmonotonic_static);
15187     return nullptr;
15188   }
15189   Expr *ValExpr = ChunkSize;
15190   Stmt *HelperValStmt = nullptr;
15191   if (ChunkSize) {
15192     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15193         !ChunkSize->isInstantiationDependent() &&
15194         !ChunkSize->containsUnexpandedParameterPack()) {
15195       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
15196       ExprResult Val =
15197           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
15198       if (Val.isInvalid())
15199         return nullptr;
15200 
15201       ValExpr = Val.get();
15202 
15203       // OpenMP [2.7.1, Restrictions]
15204       //  chunk_size must be a loop invariant integer expression with a positive
15205       //  value.
15206       if (Optional<llvm::APSInt> Result =
15207               ValExpr->getIntegerConstantExpr(Context)) {
15208         if (Result->isSigned() && !Result->isStrictlyPositive()) {
15209           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
15210               << "schedule" << 1 << ChunkSize->getSourceRange();
15211           return nullptr;
15212         }
15213       } else if (getOpenMPCaptureRegionForClause(
15214                      DSAStack->getCurrentDirective(), OMPC_schedule,
15215                      LangOpts.OpenMP) != OMPD_unknown &&
15216                  !CurContext->isDependentContext()) {
15217         ValExpr = MakeFullExpr(ValExpr).get();
15218         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15219         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15220         HelperValStmt = buildPreInits(Context, Captures);
15221       }
15222     }
15223   }
15224 
15225   return new (Context)
15226       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
15227                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
15228 }
15229 
15230 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
15231                                    SourceLocation StartLoc,
15232                                    SourceLocation EndLoc) {
15233   OMPClause *Res = nullptr;
15234   switch (Kind) {
15235   case OMPC_ordered:
15236     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
15237     break;
15238   case OMPC_nowait:
15239     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
15240     break;
15241   case OMPC_untied:
15242     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
15243     break;
15244   case OMPC_mergeable:
15245     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
15246     break;
15247   case OMPC_read:
15248     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
15249     break;
15250   case OMPC_write:
15251     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
15252     break;
15253   case OMPC_update:
15254     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
15255     break;
15256   case OMPC_capture:
15257     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
15258     break;
15259   case OMPC_seq_cst:
15260     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
15261     break;
15262   case OMPC_acq_rel:
15263     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
15264     break;
15265   case OMPC_acquire:
15266     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
15267     break;
15268   case OMPC_release:
15269     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
15270     break;
15271   case OMPC_relaxed:
15272     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
15273     break;
15274   case OMPC_threads:
15275     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
15276     break;
15277   case OMPC_simd:
15278     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
15279     break;
15280   case OMPC_nogroup:
15281     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
15282     break;
15283   case OMPC_unified_address:
15284     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
15285     break;
15286   case OMPC_unified_shared_memory:
15287     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15288     break;
15289   case OMPC_reverse_offload:
15290     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
15291     break;
15292   case OMPC_dynamic_allocators:
15293     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
15294     break;
15295   case OMPC_destroy:
15296     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
15297                                    /*LParenLoc=*/SourceLocation(),
15298                                    /*VarLoc=*/SourceLocation(), EndLoc);
15299     break;
15300   case OMPC_full:
15301     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
15302     break;
15303   case OMPC_partial:
15304     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
15305     break;
15306   case OMPC_if:
15307   case OMPC_final:
15308   case OMPC_num_threads:
15309   case OMPC_safelen:
15310   case OMPC_simdlen:
15311   case OMPC_sizes:
15312   case OMPC_allocator:
15313   case OMPC_collapse:
15314   case OMPC_schedule:
15315   case OMPC_private:
15316   case OMPC_firstprivate:
15317   case OMPC_lastprivate:
15318   case OMPC_shared:
15319   case OMPC_reduction:
15320   case OMPC_task_reduction:
15321   case OMPC_in_reduction:
15322   case OMPC_linear:
15323   case OMPC_aligned:
15324   case OMPC_copyin:
15325   case OMPC_copyprivate:
15326   case OMPC_default:
15327   case OMPC_proc_bind:
15328   case OMPC_threadprivate:
15329   case OMPC_allocate:
15330   case OMPC_flush:
15331   case OMPC_depobj:
15332   case OMPC_depend:
15333   case OMPC_device:
15334   case OMPC_map:
15335   case OMPC_num_teams:
15336   case OMPC_thread_limit:
15337   case OMPC_priority:
15338   case OMPC_grainsize:
15339   case OMPC_num_tasks:
15340   case OMPC_hint:
15341   case OMPC_dist_schedule:
15342   case OMPC_defaultmap:
15343   case OMPC_unknown:
15344   case OMPC_uniform:
15345   case OMPC_to:
15346   case OMPC_from:
15347   case OMPC_use_device_ptr:
15348   case OMPC_use_device_addr:
15349   case OMPC_is_device_ptr:
15350   case OMPC_atomic_default_mem_order:
15351   case OMPC_device_type:
15352   case OMPC_match:
15353   case OMPC_nontemporal:
15354   case OMPC_order:
15355   case OMPC_novariants:
15356   case OMPC_nocontext:
15357   case OMPC_detach:
15358   case OMPC_inclusive:
15359   case OMPC_exclusive:
15360   case OMPC_uses_allocators:
15361   case OMPC_affinity:
15362   case OMPC_when:
15363   default:
15364     llvm_unreachable("Clause is not allowed.");
15365   }
15366   return Res;
15367 }
15368 
15369 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
15370                                          SourceLocation EndLoc) {
15371   DSAStack->setNowaitRegion();
15372   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
15373 }
15374 
15375 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
15376                                          SourceLocation EndLoc) {
15377   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
15378 }
15379 
15380 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
15381                                             SourceLocation EndLoc) {
15382   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
15383 }
15384 
15385 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
15386                                        SourceLocation EndLoc) {
15387   return new (Context) OMPReadClause(StartLoc, EndLoc);
15388 }
15389 
15390 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
15391                                         SourceLocation EndLoc) {
15392   return new (Context) OMPWriteClause(StartLoc, EndLoc);
15393 }
15394 
15395 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
15396                                          SourceLocation EndLoc) {
15397   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
15398 }
15399 
15400 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
15401                                           SourceLocation EndLoc) {
15402   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
15403 }
15404 
15405 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
15406                                          SourceLocation EndLoc) {
15407   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
15408 }
15409 
15410 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
15411                                          SourceLocation EndLoc) {
15412   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
15413 }
15414 
15415 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
15416                                           SourceLocation EndLoc) {
15417   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
15418 }
15419 
15420 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
15421                                           SourceLocation EndLoc) {
15422   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
15423 }
15424 
15425 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
15426                                           SourceLocation EndLoc) {
15427   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
15428 }
15429 
15430 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
15431                                           SourceLocation EndLoc) {
15432   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
15433 }
15434 
15435 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
15436                                        SourceLocation EndLoc) {
15437   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
15438 }
15439 
15440 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
15441                                           SourceLocation EndLoc) {
15442   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
15443 }
15444 
15445 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
15446                                                  SourceLocation EndLoc) {
15447   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
15448 }
15449 
15450 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
15451                                                       SourceLocation EndLoc) {
15452   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15453 }
15454 
15455 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
15456                                                  SourceLocation EndLoc) {
15457   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
15458 }
15459 
15460 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
15461                                                     SourceLocation EndLoc) {
15462   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
15463 }
15464 
15465 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
15466                                              SourceLocation StartLoc,
15467                                              SourceLocation EndLoc) {
15468 
15469   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15470   // At least one action-clause must appear on a directive.
15471   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
15472     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
15473     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
15474         << Expected << getOpenMPDirectiveName(OMPD_interop);
15475     return StmtError();
15476   }
15477 
15478   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15479   // A depend clause can only appear on the directive if a targetsync
15480   // interop-type is present or the interop-var was initialized with
15481   // the targetsync interop-type.
15482 
15483   // If there is any 'init' clause diagnose if there is no 'init' clause with
15484   // interop-type of 'targetsync'. Cases involving other directives cannot be
15485   // diagnosed.
15486   const OMPDependClause *DependClause = nullptr;
15487   bool HasInitClause = false;
15488   bool IsTargetSync = false;
15489   for (const OMPClause *C : Clauses) {
15490     if (IsTargetSync)
15491       break;
15492     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
15493       HasInitClause = true;
15494       if (InitClause->getIsTargetSync())
15495         IsTargetSync = true;
15496     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
15497       DependClause = DC;
15498     }
15499   }
15500   if (DependClause && HasInitClause && !IsTargetSync) {
15501     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
15502     return StmtError();
15503   }
15504 
15505   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15506   // Each interop-var may be specified for at most one action-clause of each
15507   // interop construct.
15508   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
15509   for (const OMPClause *C : Clauses) {
15510     OpenMPClauseKind ClauseKind = C->getClauseKind();
15511     const DeclRefExpr *DRE = nullptr;
15512     SourceLocation VarLoc;
15513 
15514     if (ClauseKind == OMPC_init) {
15515       const auto *IC = cast<OMPInitClause>(C);
15516       VarLoc = IC->getVarLoc();
15517       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
15518     } else if (ClauseKind == OMPC_use) {
15519       const auto *UC = cast<OMPUseClause>(C);
15520       VarLoc = UC->getVarLoc();
15521       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
15522     } else if (ClauseKind == OMPC_destroy) {
15523       const auto *DC = cast<OMPDestroyClause>(C);
15524       VarLoc = DC->getVarLoc();
15525       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
15526     }
15527 
15528     if (!DRE)
15529       continue;
15530 
15531     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
15532       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
15533         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
15534         return StmtError();
15535       }
15536     }
15537   }
15538 
15539   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
15540 }
15541 
15542 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
15543                                    SourceLocation VarLoc,
15544                                    OpenMPClauseKind Kind) {
15545   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
15546       InteropVarExpr->isInstantiationDependent() ||
15547       InteropVarExpr->containsUnexpandedParameterPack())
15548     return true;
15549 
15550   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
15551   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
15552     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
15553     return false;
15554   }
15555 
15556   // Interop variable should be of type omp_interop_t.
15557   bool HasError = false;
15558   QualType InteropType;
15559   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
15560                       VarLoc, Sema::LookupOrdinaryName);
15561   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
15562     NamedDecl *ND = Result.getFoundDecl();
15563     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
15564       InteropType = QualType(TD->getTypeForDecl(), 0);
15565     } else {
15566       HasError = true;
15567     }
15568   } else {
15569     HasError = true;
15570   }
15571 
15572   if (HasError) {
15573     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
15574         << "omp_interop_t";
15575     return false;
15576   }
15577 
15578   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
15579   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
15580     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
15581     return false;
15582   }
15583 
15584   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15585   // The interop-var passed to init or destroy must be non-const.
15586   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
15587       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
15588     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
15589         << /*non-const*/ 1;
15590     return false;
15591   }
15592   return true;
15593 }
15594 
15595 OMPClause *
15596 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
15597                             bool IsTarget, bool IsTargetSync,
15598                             SourceLocation StartLoc, SourceLocation LParenLoc,
15599                             SourceLocation VarLoc, SourceLocation EndLoc) {
15600 
15601   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
15602     return nullptr;
15603 
15604   // Check prefer_type values.  These foreign-runtime-id values are either
15605   // string literals or constant integral expressions.
15606   for (const Expr *E : PrefExprs) {
15607     if (E->isValueDependent() || E->isTypeDependent() ||
15608         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15609       continue;
15610     if (E->isIntegerConstantExpr(Context))
15611       continue;
15612     if (isa<StringLiteral>(E))
15613       continue;
15614     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
15615     return nullptr;
15616   }
15617 
15618   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
15619                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
15620                                EndLoc);
15621 }
15622 
15623 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
15624                                       SourceLocation LParenLoc,
15625                                       SourceLocation VarLoc,
15626                                       SourceLocation EndLoc) {
15627 
15628   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
15629     return nullptr;
15630 
15631   return new (Context)
15632       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15633 }
15634 
15635 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
15636                                           SourceLocation StartLoc,
15637                                           SourceLocation LParenLoc,
15638                                           SourceLocation VarLoc,
15639                                           SourceLocation EndLoc) {
15640   if (InteropVar &&
15641       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
15642     return nullptr;
15643 
15644   return new (Context)
15645       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15646 }
15647 
15648 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
15649                                              SourceLocation StartLoc,
15650                                              SourceLocation LParenLoc,
15651                                              SourceLocation EndLoc) {
15652   Expr *ValExpr = Condition;
15653   Stmt *HelperValStmt = nullptr;
15654   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15655   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15656       !Condition->isInstantiationDependent() &&
15657       !Condition->containsUnexpandedParameterPack()) {
15658     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15659     if (Val.isInvalid())
15660       return nullptr;
15661 
15662     ValExpr = MakeFullExpr(Val.get()).get();
15663 
15664     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15665     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
15666                                                     LangOpts.OpenMP);
15667     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15668       ValExpr = MakeFullExpr(ValExpr).get();
15669       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15670       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15671       HelperValStmt = buildPreInits(Context, Captures);
15672     }
15673   }
15674 
15675   return new (Context) OMPNovariantsClause(
15676       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15677 }
15678 
15679 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
15680                                             SourceLocation StartLoc,
15681                                             SourceLocation LParenLoc,
15682                                             SourceLocation EndLoc) {
15683   Expr *ValExpr = Condition;
15684   Stmt *HelperValStmt = nullptr;
15685   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15686   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15687       !Condition->isInstantiationDependent() &&
15688       !Condition->containsUnexpandedParameterPack()) {
15689     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15690     if (Val.isInvalid())
15691       return nullptr;
15692 
15693     ValExpr = MakeFullExpr(Val.get()).get();
15694 
15695     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15696     CaptureRegion =
15697         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
15698     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15699       ValExpr = MakeFullExpr(ValExpr).get();
15700       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15701       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15702       HelperValStmt = buildPreInits(Context, Captures);
15703     }
15704   }
15705 
15706   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
15707                                           StartLoc, LParenLoc, EndLoc);
15708 }
15709 
15710 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
15711                                          SourceLocation StartLoc,
15712                                          SourceLocation LParenLoc,
15713                                          SourceLocation EndLoc) {
15714   Expr *ValExpr = ThreadID;
15715   Stmt *HelperValStmt = nullptr;
15716 
15717   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15718   OpenMPDirectiveKind CaptureRegion =
15719       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
15720   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15721     ValExpr = MakeFullExpr(ValExpr).get();
15722     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15723     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15724     HelperValStmt = buildPreInits(Context, Captures);
15725   }
15726 
15727   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
15728                                        StartLoc, LParenLoc, EndLoc);
15729 }
15730 
15731 OMPClause *Sema::ActOnOpenMPVarListClause(
15732     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
15733     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
15734     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
15735     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
15736     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15737     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
15738     SourceLocation ExtraModifierLoc,
15739     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
15740     ArrayRef<SourceLocation> MotionModifiersLoc) {
15741   SourceLocation StartLoc = Locs.StartLoc;
15742   SourceLocation LParenLoc = Locs.LParenLoc;
15743   SourceLocation EndLoc = Locs.EndLoc;
15744   OMPClause *Res = nullptr;
15745   switch (Kind) {
15746   case OMPC_private:
15747     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15748     break;
15749   case OMPC_firstprivate:
15750     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15751     break;
15752   case OMPC_lastprivate:
15753     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
15754            "Unexpected lastprivate modifier.");
15755     Res = ActOnOpenMPLastprivateClause(
15756         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
15757         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
15758     break;
15759   case OMPC_shared:
15760     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
15761     break;
15762   case OMPC_reduction:
15763     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
15764            "Unexpected lastprivate modifier.");
15765     Res = ActOnOpenMPReductionClause(
15766         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
15767         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
15768         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
15769     break;
15770   case OMPC_task_reduction:
15771     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15772                                          EndLoc, ReductionOrMapperIdScopeSpec,
15773                                          ReductionOrMapperId);
15774     break;
15775   case OMPC_in_reduction:
15776     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15777                                        EndLoc, ReductionOrMapperIdScopeSpec,
15778                                        ReductionOrMapperId);
15779     break;
15780   case OMPC_linear:
15781     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
15782            "Unexpected linear modifier.");
15783     Res = ActOnOpenMPLinearClause(
15784         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15785         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15786         ColonLoc, EndLoc);
15787     break;
15788   case OMPC_aligned:
15789     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15790                                    LParenLoc, ColonLoc, EndLoc);
15791     break;
15792   case OMPC_copyin:
15793     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15794     break;
15795   case OMPC_copyprivate:
15796     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15797     break;
15798   case OMPC_flush:
15799     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15800     break;
15801   case OMPC_depend:
15802     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15803            "Unexpected depend modifier.");
15804     Res = ActOnOpenMPDependClause(
15805         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15806         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15807     break;
15808   case OMPC_map:
15809     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15810            "Unexpected map modifier.");
15811     Res = ActOnOpenMPMapClause(
15812         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15813         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15814         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15815     break;
15816   case OMPC_to:
15817     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15818                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15819                               ColonLoc, VarList, Locs);
15820     break;
15821   case OMPC_from:
15822     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15823                                 ReductionOrMapperIdScopeSpec,
15824                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15825     break;
15826   case OMPC_use_device_ptr:
15827     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15828     break;
15829   case OMPC_use_device_addr:
15830     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15831     break;
15832   case OMPC_is_device_ptr:
15833     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15834     break;
15835   case OMPC_allocate:
15836     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15837                                     LParenLoc, ColonLoc, EndLoc);
15838     break;
15839   case OMPC_nontemporal:
15840     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15841     break;
15842   case OMPC_inclusive:
15843     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15844     break;
15845   case OMPC_exclusive:
15846     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15847     break;
15848   case OMPC_affinity:
15849     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15850                                     DepModOrTailExpr, VarList);
15851     break;
15852   case OMPC_if:
15853   case OMPC_depobj:
15854   case OMPC_final:
15855   case OMPC_num_threads:
15856   case OMPC_safelen:
15857   case OMPC_simdlen:
15858   case OMPC_sizes:
15859   case OMPC_allocator:
15860   case OMPC_collapse:
15861   case OMPC_default:
15862   case OMPC_proc_bind:
15863   case OMPC_schedule:
15864   case OMPC_ordered:
15865   case OMPC_nowait:
15866   case OMPC_untied:
15867   case OMPC_mergeable:
15868   case OMPC_threadprivate:
15869   case OMPC_read:
15870   case OMPC_write:
15871   case OMPC_update:
15872   case OMPC_capture:
15873   case OMPC_seq_cst:
15874   case OMPC_acq_rel:
15875   case OMPC_acquire:
15876   case OMPC_release:
15877   case OMPC_relaxed:
15878   case OMPC_device:
15879   case OMPC_threads:
15880   case OMPC_simd:
15881   case OMPC_num_teams:
15882   case OMPC_thread_limit:
15883   case OMPC_priority:
15884   case OMPC_grainsize:
15885   case OMPC_nogroup:
15886   case OMPC_num_tasks:
15887   case OMPC_hint:
15888   case OMPC_dist_schedule:
15889   case OMPC_defaultmap:
15890   case OMPC_unknown:
15891   case OMPC_uniform:
15892   case OMPC_unified_address:
15893   case OMPC_unified_shared_memory:
15894   case OMPC_reverse_offload:
15895   case OMPC_dynamic_allocators:
15896   case OMPC_atomic_default_mem_order:
15897   case OMPC_device_type:
15898   case OMPC_match:
15899   case OMPC_order:
15900   case OMPC_destroy:
15901   case OMPC_novariants:
15902   case OMPC_nocontext:
15903   case OMPC_detach:
15904   case OMPC_uses_allocators:
15905   case OMPC_when:
15906   case OMPC_bind:
15907   default:
15908     llvm_unreachable("Clause is not allowed.");
15909   }
15910   return Res;
15911 }
15912 
15913 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15914                                        ExprObjectKind OK, SourceLocation Loc) {
15915   ExprResult Res = BuildDeclRefExpr(
15916       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15917   if (!Res.isUsable())
15918     return ExprError();
15919   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15920     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15921     if (!Res.isUsable())
15922       return ExprError();
15923   }
15924   if (VK != VK_LValue && Res.get()->isGLValue()) {
15925     Res = DefaultLvalueConversion(Res.get());
15926     if (!Res.isUsable())
15927       return ExprError();
15928   }
15929   return Res;
15930 }
15931 
15932 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15933                                           SourceLocation StartLoc,
15934                                           SourceLocation LParenLoc,
15935                                           SourceLocation EndLoc) {
15936   SmallVector<Expr *, 8> Vars;
15937   SmallVector<Expr *, 8> PrivateCopies;
15938   for (Expr *RefExpr : VarList) {
15939     assert(RefExpr && "NULL expr in OpenMP private clause.");
15940     SourceLocation ELoc;
15941     SourceRange ERange;
15942     Expr *SimpleRefExpr = RefExpr;
15943     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15944     if (Res.second) {
15945       // It will be analyzed later.
15946       Vars.push_back(RefExpr);
15947       PrivateCopies.push_back(nullptr);
15948     }
15949     ValueDecl *D = Res.first;
15950     if (!D)
15951       continue;
15952 
15953     QualType Type = D->getType();
15954     auto *VD = dyn_cast<VarDecl>(D);
15955 
15956     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15957     //  A variable that appears in a private clause must not have an incomplete
15958     //  type or a reference type.
15959     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15960       continue;
15961     Type = Type.getNonReferenceType();
15962 
15963     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15964     // A variable that is privatized must not have a const-qualified type
15965     // unless it is of class type with a mutable member. This restriction does
15966     // not apply to the firstprivate clause.
15967     //
15968     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15969     // A variable that appears in a private clause must not have a
15970     // const-qualified type unless it is of class type with a mutable member.
15971     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15972       continue;
15973 
15974     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15975     // in a Construct]
15976     //  Variables with the predetermined data-sharing attributes may not be
15977     //  listed in data-sharing attributes clauses, except for the cases
15978     //  listed below. For these exceptions only, listing a predetermined
15979     //  variable in a data-sharing attribute clause is allowed and overrides
15980     //  the variable's predetermined data-sharing attributes.
15981     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15982     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15983       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15984                                           << getOpenMPClauseName(OMPC_private);
15985       reportOriginalDsa(*this, DSAStack, D, DVar);
15986       continue;
15987     }
15988 
15989     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15990     // Variably modified types are not supported for tasks.
15991     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15992         isOpenMPTaskingDirective(CurrDir)) {
15993       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15994           << getOpenMPClauseName(OMPC_private) << Type
15995           << getOpenMPDirectiveName(CurrDir);
15996       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15997                                VarDecl::DeclarationOnly;
15998       Diag(D->getLocation(),
15999            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16000           << D;
16001       continue;
16002     }
16003 
16004     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16005     // A list item cannot appear in both a map clause and a data-sharing
16006     // attribute clause on the same construct
16007     //
16008     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16009     // A list item cannot appear in both a map clause and a data-sharing
16010     // attribute clause on the same construct unless the construct is a
16011     // combined construct.
16012     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
16013         CurrDir == OMPD_target) {
16014       OpenMPClauseKind ConflictKind;
16015       if (DSAStack->checkMappableExprComponentListsForDecl(
16016               VD, /*CurrentRegionOnly=*/true,
16017               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
16018                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
16019                 ConflictKind = WhereFoundClauseKind;
16020                 return true;
16021               })) {
16022         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16023             << getOpenMPClauseName(OMPC_private)
16024             << getOpenMPClauseName(ConflictKind)
16025             << getOpenMPDirectiveName(CurrDir);
16026         reportOriginalDsa(*this, DSAStack, D, DVar);
16027         continue;
16028       }
16029     }
16030 
16031     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
16032     //  A variable of class type (or array thereof) that appears in a private
16033     //  clause requires an accessible, unambiguous default constructor for the
16034     //  class type.
16035     // Generate helper private variable and initialize it with the default
16036     // value. The address of the original variable is replaced by the address of
16037     // the new private variable in CodeGen. This new variable is not added to
16038     // IdResolver, so the code in the OpenMP region uses original variable for
16039     // proper diagnostics.
16040     Type = Type.getUnqualifiedType();
16041     VarDecl *VDPrivate =
16042         buildVarDecl(*this, ELoc, Type, D->getName(),
16043                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16044                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16045     ActOnUninitializedDecl(VDPrivate);
16046     if (VDPrivate->isInvalidDecl())
16047       continue;
16048     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16049         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16050 
16051     DeclRefExpr *Ref = nullptr;
16052     if (!VD && !CurContext->isDependentContext())
16053       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16054     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
16055     Vars.push_back((VD || CurContext->isDependentContext())
16056                        ? RefExpr->IgnoreParens()
16057                        : Ref);
16058     PrivateCopies.push_back(VDPrivateRefExpr);
16059   }
16060 
16061   if (Vars.empty())
16062     return nullptr;
16063 
16064   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
16065                                   PrivateCopies);
16066 }
16067 
16068 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
16069                                                SourceLocation StartLoc,
16070                                                SourceLocation LParenLoc,
16071                                                SourceLocation EndLoc) {
16072   SmallVector<Expr *, 8> Vars;
16073   SmallVector<Expr *, 8> PrivateCopies;
16074   SmallVector<Expr *, 8> Inits;
16075   SmallVector<Decl *, 4> ExprCaptures;
16076   bool IsImplicitClause =
16077       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
16078   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
16079 
16080   for (Expr *RefExpr : VarList) {
16081     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
16082     SourceLocation ELoc;
16083     SourceRange ERange;
16084     Expr *SimpleRefExpr = RefExpr;
16085     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16086     if (Res.second) {
16087       // It will be analyzed later.
16088       Vars.push_back(RefExpr);
16089       PrivateCopies.push_back(nullptr);
16090       Inits.push_back(nullptr);
16091     }
16092     ValueDecl *D = Res.first;
16093     if (!D)
16094       continue;
16095 
16096     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
16097     QualType Type = D->getType();
16098     auto *VD = dyn_cast<VarDecl>(D);
16099 
16100     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16101     //  A variable that appears in a private clause must not have an incomplete
16102     //  type or a reference type.
16103     if (RequireCompleteType(ELoc, Type,
16104                             diag::err_omp_firstprivate_incomplete_type))
16105       continue;
16106     Type = Type.getNonReferenceType();
16107 
16108     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
16109     //  A variable of class type (or array thereof) that appears in a private
16110     //  clause requires an accessible, unambiguous copy constructor for the
16111     //  class type.
16112     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
16113 
16114     // If an implicit firstprivate variable found it was checked already.
16115     DSAStackTy::DSAVarData TopDVar;
16116     if (!IsImplicitClause) {
16117       DSAStackTy::DSAVarData DVar =
16118           DSAStack->getTopDSA(D, /*FromParent=*/false);
16119       TopDVar = DVar;
16120       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16121       bool IsConstant = ElemType.isConstant(Context);
16122       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
16123       //  A list item that specifies a given variable may not appear in more
16124       // than one clause on the same directive, except that a variable may be
16125       //  specified in both firstprivate and lastprivate clauses.
16126       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16127       // A list item may appear in a firstprivate or lastprivate clause but not
16128       // both.
16129       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
16130           (isOpenMPDistributeDirective(CurrDir) ||
16131            DVar.CKind != OMPC_lastprivate) &&
16132           DVar.RefExpr) {
16133         Diag(ELoc, diag::err_omp_wrong_dsa)
16134             << getOpenMPClauseName(DVar.CKind)
16135             << getOpenMPClauseName(OMPC_firstprivate);
16136         reportOriginalDsa(*this, DSAStack, D, DVar);
16137         continue;
16138       }
16139 
16140       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16141       // in a Construct]
16142       //  Variables with the predetermined data-sharing attributes may not be
16143       //  listed in data-sharing attributes clauses, except for the cases
16144       //  listed below. For these exceptions only, listing a predetermined
16145       //  variable in a data-sharing attribute clause is allowed and overrides
16146       //  the variable's predetermined data-sharing attributes.
16147       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16148       // in a Construct, C/C++, p.2]
16149       //  Variables with const-qualified type having no mutable member may be
16150       //  listed in a firstprivate clause, even if they are static data members.
16151       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
16152           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
16153         Diag(ELoc, diag::err_omp_wrong_dsa)
16154             << getOpenMPClauseName(DVar.CKind)
16155             << getOpenMPClauseName(OMPC_firstprivate);
16156         reportOriginalDsa(*this, DSAStack, D, DVar);
16157         continue;
16158       }
16159 
16160       // OpenMP [2.9.3.4, Restrictions, p.2]
16161       //  A list item that is private within a parallel region must not appear
16162       //  in a firstprivate clause on a worksharing construct if any of the
16163       //  worksharing regions arising from the worksharing construct ever bind
16164       //  to any of the parallel regions arising from the parallel construct.
16165       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16166       // A list item that is private within a teams region must not appear in a
16167       // firstprivate clause on a distribute construct if any of the distribute
16168       // regions arising from the distribute construct ever bind to any of the
16169       // teams regions arising from the teams construct.
16170       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16171       // A list item that appears in a reduction clause of a teams construct
16172       // must not appear in a firstprivate clause on a distribute construct if
16173       // any of the distribute regions arising from the distribute construct
16174       // ever bind to any of the teams regions arising from the teams construct.
16175       if ((isOpenMPWorksharingDirective(CurrDir) ||
16176            isOpenMPDistributeDirective(CurrDir)) &&
16177           !isOpenMPParallelDirective(CurrDir) &&
16178           !isOpenMPTeamsDirective(CurrDir)) {
16179         DVar = DSAStack->getImplicitDSA(D, true);
16180         if (DVar.CKind != OMPC_shared &&
16181             (isOpenMPParallelDirective(DVar.DKind) ||
16182              isOpenMPTeamsDirective(DVar.DKind) ||
16183              DVar.DKind == OMPD_unknown)) {
16184           Diag(ELoc, diag::err_omp_required_access)
16185               << getOpenMPClauseName(OMPC_firstprivate)
16186               << getOpenMPClauseName(OMPC_shared);
16187           reportOriginalDsa(*this, DSAStack, D, DVar);
16188           continue;
16189         }
16190       }
16191       // OpenMP [2.9.3.4, Restrictions, p.3]
16192       //  A list item that appears in a reduction clause of a parallel construct
16193       //  must not appear in a firstprivate clause on a worksharing or task
16194       //  construct if any of the worksharing or task regions arising from the
16195       //  worksharing or task construct ever bind to any of the parallel regions
16196       //  arising from the parallel construct.
16197       // OpenMP [2.9.3.4, Restrictions, p.4]
16198       //  A list item that appears in a reduction clause in worksharing
16199       //  construct must not appear in a firstprivate clause in a task construct
16200       //  encountered during execution of any of the worksharing regions arising
16201       //  from the worksharing construct.
16202       if (isOpenMPTaskingDirective(CurrDir)) {
16203         DVar = DSAStack->hasInnermostDSA(
16204             D,
16205             [](OpenMPClauseKind C, bool AppliedToPointee) {
16206               return C == OMPC_reduction && !AppliedToPointee;
16207             },
16208             [](OpenMPDirectiveKind K) {
16209               return isOpenMPParallelDirective(K) ||
16210                      isOpenMPWorksharingDirective(K) ||
16211                      isOpenMPTeamsDirective(K);
16212             },
16213             /*FromParent=*/true);
16214         if (DVar.CKind == OMPC_reduction &&
16215             (isOpenMPParallelDirective(DVar.DKind) ||
16216              isOpenMPWorksharingDirective(DVar.DKind) ||
16217              isOpenMPTeamsDirective(DVar.DKind))) {
16218           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
16219               << getOpenMPDirectiveName(DVar.DKind);
16220           reportOriginalDsa(*this, DSAStack, D, DVar);
16221           continue;
16222         }
16223       }
16224 
16225       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16226       // A list item cannot appear in both a map clause and a data-sharing
16227       // attribute clause on the same construct
16228       //
16229       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16230       // A list item cannot appear in both a map clause and a data-sharing
16231       // attribute clause on the same construct unless the construct is a
16232       // combined construct.
16233       if ((LangOpts.OpenMP <= 45 &&
16234            isOpenMPTargetExecutionDirective(CurrDir)) ||
16235           CurrDir == OMPD_target) {
16236         OpenMPClauseKind ConflictKind;
16237         if (DSAStack->checkMappableExprComponentListsForDecl(
16238                 VD, /*CurrentRegionOnly=*/true,
16239                 [&ConflictKind](
16240                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
16241                     OpenMPClauseKind WhereFoundClauseKind) {
16242                   ConflictKind = WhereFoundClauseKind;
16243                   return true;
16244                 })) {
16245           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16246               << getOpenMPClauseName(OMPC_firstprivate)
16247               << getOpenMPClauseName(ConflictKind)
16248               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16249           reportOriginalDsa(*this, DSAStack, D, DVar);
16250           continue;
16251         }
16252       }
16253     }
16254 
16255     // Variably modified types are not supported for tasks.
16256     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
16257         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
16258       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16259           << getOpenMPClauseName(OMPC_firstprivate) << Type
16260           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16261       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16262                                VarDecl::DeclarationOnly;
16263       Diag(D->getLocation(),
16264            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16265           << D;
16266       continue;
16267     }
16268 
16269     Type = Type.getUnqualifiedType();
16270     VarDecl *VDPrivate =
16271         buildVarDecl(*this, ELoc, Type, D->getName(),
16272                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16273                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16274     // Generate helper private variable and initialize it with the value of the
16275     // original variable. The address of the original variable is replaced by
16276     // the address of the new private variable in the CodeGen. This new variable
16277     // is not added to IdResolver, so the code in the OpenMP region uses
16278     // original variable for proper diagnostics and variable capturing.
16279     Expr *VDInitRefExpr = nullptr;
16280     // For arrays generate initializer for single element and replace it by the
16281     // original array element in CodeGen.
16282     if (Type->isArrayType()) {
16283       VarDecl *VDInit =
16284           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
16285       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
16286       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
16287       ElemType = ElemType.getUnqualifiedType();
16288       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
16289                                          ".firstprivate.temp");
16290       InitializedEntity Entity =
16291           InitializedEntity::InitializeVariable(VDInitTemp);
16292       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
16293 
16294       InitializationSequence InitSeq(*this, Entity, Kind, Init);
16295       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
16296       if (Result.isInvalid())
16297         VDPrivate->setInvalidDecl();
16298       else
16299         VDPrivate->setInit(Result.getAs<Expr>());
16300       // Remove temp variable declaration.
16301       Context.Deallocate(VDInitTemp);
16302     } else {
16303       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
16304                                      ".firstprivate.temp");
16305       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
16306                                        RefExpr->getExprLoc());
16307       AddInitializerToDecl(VDPrivate,
16308                            DefaultLvalueConversion(VDInitRefExpr).get(),
16309                            /*DirectInit=*/false);
16310     }
16311     if (VDPrivate->isInvalidDecl()) {
16312       if (IsImplicitClause) {
16313         Diag(RefExpr->getExprLoc(),
16314              diag::note_omp_task_predetermined_firstprivate_here);
16315       }
16316       continue;
16317     }
16318     CurContext->addDecl(VDPrivate);
16319     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16320         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
16321         RefExpr->getExprLoc());
16322     DeclRefExpr *Ref = nullptr;
16323     if (!VD && !CurContext->isDependentContext()) {
16324       if (TopDVar.CKind == OMPC_lastprivate) {
16325         Ref = TopDVar.PrivateCopy;
16326       } else {
16327         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16328         if (!isOpenMPCapturedDecl(D))
16329           ExprCaptures.push_back(Ref->getDecl());
16330       }
16331     }
16332     if (!IsImplicitClause)
16333       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16334     Vars.push_back((VD || CurContext->isDependentContext())
16335                        ? RefExpr->IgnoreParens()
16336                        : Ref);
16337     PrivateCopies.push_back(VDPrivateRefExpr);
16338     Inits.push_back(VDInitRefExpr);
16339   }
16340 
16341   if (Vars.empty())
16342     return nullptr;
16343 
16344   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16345                                        Vars, PrivateCopies, Inits,
16346                                        buildPreInits(Context, ExprCaptures));
16347 }
16348 
16349 OMPClause *Sema::ActOnOpenMPLastprivateClause(
16350     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
16351     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
16352     SourceLocation LParenLoc, SourceLocation EndLoc) {
16353   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
16354     assert(ColonLoc.isValid() && "Colon location must be valid.");
16355     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
16356         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
16357                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
16358         << getOpenMPClauseName(OMPC_lastprivate);
16359     return nullptr;
16360   }
16361 
16362   SmallVector<Expr *, 8> Vars;
16363   SmallVector<Expr *, 8> SrcExprs;
16364   SmallVector<Expr *, 8> DstExprs;
16365   SmallVector<Expr *, 8> AssignmentOps;
16366   SmallVector<Decl *, 4> ExprCaptures;
16367   SmallVector<Expr *, 4> ExprPostUpdates;
16368   for (Expr *RefExpr : VarList) {
16369     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16370     SourceLocation ELoc;
16371     SourceRange ERange;
16372     Expr *SimpleRefExpr = RefExpr;
16373     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16374     if (Res.second) {
16375       // It will be analyzed later.
16376       Vars.push_back(RefExpr);
16377       SrcExprs.push_back(nullptr);
16378       DstExprs.push_back(nullptr);
16379       AssignmentOps.push_back(nullptr);
16380     }
16381     ValueDecl *D = Res.first;
16382     if (!D)
16383       continue;
16384 
16385     QualType Type = D->getType();
16386     auto *VD = dyn_cast<VarDecl>(D);
16387 
16388     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
16389     //  A variable that appears in a lastprivate clause must not have an
16390     //  incomplete type or a reference type.
16391     if (RequireCompleteType(ELoc, Type,
16392                             diag::err_omp_lastprivate_incomplete_type))
16393       continue;
16394     Type = Type.getNonReferenceType();
16395 
16396     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16397     // A variable that is privatized must not have a const-qualified type
16398     // unless it is of class type with a mutable member. This restriction does
16399     // not apply to the firstprivate clause.
16400     //
16401     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
16402     // A variable that appears in a lastprivate clause must not have a
16403     // const-qualified type unless it is of class type with a mutable member.
16404     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
16405       continue;
16406 
16407     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
16408     // A list item that appears in a lastprivate clause with the conditional
16409     // modifier must be a scalar variable.
16410     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
16411       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
16412       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16413                                VarDecl::DeclarationOnly;
16414       Diag(D->getLocation(),
16415            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16416           << D;
16417       continue;
16418     }
16419 
16420     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16421     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16422     // in a Construct]
16423     //  Variables with the predetermined data-sharing attributes may not be
16424     //  listed in data-sharing attributes clauses, except for the cases
16425     //  listed below.
16426     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16427     // A list item may appear in a firstprivate or lastprivate clause but not
16428     // both.
16429     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16430     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
16431         (isOpenMPDistributeDirective(CurrDir) ||
16432          DVar.CKind != OMPC_firstprivate) &&
16433         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
16434       Diag(ELoc, diag::err_omp_wrong_dsa)
16435           << getOpenMPClauseName(DVar.CKind)
16436           << getOpenMPClauseName(OMPC_lastprivate);
16437       reportOriginalDsa(*this, DSAStack, D, DVar);
16438       continue;
16439     }
16440 
16441     // OpenMP [2.14.3.5, Restrictions, p.2]
16442     // A list item that is private within a parallel region, or that appears in
16443     // the reduction clause of a parallel construct, must not appear in a
16444     // lastprivate clause on a worksharing construct if any of the corresponding
16445     // worksharing regions ever binds to any of the corresponding parallel
16446     // regions.
16447     DSAStackTy::DSAVarData TopDVar = DVar;
16448     if (isOpenMPWorksharingDirective(CurrDir) &&
16449         !isOpenMPParallelDirective(CurrDir) &&
16450         !isOpenMPTeamsDirective(CurrDir)) {
16451       DVar = DSAStack->getImplicitDSA(D, true);
16452       if (DVar.CKind != OMPC_shared) {
16453         Diag(ELoc, diag::err_omp_required_access)
16454             << getOpenMPClauseName(OMPC_lastprivate)
16455             << getOpenMPClauseName(OMPC_shared);
16456         reportOriginalDsa(*this, DSAStack, D, DVar);
16457         continue;
16458       }
16459     }
16460 
16461     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
16462     //  A variable of class type (or array thereof) that appears in a
16463     //  lastprivate clause requires an accessible, unambiguous default
16464     //  constructor for the class type, unless the list item is also specified
16465     //  in a firstprivate clause.
16466     //  A variable of class type (or array thereof) that appears in a
16467     //  lastprivate clause requires an accessible, unambiguous copy assignment
16468     //  operator for the class type.
16469     Type = Context.getBaseElementType(Type).getNonReferenceType();
16470     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
16471                                   Type.getUnqualifiedType(), ".lastprivate.src",
16472                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16473     DeclRefExpr *PseudoSrcExpr =
16474         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
16475     VarDecl *DstVD =
16476         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
16477                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16478     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16479     // For arrays generate assignment operation for single element and replace
16480     // it by the original array element in CodeGen.
16481     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
16482                                          PseudoDstExpr, PseudoSrcExpr);
16483     if (AssignmentOp.isInvalid())
16484       continue;
16485     AssignmentOp =
16486         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16487     if (AssignmentOp.isInvalid())
16488       continue;
16489 
16490     DeclRefExpr *Ref = nullptr;
16491     if (!VD && !CurContext->isDependentContext()) {
16492       if (TopDVar.CKind == OMPC_firstprivate) {
16493         Ref = TopDVar.PrivateCopy;
16494       } else {
16495         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16496         if (!isOpenMPCapturedDecl(D))
16497           ExprCaptures.push_back(Ref->getDecl());
16498       }
16499       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
16500           (!isOpenMPCapturedDecl(D) &&
16501            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
16502         ExprResult RefRes = DefaultLvalueConversion(Ref);
16503         if (!RefRes.isUsable())
16504           continue;
16505         ExprResult PostUpdateRes =
16506             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16507                        RefRes.get());
16508         if (!PostUpdateRes.isUsable())
16509           continue;
16510         ExprPostUpdates.push_back(
16511             IgnoredValueConversions(PostUpdateRes.get()).get());
16512       }
16513     }
16514     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
16515     Vars.push_back((VD || CurContext->isDependentContext())
16516                        ? RefExpr->IgnoreParens()
16517                        : Ref);
16518     SrcExprs.push_back(PseudoSrcExpr);
16519     DstExprs.push_back(PseudoDstExpr);
16520     AssignmentOps.push_back(AssignmentOp.get());
16521   }
16522 
16523   if (Vars.empty())
16524     return nullptr;
16525 
16526   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16527                                       Vars, SrcExprs, DstExprs, AssignmentOps,
16528                                       LPKind, LPKindLoc, ColonLoc,
16529                                       buildPreInits(Context, ExprCaptures),
16530                                       buildPostUpdate(*this, ExprPostUpdates));
16531 }
16532 
16533 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
16534                                          SourceLocation StartLoc,
16535                                          SourceLocation LParenLoc,
16536                                          SourceLocation EndLoc) {
16537   SmallVector<Expr *, 8> Vars;
16538   for (Expr *RefExpr : VarList) {
16539     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16540     SourceLocation ELoc;
16541     SourceRange ERange;
16542     Expr *SimpleRefExpr = RefExpr;
16543     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16544     if (Res.second) {
16545       // It will be analyzed later.
16546       Vars.push_back(RefExpr);
16547     }
16548     ValueDecl *D = Res.first;
16549     if (!D)
16550       continue;
16551 
16552     auto *VD = dyn_cast<VarDecl>(D);
16553     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16554     // in a Construct]
16555     //  Variables with the predetermined data-sharing attributes may not be
16556     //  listed in data-sharing attributes clauses, except for the cases
16557     //  listed below. For these exceptions only, listing a predetermined
16558     //  variable in a data-sharing attribute clause is allowed and overrides
16559     //  the variable's predetermined data-sharing attributes.
16560     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16561     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
16562         DVar.RefExpr) {
16563       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16564                                           << getOpenMPClauseName(OMPC_shared);
16565       reportOriginalDsa(*this, DSAStack, D, DVar);
16566       continue;
16567     }
16568 
16569     DeclRefExpr *Ref = nullptr;
16570     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
16571       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16572     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
16573     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
16574                        ? RefExpr->IgnoreParens()
16575                        : Ref);
16576   }
16577 
16578   if (Vars.empty())
16579     return nullptr;
16580 
16581   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
16582 }
16583 
16584 namespace {
16585 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
16586   DSAStackTy *Stack;
16587 
16588 public:
16589   bool VisitDeclRefExpr(DeclRefExpr *E) {
16590     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
16591       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
16592       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
16593         return false;
16594       if (DVar.CKind != OMPC_unknown)
16595         return true;
16596       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
16597           VD,
16598           [](OpenMPClauseKind C, bool AppliedToPointee) {
16599             return isOpenMPPrivate(C) && !AppliedToPointee;
16600           },
16601           [](OpenMPDirectiveKind) { return true; },
16602           /*FromParent=*/true);
16603       return DVarPrivate.CKind != OMPC_unknown;
16604     }
16605     return false;
16606   }
16607   bool VisitStmt(Stmt *S) {
16608     for (Stmt *Child : S->children()) {
16609       if (Child && Visit(Child))
16610         return true;
16611     }
16612     return false;
16613   }
16614   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
16615 };
16616 } // namespace
16617 
16618 namespace {
16619 // Transform MemberExpression for specified FieldDecl of current class to
16620 // DeclRefExpr to specified OMPCapturedExprDecl.
16621 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
16622   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
16623   ValueDecl *Field = nullptr;
16624   DeclRefExpr *CapturedExpr = nullptr;
16625 
16626 public:
16627   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
16628       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
16629 
16630   ExprResult TransformMemberExpr(MemberExpr *E) {
16631     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
16632         E->getMemberDecl() == Field) {
16633       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
16634       return CapturedExpr;
16635     }
16636     return BaseTransform::TransformMemberExpr(E);
16637   }
16638   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
16639 };
16640 } // namespace
16641 
16642 template <typename T, typename U>
16643 static T filterLookupForUDReductionAndMapper(
16644     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
16645   for (U &Set : Lookups) {
16646     for (auto *D : Set) {
16647       if (T Res = Gen(cast<ValueDecl>(D)))
16648         return Res;
16649     }
16650   }
16651   return T();
16652 }
16653 
16654 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
16655   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
16656 
16657   for (auto RD : D->redecls()) {
16658     // Don't bother with extra checks if we already know this one isn't visible.
16659     if (RD == D)
16660       continue;
16661 
16662     auto ND = cast<NamedDecl>(RD);
16663     if (LookupResult::isVisible(SemaRef, ND))
16664       return ND;
16665   }
16666 
16667   return nullptr;
16668 }
16669 
16670 static void
16671 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
16672                         SourceLocation Loc, QualType Ty,
16673                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
16674   // Find all of the associated namespaces and classes based on the
16675   // arguments we have.
16676   Sema::AssociatedNamespaceSet AssociatedNamespaces;
16677   Sema::AssociatedClassSet AssociatedClasses;
16678   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
16679   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
16680                                              AssociatedClasses);
16681 
16682   // C++ [basic.lookup.argdep]p3:
16683   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
16684   //   and let Y be the lookup set produced by argument dependent
16685   //   lookup (defined as follows). If X contains [...] then Y is
16686   //   empty. Otherwise Y is the set of declarations found in the
16687   //   namespaces associated with the argument types as described
16688   //   below. The set of declarations found by the lookup of the name
16689   //   is the union of X and Y.
16690   //
16691   // Here, we compute Y and add its members to the overloaded
16692   // candidate set.
16693   for (auto *NS : AssociatedNamespaces) {
16694     //   When considering an associated namespace, the lookup is the
16695     //   same as the lookup performed when the associated namespace is
16696     //   used as a qualifier (3.4.3.2) except that:
16697     //
16698     //     -- Any using-directives in the associated namespace are
16699     //        ignored.
16700     //
16701     //     -- Any namespace-scope friend functions declared in
16702     //        associated classes are visible within their respective
16703     //        namespaces even if they are not visible during an ordinary
16704     //        lookup (11.4).
16705     DeclContext::lookup_result R = NS->lookup(Id.getName());
16706     for (auto *D : R) {
16707       auto *Underlying = D;
16708       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16709         Underlying = USD->getTargetDecl();
16710 
16711       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
16712           !isa<OMPDeclareMapperDecl>(Underlying))
16713         continue;
16714 
16715       if (!SemaRef.isVisible(D)) {
16716         D = findAcceptableDecl(SemaRef, D);
16717         if (!D)
16718           continue;
16719         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16720           Underlying = USD->getTargetDecl();
16721       }
16722       Lookups.emplace_back();
16723       Lookups.back().addDecl(Underlying);
16724     }
16725   }
16726 }
16727 
16728 static ExprResult
16729 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
16730                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
16731                          const DeclarationNameInfo &ReductionId, QualType Ty,
16732                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
16733   if (ReductionIdScopeSpec.isInvalid())
16734     return ExprError();
16735   SmallVector<UnresolvedSet<8>, 4> Lookups;
16736   if (S) {
16737     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16738     Lookup.suppressDiagnostics();
16739     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
16740       NamedDecl *D = Lookup.getRepresentativeDecl();
16741       do {
16742         S = S->getParent();
16743       } while (S && !S->isDeclScope(D));
16744       if (S)
16745         S = S->getParent();
16746       Lookups.emplace_back();
16747       Lookups.back().append(Lookup.begin(), Lookup.end());
16748       Lookup.clear();
16749     }
16750   } else if (auto *ULE =
16751                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
16752     Lookups.push_back(UnresolvedSet<8>());
16753     Decl *PrevD = nullptr;
16754     for (NamedDecl *D : ULE->decls()) {
16755       if (D == PrevD)
16756         Lookups.push_back(UnresolvedSet<8>());
16757       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
16758         Lookups.back().addDecl(DRD);
16759       PrevD = D;
16760     }
16761   }
16762   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16763       Ty->isInstantiationDependentType() ||
16764       Ty->containsUnexpandedParameterPack() ||
16765       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16766         return !D->isInvalidDecl() &&
16767                (D->getType()->isDependentType() ||
16768                 D->getType()->isInstantiationDependentType() ||
16769                 D->getType()->containsUnexpandedParameterPack());
16770       })) {
16771     UnresolvedSet<8> ResSet;
16772     for (const UnresolvedSet<8> &Set : Lookups) {
16773       if (Set.empty())
16774         continue;
16775       ResSet.append(Set.begin(), Set.end());
16776       // The last item marks the end of all declarations at the specified scope.
16777       ResSet.addDecl(Set[Set.size() - 1]);
16778     }
16779     return UnresolvedLookupExpr::Create(
16780         SemaRef.Context, /*NamingClass=*/nullptr,
16781         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16782         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16783   }
16784   // Lookup inside the classes.
16785   // C++ [over.match.oper]p3:
16786   //   For a unary operator @ with an operand of a type whose
16787   //   cv-unqualified version is T1, and for a binary operator @ with
16788   //   a left operand of a type whose cv-unqualified version is T1 and
16789   //   a right operand of a type whose cv-unqualified version is T2,
16790   //   three sets of candidate functions, designated member
16791   //   candidates, non-member candidates and built-in candidates, are
16792   //   constructed as follows:
16793   //     -- If T1 is a complete class type or a class currently being
16794   //        defined, the set of member candidates is the result of the
16795   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16796   //        the set of member candidates is empty.
16797   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16798   Lookup.suppressDiagnostics();
16799   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16800     // Complete the type if it can be completed.
16801     // If the type is neither complete nor being defined, bail out now.
16802     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16803         TyRec->getDecl()->getDefinition()) {
16804       Lookup.clear();
16805       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16806       if (Lookup.empty()) {
16807         Lookups.emplace_back();
16808         Lookups.back().append(Lookup.begin(), Lookup.end());
16809       }
16810     }
16811   }
16812   // Perform ADL.
16813   if (SemaRef.getLangOpts().CPlusPlus)
16814     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16815   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16816           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16817             if (!D->isInvalidDecl() &&
16818                 SemaRef.Context.hasSameType(D->getType(), Ty))
16819               return D;
16820             return nullptr;
16821           }))
16822     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16823                                     VK_LValue, Loc);
16824   if (SemaRef.getLangOpts().CPlusPlus) {
16825     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16826             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16827               if (!D->isInvalidDecl() &&
16828                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16829                   !Ty.isMoreQualifiedThan(D->getType()))
16830                 return D;
16831               return nullptr;
16832             })) {
16833       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16834                          /*DetectVirtual=*/false);
16835       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16836         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16837                 VD->getType().getUnqualifiedType()))) {
16838           if (SemaRef.CheckBaseClassAccess(
16839                   Loc, VD->getType(), Ty, Paths.front(),
16840                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16841             SemaRef.BuildBasePathArray(Paths, BasePath);
16842             return SemaRef.BuildDeclRefExpr(
16843                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16844           }
16845         }
16846       }
16847     }
16848   }
16849   if (ReductionIdScopeSpec.isSet()) {
16850     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16851         << Ty << Range;
16852     return ExprError();
16853   }
16854   return ExprEmpty();
16855 }
16856 
16857 namespace {
16858 /// Data for the reduction-based clauses.
16859 struct ReductionData {
16860   /// List of original reduction items.
16861   SmallVector<Expr *, 8> Vars;
16862   /// List of private copies of the reduction items.
16863   SmallVector<Expr *, 8> Privates;
16864   /// LHS expressions for the reduction_op expressions.
16865   SmallVector<Expr *, 8> LHSs;
16866   /// RHS expressions for the reduction_op expressions.
16867   SmallVector<Expr *, 8> RHSs;
16868   /// Reduction operation expression.
16869   SmallVector<Expr *, 8> ReductionOps;
16870   /// inscan copy operation expressions.
16871   SmallVector<Expr *, 8> InscanCopyOps;
16872   /// inscan copy temp array expressions for prefix sums.
16873   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16874   /// inscan copy temp array element expressions for prefix sums.
16875   SmallVector<Expr *, 8> InscanCopyArrayElems;
16876   /// Taskgroup descriptors for the corresponding reduction items in
16877   /// in_reduction clauses.
16878   SmallVector<Expr *, 8> TaskgroupDescriptors;
16879   /// List of captures for clause.
16880   SmallVector<Decl *, 4> ExprCaptures;
16881   /// List of postupdate expressions.
16882   SmallVector<Expr *, 4> ExprPostUpdates;
16883   /// Reduction modifier.
16884   unsigned RedModifier = 0;
16885   ReductionData() = delete;
16886   /// Reserves required memory for the reduction data.
16887   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16888     Vars.reserve(Size);
16889     Privates.reserve(Size);
16890     LHSs.reserve(Size);
16891     RHSs.reserve(Size);
16892     ReductionOps.reserve(Size);
16893     if (RedModifier == OMPC_REDUCTION_inscan) {
16894       InscanCopyOps.reserve(Size);
16895       InscanCopyArrayTemps.reserve(Size);
16896       InscanCopyArrayElems.reserve(Size);
16897     }
16898     TaskgroupDescriptors.reserve(Size);
16899     ExprCaptures.reserve(Size);
16900     ExprPostUpdates.reserve(Size);
16901   }
16902   /// Stores reduction item and reduction operation only (required for dependent
16903   /// reduction item).
16904   void push(Expr *Item, Expr *ReductionOp) {
16905     Vars.emplace_back(Item);
16906     Privates.emplace_back(nullptr);
16907     LHSs.emplace_back(nullptr);
16908     RHSs.emplace_back(nullptr);
16909     ReductionOps.emplace_back(ReductionOp);
16910     TaskgroupDescriptors.emplace_back(nullptr);
16911     if (RedModifier == OMPC_REDUCTION_inscan) {
16912       InscanCopyOps.push_back(nullptr);
16913       InscanCopyArrayTemps.push_back(nullptr);
16914       InscanCopyArrayElems.push_back(nullptr);
16915     }
16916   }
16917   /// Stores reduction data.
16918   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16919             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16920             Expr *CopyArrayElem) {
16921     Vars.emplace_back(Item);
16922     Privates.emplace_back(Private);
16923     LHSs.emplace_back(LHS);
16924     RHSs.emplace_back(RHS);
16925     ReductionOps.emplace_back(ReductionOp);
16926     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16927     if (RedModifier == OMPC_REDUCTION_inscan) {
16928       InscanCopyOps.push_back(CopyOp);
16929       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16930       InscanCopyArrayElems.push_back(CopyArrayElem);
16931     } else {
16932       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16933              CopyArrayElem == nullptr &&
16934              "Copy operation must be used for inscan reductions only.");
16935     }
16936   }
16937 };
16938 } // namespace
16939 
16940 static bool checkOMPArraySectionConstantForReduction(
16941     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16942     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16943   const Expr *Length = OASE->getLength();
16944   if (Length == nullptr) {
16945     // For array sections of the form [1:] or [:], we would need to analyze
16946     // the lower bound...
16947     if (OASE->getColonLocFirst().isValid())
16948       return false;
16949 
16950     // This is an array subscript which has implicit length 1!
16951     SingleElement = true;
16952     ArraySizes.push_back(llvm::APSInt::get(1));
16953   } else {
16954     Expr::EvalResult Result;
16955     if (!Length->EvaluateAsInt(Result, Context))
16956       return false;
16957 
16958     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16959     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16960     ArraySizes.push_back(ConstantLengthValue);
16961   }
16962 
16963   // Get the base of this array section and walk up from there.
16964   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16965 
16966   // We require length = 1 for all array sections except the right-most to
16967   // guarantee that the memory region is contiguous and has no holes in it.
16968   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16969     Length = TempOASE->getLength();
16970     if (Length == nullptr) {
16971       // For array sections of the form [1:] or [:], we would need to analyze
16972       // the lower bound...
16973       if (OASE->getColonLocFirst().isValid())
16974         return false;
16975 
16976       // This is an array subscript which has implicit length 1!
16977       ArraySizes.push_back(llvm::APSInt::get(1));
16978     } else {
16979       Expr::EvalResult Result;
16980       if (!Length->EvaluateAsInt(Result, Context))
16981         return false;
16982 
16983       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16984       if (ConstantLengthValue.getSExtValue() != 1)
16985         return false;
16986 
16987       ArraySizes.push_back(ConstantLengthValue);
16988     }
16989     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16990   }
16991 
16992   // If we have a single element, we don't need to add the implicit lengths.
16993   if (!SingleElement) {
16994     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16995       // Has implicit length 1!
16996       ArraySizes.push_back(llvm::APSInt::get(1));
16997       Base = TempASE->getBase()->IgnoreParenImpCasts();
16998     }
16999   }
17000 
17001   // This array section can be privatized as a single value or as a constant
17002   // sized array.
17003   return true;
17004 }
17005 
17006 static BinaryOperatorKind
17007 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
17008   if (BOK == BO_Add)
17009     return BO_AddAssign;
17010   if (BOK == BO_Mul)
17011     return BO_MulAssign;
17012   if (BOK == BO_And)
17013     return BO_AndAssign;
17014   if (BOK == BO_Or)
17015     return BO_OrAssign;
17016   if (BOK == BO_Xor)
17017     return BO_XorAssign;
17018   return BOK;
17019 }
17020 
17021 static bool actOnOMPReductionKindClause(
17022     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
17023     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17024     SourceLocation ColonLoc, SourceLocation EndLoc,
17025     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17026     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
17027   DeclarationName DN = ReductionId.getName();
17028   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
17029   BinaryOperatorKind BOK = BO_Comma;
17030 
17031   ASTContext &Context = S.Context;
17032   // OpenMP [2.14.3.6, reduction clause]
17033   // C
17034   // reduction-identifier is either an identifier or one of the following
17035   // operators: +, -, *,  &, |, ^, && and ||
17036   // C++
17037   // reduction-identifier is either an id-expression or one of the following
17038   // operators: +, -, *, &, |, ^, && and ||
17039   switch (OOK) {
17040   case OO_Plus:
17041   case OO_Minus:
17042     BOK = BO_Add;
17043     break;
17044   case OO_Star:
17045     BOK = BO_Mul;
17046     break;
17047   case OO_Amp:
17048     BOK = BO_And;
17049     break;
17050   case OO_Pipe:
17051     BOK = BO_Or;
17052     break;
17053   case OO_Caret:
17054     BOK = BO_Xor;
17055     break;
17056   case OO_AmpAmp:
17057     BOK = BO_LAnd;
17058     break;
17059   case OO_PipePipe:
17060     BOK = BO_LOr;
17061     break;
17062   case OO_New:
17063   case OO_Delete:
17064   case OO_Array_New:
17065   case OO_Array_Delete:
17066   case OO_Slash:
17067   case OO_Percent:
17068   case OO_Tilde:
17069   case OO_Exclaim:
17070   case OO_Equal:
17071   case OO_Less:
17072   case OO_Greater:
17073   case OO_LessEqual:
17074   case OO_GreaterEqual:
17075   case OO_PlusEqual:
17076   case OO_MinusEqual:
17077   case OO_StarEqual:
17078   case OO_SlashEqual:
17079   case OO_PercentEqual:
17080   case OO_CaretEqual:
17081   case OO_AmpEqual:
17082   case OO_PipeEqual:
17083   case OO_LessLess:
17084   case OO_GreaterGreater:
17085   case OO_LessLessEqual:
17086   case OO_GreaterGreaterEqual:
17087   case OO_EqualEqual:
17088   case OO_ExclaimEqual:
17089   case OO_Spaceship:
17090   case OO_PlusPlus:
17091   case OO_MinusMinus:
17092   case OO_Comma:
17093   case OO_ArrowStar:
17094   case OO_Arrow:
17095   case OO_Call:
17096   case OO_Subscript:
17097   case OO_Conditional:
17098   case OO_Coawait:
17099   case NUM_OVERLOADED_OPERATORS:
17100     llvm_unreachable("Unexpected reduction identifier");
17101   case OO_None:
17102     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
17103       if (II->isStr("max"))
17104         BOK = BO_GT;
17105       else if (II->isStr("min"))
17106         BOK = BO_LT;
17107     }
17108     break;
17109   }
17110   SourceRange ReductionIdRange;
17111   if (ReductionIdScopeSpec.isValid())
17112     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
17113   else
17114     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
17115   ReductionIdRange.setEnd(ReductionId.getEndLoc());
17116 
17117   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
17118   bool FirstIter = true;
17119   for (Expr *RefExpr : VarList) {
17120     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
17121     // OpenMP [2.1, C/C++]
17122     //  A list item is a variable or array section, subject to the restrictions
17123     //  specified in Section 2.4 on page 42 and in each of the sections
17124     // describing clauses and directives for which a list appears.
17125     // OpenMP  [2.14.3.3, Restrictions, p.1]
17126     //  A variable that is part of another variable (as an array or
17127     //  structure element) cannot appear in a private clause.
17128     if (!FirstIter && IR != ER)
17129       ++IR;
17130     FirstIter = false;
17131     SourceLocation ELoc;
17132     SourceRange ERange;
17133     Expr *SimpleRefExpr = RefExpr;
17134     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
17135                               /*AllowArraySection=*/true);
17136     if (Res.second) {
17137       // Try to find 'declare reduction' corresponding construct before using
17138       // builtin/overloaded operators.
17139       QualType Type = Context.DependentTy;
17140       CXXCastPath BasePath;
17141       ExprResult DeclareReductionRef = buildDeclareReductionRef(
17142           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17143           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17144       Expr *ReductionOp = nullptr;
17145       if (S.CurContext->isDependentContext() &&
17146           (DeclareReductionRef.isUnset() ||
17147            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
17148         ReductionOp = DeclareReductionRef.get();
17149       // It will be analyzed later.
17150       RD.push(RefExpr, ReductionOp);
17151     }
17152     ValueDecl *D = Res.first;
17153     if (!D)
17154       continue;
17155 
17156     Expr *TaskgroupDescriptor = nullptr;
17157     QualType Type;
17158     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
17159     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
17160     if (ASE) {
17161       Type = ASE->getType().getNonReferenceType();
17162     } else if (OASE) {
17163       QualType BaseType =
17164           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17165       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17166         Type = ATy->getElementType();
17167       else
17168         Type = BaseType->getPointeeType();
17169       Type = Type.getNonReferenceType();
17170     } else {
17171       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
17172     }
17173     auto *VD = dyn_cast<VarDecl>(D);
17174 
17175     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17176     //  A variable that appears in a private clause must not have an incomplete
17177     //  type or a reference type.
17178     if (S.RequireCompleteType(ELoc, D->getType(),
17179                               diag::err_omp_reduction_incomplete_type))
17180       continue;
17181     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17182     // A list item that appears in a reduction clause must not be
17183     // const-qualified.
17184     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
17185                                   /*AcceptIfMutable*/ false, ASE || OASE))
17186       continue;
17187 
17188     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
17189     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
17190     //  If a list-item is a reference type then it must bind to the same object
17191     //  for all threads of the team.
17192     if (!ASE && !OASE) {
17193       if (VD) {
17194         VarDecl *VDDef = VD->getDefinition();
17195         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
17196           DSARefChecker Check(Stack);
17197           if (Check.Visit(VDDef->getInit())) {
17198             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
17199                 << getOpenMPClauseName(ClauseKind) << ERange;
17200             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
17201             continue;
17202           }
17203         }
17204       }
17205 
17206       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
17207       // in a Construct]
17208       //  Variables with the predetermined data-sharing attributes may not be
17209       //  listed in data-sharing attributes clauses, except for the cases
17210       //  listed below. For these exceptions only, listing a predetermined
17211       //  variable in a data-sharing attribute clause is allowed and overrides
17212       //  the variable's predetermined data-sharing attributes.
17213       // OpenMP [2.14.3.6, Restrictions, p.3]
17214       //  Any number of reduction clauses can be specified on the directive,
17215       //  but a list item can appear only once in the reduction clauses for that
17216       //  directive.
17217       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17218       if (DVar.CKind == OMPC_reduction) {
17219         S.Diag(ELoc, diag::err_omp_once_referenced)
17220             << getOpenMPClauseName(ClauseKind);
17221         if (DVar.RefExpr)
17222           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
17223         continue;
17224       }
17225       if (DVar.CKind != OMPC_unknown) {
17226         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17227             << getOpenMPClauseName(DVar.CKind)
17228             << getOpenMPClauseName(OMPC_reduction);
17229         reportOriginalDsa(S, Stack, D, DVar);
17230         continue;
17231       }
17232 
17233       // OpenMP [2.14.3.6, Restrictions, p.1]
17234       //  A list item that appears in a reduction clause of a worksharing
17235       //  construct must be shared in the parallel regions to which any of the
17236       //  worksharing regions arising from the worksharing construct bind.
17237       if (isOpenMPWorksharingDirective(CurrDir) &&
17238           !isOpenMPParallelDirective(CurrDir) &&
17239           !isOpenMPTeamsDirective(CurrDir)) {
17240         DVar = Stack->getImplicitDSA(D, true);
17241         if (DVar.CKind != OMPC_shared) {
17242           S.Diag(ELoc, diag::err_omp_required_access)
17243               << getOpenMPClauseName(OMPC_reduction)
17244               << getOpenMPClauseName(OMPC_shared);
17245           reportOriginalDsa(S, Stack, D, DVar);
17246           continue;
17247         }
17248       }
17249     } else {
17250       // Threadprivates cannot be shared between threads, so dignose if the base
17251       // is a threadprivate variable.
17252       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17253       if (DVar.CKind == OMPC_threadprivate) {
17254         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17255             << getOpenMPClauseName(DVar.CKind)
17256             << getOpenMPClauseName(OMPC_reduction);
17257         reportOriginalDsa(S, Stack, D, DVar);
17258         continue;
17259       }
17260     }
17261 
17262     // Try to find 'declare reduction' corresponding construct before using
17263     // builtin/overloaded operators.
17264     CXXCastPath BasePath;
17265     ExprResult DeclareReductionRef = buildDeclareReductionRef(
17266         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17267         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17268     if (DeclareReductionRef.isInvalid())
17269       continue;
17270     if (S.CurContext->isDependentContext() &&
17271         (DeclareReductionRef.isUnset() ||
17272          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
17273       RD.push(RefExpr, DeclareReductionRef.get());
17274       continue;
17275     }
17276     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
17277       // Not allowed reduction identifier is found.
17278       S.Diag(ReductionId.getBeginLoc(),
17279              diag::err_omp_unknown_reduction_identifier)
17280           << Type << ReductionIdRange;
17281       continue;
17282     }
17283 
17284     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17285     // The type of a list item that appears in a reduction clause must be valid
17286     // for the reduction-identifier. For a max or min reduction in C, the type
17287     // of the list item must be an allowed arithmetic data type: char, int,
17288     // float, double, or _Bool, possibly modified with long, short, signed, or
17289     // unsigned. For a max or min reduction in C++, the type of the list item
17290     // must be an allowed arithmetic data type: char, wchar_t, int, float,
17291     // double, or bool, possibly modified with long, short, signed, or unsigned.
17292     if (DeclareReductionRef.isUnset()) {
17293       if ((BOK == BO_GT || BOK == BO_LT) &&
17294           !(Type->isScalarType() ||
17295             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
17296         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
17297             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
17298         if (!ASE && !OASE) {
17299           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17300                                    VarDecl::DeclarationOnly;
17301           S.Diag(D->getLocation(),
17302                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17303               << D;
17304         }
17305         continue;
17306       }
17307       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
17308           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
17309         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
17310             << getOpenMPClauseName(ClauseKind);
17311         if (!ASE && !OASE) {
17312           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17313                                    VarDecl::DeclarationOnly;
17314           S.Diag(D->getLocation(),
17315                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17316               << D;
17317         }
17318         continue;
17319       }
17320     }
17321 
17322     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
17323     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
17324                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17325     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
17326                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17327     QualType PrivateTy = Type;
17328 
17329     // Try if we can determine constant lengths for all array sections and avoid
17330     // the VLA.
17331     bool ConstantLengthOASE = false;
17332     if (OASE) {
17333       bool SingleElement;
17334       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
17335       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
17336           Context, OASE, SingleElement, ArraySizes);
17337 
17338       // If we don't have a single element, we must emit a constant array type.
17339       if (ConstantLengthOASE && !SingleElement) {
17340         for (llvm::APSInt &Size : ArraySizes)
17341           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
17342                                                    ArrayType::Normal,
17343                                                    /*IndexTypeQuals=*/0);
17344       }
17345     }
17346 
17347     if ((OASE && !ConstantLengthOASE) ||
17348         (!OASE && !ASE &&
17349          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
17350       if (!Context.getTargetInfo().isVLASupported()) {
17351         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
17352           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17353           S.Diag(ELoc, diag::note_vla_unsupported);
17354           continue;
17355         } else {
17356           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17357           S.targetDiag(ELoc, diag::note_vla_unsupported);
17358         }
17359       }
17360       // For arrays/array sections only:
17361       // Create pseudo array type for private copy. The size for this array will
17362       // be generated during codegen.
17363       // For array subscripts or single variables Private Ty is the same as Type
17364       // (type of the variable or single array element).
17365       PrivateTy = Context.getVariableArrayType(
17366           Type,
17367           new (Context)
17368               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
17369           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
17370     } else if (!ASE && !OASE &&
17371                Context.getAsArrayType(D->getType().getNonReferenceType())) {
17372       PrivateTy = D->getType().getNonReferenceType();
17373     }
17374     // Private copy.
17375     VarDecl *PrivateVD =
17376         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17377                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17378                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17379     // Add initializer for private variable.
17380     Expr *Init = nullptr;
17381     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
17382     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
17383     if (DeclareReductionRef.isUsable()) {
17384       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
17385       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
17386       if (DRD->getInitializer()) {
17387         Init = DRDRef;
17388         RHSVD->setInit(DRDRef);
17389         RHSVD->setInitStyle(VarDecl::CallInit);
17390       }
17391     } else {
17392       switch (BOK) {
17393       case BO_Add:
17394       case BO_Xor:
17395       case BO_Or:
17396       case BO_LOr:
17397         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
17398         if (Type->isScalarType() || Type->isAnyComplexType())
17399           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
17400         break;
17401       case BO_Mul:
17402       case BO_LAnd:
17403         if (Type->isScalarType() || Type->isAnyComplexType()) {
17404           // '*' and '&&' reduction ops - initializer is '1'.
17405           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
17406         }
17407         break;
17408       case BO_And: {
17409         // '&' reduction op - initializer is '~0'.
17410         QualType OrigType = Type;
17411         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
17412           Type = ComplexTy->getElementType();
17413         if (Type->isRealFloatingType()) {
17414           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
17415               Context.getFloatTypeSemantics(Type));
17416           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17417                                          Type, ELoc);
17418         } else if (Type->isScalarType()) {
17419           uint64_t Size = Context.getTypeSize(Type);
17420           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
17421           llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
17422           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17423         }
17424         if (Init && OrigType->isAnyComplexType()) {
17425           // Init = 0xFFFF + 0xFFFFi;
17426           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
17427           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
17428         }
17429         Type = OrigType;
17430         break;
17431       }
17432       case BO_LT:
17433       case BO_GT: {
17434         // 'min' reduction op - initializer is 'Largest representable number in
17435         // the reduction list item type'.
17436         // 'max' reduction op - initializer is 'Least representable number in
17437         // the reduction list item type'.
17438         if (Type->isIntegerType() || Type->isPointerType()) {
17439           bool IsSigned = Type->hasSignedIntegerRepresentation();
17440           uint64_t Size = Context.getTypeSize(Type);
17441           QualType IntTy =
17442               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
17443           llvm::APInt InitValue =
17444               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
17445                                         : llvm::APInt::getMinValue(Size)
17446               : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
17447                              : llvm::APInt::getMaxValue(Size);
17448           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17449           if (Type->isPointerType()) {
17450             // Cast to pointer type.
17451             ExprResult CastExpr = S.BuildCStyleCastExpr(
17452                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
17453             if (CastExpr.isInvalid())
17454               continue;
17455             Init = CastExpr.get();
17456           }
17457         } else if (Type->isRealFloatingType()) {
17458           llvm::APFloat InitValue = llvm::APFloat::getLargest(
17459               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
17460           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17461                                          Type, ELoc);
17462         }
17463         break;
17464       }
17465       case BO_PtrMemD:
17466       case BO_PtrMemI:
17467       case BO_MulAssign:
17468       case BO_Div:
17469       case BO_Rem:
17470       case BO_Sub:
17471       case BO_Shl:
17472       case BO_Shr:
17473       case BO_LE:
17474       case BO_GE:
17475       case BO_EQ:
17476       case BO_NE:
17477       case BO_Cmp:
17478       case BO_AndAssign:
17479       case BO_XorAssign:
17480       case BO_OrAssign:
17481       case BO_Assign:
17482       case BO_AddAssign:
17483       case BO_SubAssign:
17484       case BO_DivAssign:
17485       case BO_RemAssign:
17486       case BO_ShlAssign:
17487       case BO_ShrAssign:
17488       case BO_Comma:
17489         llvm_unreachable("Unexpected reduction operation");
17490       }
17491     }
17492     if (Init && DeclareReductionRef.isUnset()) {
17493       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
17494       // Store initializer for single element in private copy. Will be used
17495       // during codegen.
17496       PrivateVD->setInit(RHSVD->getInit());
17497       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17498     } else if (!Init) {
17499       S.ActOnUninitializedDecl(RHSVD);
17500       // Store initializer for single element in private copy. Will be used
17501       // during codegen.
17502       PrivateVD->setInit(RHSVD->getInit());
17503       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17504     }
17505     if (RHSVD->isInvalidDecl())
17506       continue;
17507     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
17508       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
17509           << Type << ReductionIdRange;
17510       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17511                                VarDecl::DeclarationOnly;
17512       S.Diag(D->getLocation(),
17513              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17514           << D;
17515       continue;
17516     }
17517     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
17518     ExprResult ReductionOp;
17519     if (DeclareReductionRef.isUsable()) {
17520       QualType RedTy = DeclareReductionRef.get()->getType();
17521       QualType PtrRedTy = Context.getPointerType(RedTy);
17522       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
17523       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
17524       if (!BasePath.empty()) {
17525         LHS = S.DefaultLvalueConversion(LHS.get());
17526         RHS = S.DefaultLvalueConversion(RHS.get());
17527         LHS = ImplicitCastExpr::Create(
17528             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
17529             LHS.get()->getValueKind(), FPOptionsOverride());
17530         RHS = ImplicitCastExpr::Create(
17531             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
17532             RHS.get()->getValueKind(), FPOptionsOverride());
17533       }
17534       FunctionProtoType::ExtProtoInfo EPI;
17535       QualType Params[] = {PtrRedTy, PtrRedTy};
17536       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
17537       auto *OVE = new (Context) OpaqueValueExpr(
17538           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
17539           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
17540       Expr *Args[] = {LHS.get(), RHS.get()};
17541       ReductionOp =
17542           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
17543                            S.CurFPFeatureOverrides());
17544     } else {
17545       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
17546       if (Type->isRecordType() && CombBOK != BOK) {
17547         Sema::TentativeAnalysisScope Trap(S);
17548         ReductionOp =
17549             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17550                          CombBOK, LHSDRE, RHSDRE);
17551       }
17552       if (!ReductionOp.isUsable()) {
17553         ReductionOp =
17554             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
17555                          LHSDRE, RHSDRE);
17556         if (ReductionOp.isUsable()) {
17557           if (BOK != BO_LT && BOK != BO_GT) {
17558             ReductionOp =
17559                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17560                              BO_Assign, LHSDRE, ReductionOp.get());
17561           } else {
17562             auto *ConditionalOp = new (Context)
17563                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
17564                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
17565             ReductionOp =
17566                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17567                              BO_Assign, LHSDRE, ConditionalOp);
17568           }
17569         }
17570       }
17571       if (ReductionOp.isUsable())
17572         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
17573                                             /*DiscardedValue*/ false);
17574       if (!ReductionOp.isUsable())
17575         continue;
17576     }
17577 
17578     // Add copy operations for inscan reductions.
17579     // LHS = RHS;
17580     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
17581     if (ClauseKind == OMPC_reduction &&
17582         RD.RedModifier == OMPC_REDUCTION_inscan) {
17583       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
17584       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
17585                                RHS.get());
17586       if (!CopyOpRes.isUsable())
17587         continue;
17588       CopyOpRes =
17589           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
17590       if (!CopyOpRes.isUsable())
17591         continue;
17592       // For simd directive and simd-based directives in simd mode no need to
17593       // construct temp array, need just a single temp element.
17594       if (Stack->getCurrentDirective() == OMPD_simd ||
17595           (S.getLangOpts().OpenMPSimd &&
17596            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
17597         VarDecl *TempArrayVD =
17598             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17599                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17600         // Add a constructor to the temp decl.
17601         S.ActOnUninitializedDecl(TempArrayVD);
17602         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
17603       } else {
17604         // Build temp array for prefix sum.
17605         auto *Dim = new (S.Context)
17606             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17607         QualType ArrayTy =
17608             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
17609                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
17610         VarDecl *TempArrayVD =
17611             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
17612                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17613         // Add a constructor to the temp decl.
17614         S.ActOnUninitializedDecl(TempArrayVD);
17615         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
17616         TempArrayElem =
17617             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
17618         auto *Idx = new (S.Context)
17619             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17620         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
17621                                                           ELoc, Idx, ELoc);
17622       }
17623     }
17624 
17625     // OpenMP [2.15.4.6, Restrictions, p.2]
17626     // A list item that appears in an in_reduction clause of a task construct
17627     // must appear in a task_reduction clause of a construct associated with a
17628     // taskgroup region that includes the participating task in its taskgroup
17629     // set. The construct associated with the innermost region that meets this
17630     // condition must specify the same reduction-identifier as the in_reduction
17631     // clause.
17632     if (ClauseKind == OMPC_in_reduction) {
17633       SourceRange ParentSR;
17634       BinaryOperatorKind ParentBOK;
17635       const Expr *ParentReductionOp = nullptr;
17636       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
17637       DSAStackTy::DSAVarData ParentBOKDSA =
17638           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
17639                                                   ParentBOKTD);
17640       DSAStackTy::DSAVarData ParentReductionOpDSA =
17641           Stack->getTopMostTaskgroupReductionData(
17642               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
17643       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
17644       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
17645       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
17646           (DeclareReductionRef.isUsable() && IsParentBOK) ||
17647           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
17648         bool EmitError = true;
17649         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
17650           llvm::FoldingSetNodeID RedId, ParentRedId;
17651           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
17652           DeclareReductionRef.get()->Profile(RedId, Context,
17653                                              /*Canonical=*/true);
17654           EmitError = RedId != ParentRedId;
17655         }
17656         if (EmitError) {
17657           S.Diag(ReductionId.getBeginLoc(),
17658                  diag::err_omp_reduction_identifier_mismatch)
17659               << ReductionIdRange << RefExpr->getSourceRange();
17660           S.Diag(ParentSR.getBegin(),
17661                  diag::note_omp_previous_reduction_identifier)
17662               << ParentSR
17663               << (IsParentBOK ? ParentBOKDSA.RefExpr
17664                               : ParentReductionOpDSA.RefExpr)
17665                      ->getSourceRange();
17666           continue;
17667         }
17668       }
17669       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
17670     }
17671 
17672     DeclRefExpr *Ref = nullptr;
17673     Expr *VarsExpr = RefExpr->IgnoreParens();
17674     if (!VD && !S.CurContext->isDependentContext()) {
17675       if (ASE || OASE) {
17676         TransformExprToCaptures RebuildToCapture(S, D);
17677         VarsExpr =
17678             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
17679         Ref = RebuildToCapture.getCapturedExpr();
17680       } else {
17681         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
17682       }
17683       if (!S.isOpenMPCapturedDecl(D)) {
17684         RD.ExprCaptures.emplace_back(Ref->getDecl());
17685         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17686           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
17687           if (!RefRes.isUsable())
17688             continue;
17689           ExprResult PostUpdateRes =
17690               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17691                            RefRes.get());
17692           if (!PostUpdateRes.isUsable())
17693             continue;
17694           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
17695               Stack->getCurrentDirective() == OMPD_taskgroup) {
17696             S.Diag(RefExpr->getExprLoc(),
17697                    diag::err_omp_reduction_non_addressable_expression)
17698                 << RefExpr->getSourceRange();
17699             continue;
17700           }
17701           RD.ExprPostUpdates.emplace_back(
17702               S.IgnoredValueConversions(PostUpdateRes.get()).get());
17703         }
17704       }
17705     }
17706     // All reduction items are still marked as reduction (to do not increase
17707     // code base size).
17708     unsigned Modifier = RD.RedModifier;
17709     // Consider task_reductions as reductions with task modifier. Required for
17710     // correct analysis of in_reduction clauses.
17711     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
17712       Modifier = OMPC_REDUCTION_task;
17713     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
17714                   ASE || OASE);
17715     if (Modifier == OMPC_REDUCTION_task &&
17716         (CurrDir == OMPD_taskgroup ||
17717          ((isOpenMPParallelDirective(CurrDir) ||
17718            isOpenMPWorksharingDirective(CurrDir)) &&
17719           !isOpenMPSimdDirective(CurrDir)))) {
17720       if (DeclareReductionRef.isUsable())
17721         Stack->addTaskgroupReductionData(D, ReductionIdRange,
17722                                          DeclareReductionRef.get());
17723       else
17724         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
17725     }
17726     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
17727             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
17728             TempArrayElem.get());
17729   }
17730   return RD.Vars.empty();
17731 }
17732 
17733 OMPClause *Sema::ActOnOpenMPReductionClause(
17734     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
17735     SourceLocation StartLoc, SourceLocation LParenLoc,
17736     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
17737     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17738     ArrayRef<Expr *> UnresolvedReductions) {
17739   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
17740     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
17741         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
17742                                    /*Last=*/OMPC_REDUCTION_unknown)
17743         << getOpenMPClauseName(OMPC_reduction);
17744     return nullptr;
17745   }
17746   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
17747   // A reduction clause with the inscan reduction-modifier may only appear on a
17748   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
17749   // construct, a parallel worksharing-loop construct or a parallel
17750   // worksharing-loop SIMD construct.
17751   if (Modifier == OMPC_REDUCTION_inscan &&
17752       (DSAStack->getCurrentDirective() != OMPD_for &&
17753        DSAStack->getCurrentDirective() != OMPD_for_simd &&
17754        DSAStack->getCurrentDirective() != OMPD_simd &&
17755        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
17756        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
17757     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
17758     return nullptr;
17759   }
17760 
17761   ReductionData RD(VarList.size(), Modifier);
17762   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
17763                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17764                                   ReductionIdScopeSpec, ReductionId,
17765                                   UnresolvedReductions, RD))
17766     return nullptr;
17767 
17768   return OMPReductionClause::Create(
17769       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
17770       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17771       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
17772       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
17773       buildPreInits(Context, RD.ExprCaptures),
17774       buildPostUpdate(*this, RD.ExprPostUpdates));
17775 }
17776 
17777 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
17778     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17779     SourceLocation ColonLoc, SourceLocation EndLoc,
17780     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17781     ArrayRef<Expr *> UnresolvedReductions) {
17782   ReductionData RD(VarList.size());
17783   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17784                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17785                                   ReductionIdScopeSpec, ReductionId,
17786                                   UnresolvedReductions, RD))
17787     return nullptr;
17788 
17789   return OMPTaskReductionClause::Create(
17790       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17791       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17792       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17793       buildPreInits(Context, RD.ExprCaptures),
17794       buildPostUpdate(*this, RD.ExprPostUpdates));
17795 }
17796 
17797 OMPClause *Sema::ActOnOpenMPInReductionClause(
17798     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17799     SourceLocation ColonLoc, SourceLocation EndLoc,
17800     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17801     ArrayRef<Expr *> UnresolvedReductions) {
17802   ReductionData RD(VarList.size());
17803   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17804                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17805                                   ReductionIdScopeSpec, ReductionId,
17806                                   UnresolvedReductions, RD))
17807     return nullptr;
17808 
17809   return OMPInReductionClause::Create(
17810       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17811       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17812       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17813       buildPreInits(Context, RD.ExprCaptures),
17814       buildPostUpdate(*this, RD.ExprPostUpdates));
17815 }
17816 
17817 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17818                                      SourceLocation LinLoc) {
17819   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17820       LinKind == OMPC_LINEAR_unknown) {
17821     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17822     return true;
17823   }
17824   return false;
17825 }
17826 
17827 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17828                                  OpenMPLinearClauseKind LinKind, QualType Type,
17829                                  bool IsDeclareSimd) {
17830   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17831   // A variable must not have an incomplete type or a reference type.
17832   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17833     return true;
17834   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17835       !Type->isReferenceType()) {
17836     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17837         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17838     return true;
17839   }
17840   Type = Type.getNonReferenceType();
17841 
17842   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17843   // A variable that is privatized must not have a const-qualified type
17844   // unless it is of class type with a mutable member. This restriction does
17845   // not apply to the firstprivate clause, nor to the linear clause on
17846   // declarative directives (like declare simd).
17847   if (!IsDeclareSimd &&
17848       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17849     return true;
17850 
17851   // A list item must be of integral or pointer type.
17852   Type = Type.getUnqualifiedType().getCanonicalType();
17853   const auto *Ty = Type.getTypePtrOrNull();
17854   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17855               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17856     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17857     if (D) {
17858       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17859                                VarDecl::DeclarationOnly;
17860       Diag(D->getLocation(),
17861            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17862           << D;
17863     }
17864     return true;
17865   }
17866   return false;
17867 }
17868 
17869 OMPClause *Sema::ActOnOpenMPLinearClause(
17870     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17871     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17872     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17873   SmallVector<Expr *, 8> Vars;
17874   SmallVector<Expr *, 8> Privates;
17875   SmallVector<Expr *, 8> Inits;
17876   SmallVector<Decl *, 4> ExprCaptures;
17877   SmallVector<Expr *, 4> ExprPostUpdates;
17878   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17879     LinKind = OMPC_LINEAR_val;
17880   for (Expr *RefExpr : VarList) {
17881     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17882     SourceLocation ELoc;
17883     SourceRange ERange;
17884     Expr *SimpleRefExpr = RefExpr;
17885     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17886     if (Res.second) {
17887       // It will be analyzed later.
17888       Vars.push_back(RefExpr);
17889       Privates.push_back(nullptr);
17890       Inits.push_back(nullptr);
17891     }
17892     ValueDecl *D = Res.first;
17893     if (!D)
17894       continue;
17895 
17896     QualType Type = D->getType();
17897     auto *VD = dyn_cast<VarDecl>(D);
17898 
17899     // OpenMP [2.14.3.7, linear clause]
17900     //  A list-item cannot appear in more than one linear clause.
17901     //  A list-item that appears in a linear clause cannot appear in any
17902     //  other data-sharing attribute clause.
17903     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17904     if (DVar.RefExpr) {
17905       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17906                                           << getOpenMPClauseName(OMPC_linear);
17907       reportOriginalDsa(*this, DSAStack, D, DVar);
17908       continue;
17909     }
17910 
17911     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17912       continue;
17913     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17914 
17915     // Build private copy of original var.
17916     VarDecl *Private =
17917         buildVarDecl(*this, ELoc, Type, D->getName(),
17918                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17919                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17920     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17921     // Build var to save initial value.
17922     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17923     Expr *InitExpr;
17924     DeclRefExpr *Ref = nullptr;
17925     if (!VD && !CurContext->isDependentContext()) {
17926       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17927       if (!isOpenMPCapturedDecl(D)) {
17928         ExprCaptures.push_back(Ref->getDecl());
17929         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17930           ExprResult RefRes = DefaultLvalueConversion(Ref);
17931           if (!RefRes.isUsable())
17932             continue;
17933           ExprResult PostUpdateRes =
17934               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17935                          SimpleRefExpr, RefRes.get());
17936           if (!PostUpdateRes.isUsable())
17937             continue;
17938           ExprPostUpdates.push_back(
17939               IgnoredValueConversions(PostUpdateRes.get()).get());
17940         }
17941       }
17942     }
17943     if (LinKind == OMPC_LINEAR_uval)
17944       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17945     else
17946       InitExpr = VD ? SimpleRefExpr : Ref;
17947     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17948                          /*DirectInit=*/false);
17949     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17950 
17951     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17952     Vars.push_back((VD || CurContext->isDependentContext())
17953                        ? RefExpr->IgnoreParens()
17954                        : Ref);
17955     Privates.push_back(PrivateRef);
17956     Inits.push_back(InitRef);
17957   }
17958 
17959   if (Vars.empty())
17960     return nullptr;
17961 
17962   Expr *StepExpr = Step;
17963   Expr *CalcStepExpr = nullptr;
17964   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17965       !Step->isInstantiationDependent() &&
17966       !Step->containsUnexpandedParameterPack()) {
17967     SourceLocation StepLoc = Step->getBeginLoc();
17968     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17969     if (Val.isInvalid())
17970       return nullptr;
17971     StepExpr = Val.get();
17972 
17973     // Build var to save the step value.
17974     VarDecl *SaveVar =
17975         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17976     ExprResult SaveRef =
17977         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17978     ExprResult CalcStep =
17979         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17980     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17981 
17982     // Warn about zero linear step (it would be probably better specified as
17983     // making corresponding variables 'const').
17984     if (Optional<llvm::APSInt> Result =
17985             StepExpr->getIntegerConstantExpr(Context)) {
17986       if (!Result->isNegative() && !Result->isStrictlyPositive())
17987         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17988             << Vars[0] << (Vars.size() > 1);
17989     } else if (CalcStep.isUsable()) {
17990       // Calculate the step beforehand instead of doing this on each iteration.
17991       // (This is not used if the number of iterations may be kfold-ed).
17992       CalcStepExpr = CalcStep.get();
17993     }
17994   }
17995 
17996   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17997                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17998                                  StepExpr, CalcStepExpr,
17999                                  buildPreInits(Context, ExprCaptures),
18000                                  buildPostUpdate(*this, ExprPostUpdates));
18001 }
18002 
18003 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
18004                                      Expr *NumIterations, Sema &SemaRef,
18005                                      Scope *S, DSAStackTy *Stack) {
18006   // Walk the vars and build update/final expressions for the CodeGen.
18007   SmallVector<Expr *, 8> Updates;
18008   SmallVector<Expr *, 8> Finals;
18009   SmallVector<Expr *, 8> UsedExprs;
18010   Expr *Step = Clause.getStep();
18011   Expr *CalcStep = Clause.getCalcStep();
18012   // OpenMP [2.14.3.7, linear clause]
18013   // If linear-step is not specified it is assumed to be 1.
18014   if (!Step)
18015     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
18016   else if (CalcStep)
18017     Step = cast<BinaryOperator>(CalcStep)->getLHS();
18018   bool HasErrors = false;
18019   auto CurInit = Clause.inits().begin();
18020   auto CurPrivate = Clause.privates().begin();
18021   OpenMPLinearClauseKind LinKind = Clause.getModifier();
18022   for (Expr *RefExpr : Clause.varlists()) {
18023     SourceLocation ELoc;
18024     SourceRange ERange;
18025     Expr *SimpleRefExpr = RefExpr;
18026     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
18027     ValueDecl *D = Res.first;
18028     if (Res.second || !D) {
18029       Updates.push_back(nullptr);
18030       Finals.push_back(nullptr);
18031       HasErrors = true;
18032       continue;
18033     }
18034     auto &&Info = Stack->isLoopControlVariable(D);
18035     // OpenMP [2.15.11, distribute simd Construct]
18036     // A list item may not appear in a linear clause, unless it is the loop
18037     // iteration variable.
18038     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
18039         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
18040       SemaRef.Diag(ELoc,
18041                    diag::err_omp_linear_distribute_var_non_loop_iteration);
18042       Updates.push_back(nullptr);
18043       Finals.push_back(nullptr);
18044       HasErrors = true;
18045       continue;
18046     }
18047     Expr *InitExpr = *CurInit;
18048 
18049     // Build privatized reference to the current linear var.
18050     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
18051     Expr *CapturedRef;
18052     if (LinKind == OMPC_LINEAR_uval)
18053       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
18054     else
18055       CapturedRef =
18056           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
18057                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
18058                            /*RefersToCapture=*/true);
18059 
18060     // Build update: Var = InitExpr + IV * Step
18061     ExprResult Update;
18062     if (!Info.first)
18063       Update = buildCounterUpdate(
18064           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
18065           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
18066     else
18067       Update = *CurPrivate;
18068     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
18069                                          /*DiscardedValue*/ false);
18070 
18071     // Build final: Var = PrivCopy;
18072     ExprResult Final;
18073     if (!Info.first)
18074       Final = SemaRef.BuildBinOp(
18075           S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
18076           SemaRef.DefaultLvalueConversion(*CurPrivate).get());
18077     else
18078       Final = *CurPrivate;
18079     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
18080                                         /*DiscardedValue*/ false);
18081 
18082     if (!Update.isUsable() || !Final.isUsable()) {
18083       Updates.push_back(nullptr);
18084       Finals.push_back(nullptr);
18085       UsedExprs.push_back(nullptr);
18086       HasErrors = true;
18087     } else {
18088       Updates.push_back(Update.get());
18089       Finals.push_back(Final.get());
18090       if (!Info.first)
18091         UsedExprs.push_back(SimpleRefExpr);
18092     }
18093     ++CurInit;
18094     ++CurPrivate;
18095   }
18096   if (Expr *S = Clause.getStep())
18097     UsedExprs.push_back(S);
18098   // Fill the remaining part with the nullptr.
18099   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
18100   Clause.setUpdates(Updates);
18101   Clause.setFinals(Finals);
18102   Clause.setUsedExprs(UsedExprs);
18103   return HasErrors;
18104 }
18105 
18106 OMPClause *Sema::ActOnOpenMPAlignedClause(
18107     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
18108     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
18109   SmallVector<Expr *, 8> Vars;
18110   for (Expr *RefExpr : VarList) {
18111     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18112     SourceLocation ELoc;
18113     SourceRange ERange;
18114     Expr *SimpleRefExpr = RefExpr;
18115     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18116     if (Res.second) {
18117       // It will be analyzed later.
18118       Vars.push_back(RefExpr);
18119     }
18120     ValueDecl *D = Res.first;
18121     if (!D)
18122       continue;
18123 
18124     QualType QType = D->getType();
18125     auto *VD = dyn_cast<VarDecl>(D);
18126 
18127     // OpenMP  [2.8.1, simd construct, Restrictions]
18128     // The type of list items appearing in the aligned clause must be
18129     // array, pointer, reference to array, or reference to pointer.
18130     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
18131     const Type *Ty = QType.getTypePtrOrNull();
18132     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
18133       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
18134           << QType << getLangOpts().CPlusPlus << ERange;
18135       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18136                                VarDecl::DeclarationOnly;
18137       Diag(D->getLocation(),
18138            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18139           << D;
18140       continue;
18141     }
18142 
18143     // OpenMP  [2.8.1, simd construct, Restrictions]
18144     // A list-item cannot appear in more than one aligned clause.
18145     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
18146       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18147           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
18148       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18149           << getOpenMPClauseName(OMPC_aligned);
18150       continue;
18151     }
18152 
18153     DeclRefExpr *Ref = nullptr;
18154     if (!VD && isOpenMPCapturedDecl(D))
18155       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18156     Vars.push_back(DefaultFunctionArrayConversion(
18157                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
18158                        .get());
18159   }
18160 
18161   // OpenMP [2.8.1, simd construct, Description]
18162   // The parameter of the aligned clause, alignment, must be a constant
18163   // positive integer expression.
18164   // If no optional parameter is specified, implementation-defined default
18165   // alignments for SIMD instructions on the target platforms are assumed.
18166   if (Alignment != nullptr) {
18167     ExprResult AlignResult =
18168         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
18169     if (AlignResult.isInvalid())
18170       return nullptr;
18171     Alignment = AlignResult.get();
18172   }
18173   if (Vars.empty())
18174     return nullptr;
18175 
18176   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
18177                                   EndLoc, Vars, Alignment);
18178 }
18179 
18180 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
18181                                          SourceLocation StartLoc,
18182                                          SourceLocation LParenLoc,
18183                                          SourceLocation EndLoc) {
18184   SmallVector<Expr *, 8> Vars;
18185   SmallVector<Expr *, 8> SrcExprs;
18186   SmallVector<Expr *, 8> DstExprs;
18187   SmallVector<Expr *, 8> AssignmentOps;
18188   for (Expr *RefExpr : VarList) {
18189     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
18190     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18191       // It will be analyzed later.
18192       Vars.push_back(RefExpr);
18193       SrcExprs.push_back(nullptr);
18194       DstExprs.push_back(nullptr);
18195       AssignmentOps.push_back(nullptr);
18196       continue;
18197     }
18198 
18199     SourceLocation ELoc = RefExpr->getExprLoc();
18200     // OpenMP [2.1, C/C++]
18201     //  A list item is a variable name.
18202     // OpenMP  [2.14.4.1, Restrictions, p.1]
18203     //  A list item that appears in a copyin clause must be threadprivate.
18204     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
18205     if (!DE || !isa<VarDecl>(DE->getDecl())) {
18206       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
18207           << 0 << RefExpr->getSourceRange();
18208       continue;
18209     }
18210 
18211     Decl *D = DE->getDecl();
18212     auto *VD = cast<VarDecl>(D);
18213 
18214     QualType Type = VD->getType();
18215     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
18216       // It will be analyzed later.
18217       Vars.push_back(DE);
18218       SrcExprs.push_back(nullptr);
18219       DstExprs.push_back(nullptr);
18220       AssignmentOps.push_back(nullptr);
18221       continue;
18222     }
18223 
18224     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
18225     //  A list item that appears in a copyin clause must be threadprivate.
18226     if (!DSAStack->isThreadPrivate(VD)) {
18227       Diag(ELoc, diag::err_omp_required_access)
18228           << getOpenMPClauseName(OMPC_copyin)
18229           << getOpenMPDirectiveName(OMPD_threadprivate);
18230       continue;
18231     }
18232 
18233     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18234     //  A variable of class type (or array thereof) that appears in a
18235     //  copyin clause requires an accessible, unambiguous copy assignment
18236     //  operator for the class type.
18237     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
18238     VarDecl *SrcVD =
18239         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
18240                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18241     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
18242         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
18243     VarDecl *DstVD =
18244         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
18245                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18246     DeclRefExpr *PseudoDstExpr =
18247         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
18248     // For arrays generate assignment operation for single element and replace
18249     // it by the original array element in CodeGen.
18250     ExprResult AssignmentOp =
18251         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
18252                    PseudoSrcExpr);
18253     if (AssignmentOp.isInvalid())
18254       continue;
18255     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
18256                                        /*DiscardedValue*/ false);
18257     if (AssignmentOp.isInvalid())
18258       continue;
18259 
18260     DSAStack->addDSA(VD, DE, OMPC_copyin);
18261     Vars.push_back(DE);
18262     SrcExprs.push_back(PseudoSrcExpr);
18263     DstExprs.push_back(PseudoDstExpr);
18264     AssignmentOps.push_back(AssignmentOp.get());
18265   }
18266 
18267   if (Vars.empty())
18268     return nullptr;
18269 
18270   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
18271                                  SrcExprs, DstExprs, AssignmentOps);
18272 }
18273 
18274 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
18275                                               SourceLocation StartLoc,
18276                                               SourceLocation LParenLoc,
18277                                               SourceLocation EndLoc) {
18278   SmallVector<Expr *, 8> Vars;
18279   SmallVector<Expr *, 8> SrcExprs;
18280   SmallVector<Expr *, 8> DstExprs;
18281   SmallVector<Expr *, 8> AssignmentOps;
18282   for (Expr *RefExpr : VarList) {
18283     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18284     SourceLocation ELoc;
18285     SourceRange ERange;
18286     Expr *SimpleRefExpr = RefExpr;
18287     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18288     if (Res.second) {
18289       // It will be analyzed later.
18290       Vars.push_back(RefExpr);
18291       SrcExprs.push_back(nullptr);
18292       DstExprs.push_back(nullptr);
18293       AssignmentOps.push_back(nullptr);
18294     }
18295     ValueDecl *D = Res.first;
18296     if (!D)
18297       continue;
18298 
18299     QualType Type = D->getType();
18300     auto *VD = dyn_cast<VarDecl>(D);
18301 
18302     // OpenMP [2.14.4.2, Restrictions, p.2]
18303     //  A list item that appears in a copyprivate clause may not appear in a
18304     //  private or firstprivate clause on the single construct.
18305     if (!VD || !DSAStack->isThreadPrivate(VD)) {
18306       DSAStackTy::DSAVarData DVar =
18307           DSAStack->getTopDSA(D, /*FromParent=*/false);
18308       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
18309           DVar.RefExpr) {
18310         Diag(ELoc, diag::err_omp_wrong_dsa)
18311             << getOpenMPClauseName(DVar.CKind)
18312             << getOpenMPClauseName(OMPC_copyprivate);
18313         reportOriginalDsa(*this, DSAStack, D, DVar);
18314         continue;
18315       }
18316 
18317       // OpenMP [2.11.4.2, Restrictions, p.1]
18318       //  All list items that appear in a copyprivate clause must be either
18319       //  threadprivate or private in the enclosing context.
18320       if (DVar.CKind == OMPC_unknown) {
18321         DVar = DSAStack->getImplicitDSA(D, false);
18322         if (DVar.CKind == OMPC_shared) {
18323           Diag(ELoc, diag::err_omp_required_access)
18324               << getOpenMPClauseName(OMPC_copyprivate)
18325               << "threadprivate or private in the enclosing context";
18326           reportOriginalDsa(*this, DSAStack, D, DVar);
18327           continue;
18328         }
18329       }
18330     }
18331 
18332     // Variably modified types are not supported.
18333     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
18334       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
18335           << getOpenMPClauseName(OMPC_copyprivate) << Type
18336           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18337       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18338                                VarDecl::DeclarationOnly;
18339       Diag(D->getLocation(),
18340            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18341           << D;
18342       continue;
18343     }
18344 
18345     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18346     //  A variable of class type (or array thereof) that appears in a
18347     //  copyin clause requires an accessible, unambiguous copy assignment
18348     //  operator for the class type.
18349     Type = Context.getBaseElementType(Type.getNonReferenceType())
18350                .getUnqualifiedType();
18351     VarDecl *SrcVD =
18352         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
18353                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18354     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
18355     VarDecl *DstVD =
18356         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
18357                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18358     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
18359     ExprResult AssignmentOp = BuildBinOp(
18360         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
18361     if (AssignmentOp.isInvalid())
18362       continue;
18363     AssignmentOp =
18364         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
18365     if (AssignmentOp.isInvalid())
18366       continue;
18367 
18368     // No need to mark vars as copyprivate, they are already threadprivate or
18369     // implicitly private.
18370     assert(VD || isOpenMPCapturedDecl(D));
18371     Vars.push_back(
18372         VD ? RefExpr->IgnoreParens()
18373            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
18374     SrcExprs.push_back(PseudoSrcExpr);
18375     DstExprs.push_back(PseudoDstExpr);
18376     AssignmentOps.push_back(AssignmentOp.get());
18377   }
18378 
18379   if (Vars.empty())
18380     return nullptr;
18381 
18382   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18383                                       Vars, SrcExprs, DstExprs, AssignmentOps);
18384 }
18385 
18386 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
18387                                         SourceLocation StartLoc,
18388                                         SourceLocation LParenLoc,
18389                                         SourceLocation EndLoc) {
18390   if (VarList.empty())
18391     return nullptr;
18392 
18393   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
18394 }
18395 
18396 /// Tries to find omp_depend_t. type.
18397 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
18398                            bool Diagnose = true) {
18399   QualType OMPDependT = Stack->getOMPDependT();
18400   if (!OMPDependT.isNull())
18401     return true;
18402   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
18403   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18404   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18405     if (Diagnose)
18406       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
18407     return false;
18408   }
18409   Stack->setOMPDependT(PT.get());
18410   return true;
18411 }
18412 
18413 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
18414                                          SourceLocation LParenLoc,
18415                                          SourceLocation EndLoc) {
18416   if (!Depobj)
18417     return nullptr;
18418 
18419   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
18420 
18421   // OpenMP 5.0, 2.17.10.1 depobj Construct
18422   // depobj is an lvalue expression of type omp_depend_t.
18423   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
18424       !Depobj->isInstantiationDependent() &&
18425       !Depobj->containsUnexpandedParameterPack() &&
18426       (OMPDependTFound &&
18427        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
18428                                    /*CompareUnqualified=*/true))) {
18429     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18430         << 0 << Depobj->getType() << Depobj->getSourceRange();
18431   }
18432 
18433   if (!Depobj->isLValue()) {
18434     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18435         << 1 << Depobj->getSourceRange();
18436   }
18437 
18438   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
18439 }
18440 
18441 OMPClause *
18442 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
18443                               SourceLocation DepLoc, SourceLocation ColonLoc,
18444                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18445                               SourceLocation LParenLoc, SourceLocation EndLoc) {
18446   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
18447       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
18448     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18449         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
18450     return nullptr;
18451   }
18452   if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
18453       DepKind == OMPC_DEPEND_mutexinoutset) {
18454     Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
18455     return nullptr;
18456   }
18457   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
18458        DSAStack->getCurrentDirective() == OMPD_depobj) &&
18459       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
18460        DepKind == OMPC_DEPEND_sink ||
18461        ((LangOpts.OpenMP < 50 ||
18462          DSAStack->getCurrentDirective() == OMPD_depobj) &&
18463         DepKind == OMPC_DEPEND_depobj))) {
18464     SmallVector<unsigned, 3> Except;
18465     Except.push_back(OMPC_DEPEND_source);
18466     Except.push_back(OMPC_DEPEND_sink);
18467     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
18468       Except.push_back(OMPC_DEPEND_depobj);
18469     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
18470                                ? "depend modifier(iterator) or "
18471                                : "";
18472     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18473         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
18474                                               /*Last=*/OMPC_DEPEND_unknown,
18475                                               Except)
18476         << getOpenMPClauseName(OMPC_depend);
18477     return nullptr;
18478   }
18479   if (DepModifier &&
18480       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
18481     Diag(DepModifier->getExprLoc(),
18482          diag::err_omp_depend_sink_source_with_modifier);
18483     return nullptr;
18484   }
18485   if (DepModifier &&
18486       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
18487     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
18488 
18489   SmallVector<Expr *, 8> Vars;
18490   DSAStackTy::OperatorOffsetTy OpsOffs;
18491   llvm::APSInt DepCounter(/*BitWidth=*/32);
18492   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
18493   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
18494     if (const Expr *OrderedCountExpr =
18495             DSAStack->getParentOrderedRegionParam().first) {
18496       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
18497       TotalDepCount.setIsUnsigned(/*Val=*/true);
18498     }
18499   }
18500   for (Expr *RefExpr : VarList) {
18501     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18502     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18503       // It will be analyzed later.
18504       Vars.push_back(RefExpr);
18505       continue;
18506     }
18507 
18508     SourceLocation ELoc = RefExpr->getExprLoc();
18509     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
18510     if (DepKind == OMPC_DEPEND_sink) {
18511       if (DSAStack->getParentOrderedRegionParam().first &&
18512           DepCounter >= TotalDepCount) {
18513         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
18514         continue;
18515       }
18516       ++DepCounter;
18517       // OpenMP  [2.13.9, Summary]
18518       // depend(dependence-type : vec), where dependence-type is:
18519       // 'sink' and where vec is the iteration vector, which has the form:
18520       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
18521       // where n is the value specified by the ordered clause in the loop
18522       // directive, xi denotes the loop iteration variable of the i-th nested
18523       // loop associated with the loop directive, and di is a constant
18524       // non-negative integer.
18525       if (CurContext->isDependentContext()) {
18526         // It will be analyzed later.
18527         Vars.push_back(RefExpr);
18528         continue;
18529       }
18530       SimpleExpr = SimpleExpr->IgnoreImplicit();
18531       OverloadedOperatorKind OOK = OO_None;
18532       SourceLocation OOLoc;
18533       Expr *LHS = SimpleExpr;
18534       Expr *RHS = nullptr;
18535       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
18536         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
18537         OOLoc = BO->getOperatorLoc();
18538         LHS = BO->getLHS()->IgnoreParenImpCasts();
18539         RHS = BO->getRHS()->IgnoreParenImpCasts();
18540       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
18541         OOK = OCE->getOperator();
18542         OOLoc = OCE->getOperatorLoc();
18543         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18544         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
18545       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
18546         OOK = MCE->getMethodDecl()
18547                   ->getNameInfo()
18548                   .getName()
18549                   .getCXXOverloadedOperator();
18550         OOLoc = MCE->getCallee()->getExprLoc();
18551         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
18552         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18553       }
18554       SourceLocation ELoc;
18555       SourceRange ERange;
18556       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
18557       if (Res.second) {
18558         // It will be analyzed later.
18559         Vars.push_back(RefExpr);
18560       }
18561       ValueDecl *D = Res.first;
18562       if (!D)
18563         continue;
18564 
18565       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
18566         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
18567         continue;
18568       }
18569       if (RHS) {
18570         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
18571             RHS, OMPC_depend, /*StrictlyPositive=*/false);
18572         if (RHSRes.isInvalid())
18573           continue;
18574       }
18575       if (!CurContext->isDependentContext() &&
18576           DSAStack->getParentOrderedRegionParam().first &&
18577           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
18578         const ValueDecl *VD =
18579             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
18580         if (VD)
18581           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
18582               << 1 << VD;
18583         else
18584           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
18585         continue;
18586       }
18587       OpsOffs.emplace_back(RHS, OOK);
18588     } else {
18589       bool OMPDependTFound = LangOpts.OpenMP >= 50;
18590       if (OMPDependTFound)
18591         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
18592                                          DepKind == OMPC_DEPEND_depobj);
18593       if (DepKind == OMPC_DEPEND_depobj) {
18594         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18595         // List items used in depend clauses with the depobj dependence type
18596         // must be expressions of the omp_depend_t type.
18597         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18598             !RefExpr->isInstantiationDependent() &&
18599             !RefExpr->containsUnexpandedParameterPack() &&
18600             (OMPDependTFound &&
18601              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
18602                                              RefExpr->getType()))) {
18603           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18604               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
18605           continue;
18606         }
18607         if (!RefExpr->isLValue()) {
18608           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18609               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
18610           continue;
18611         }
18612       } else {
18613         // OpenMP 5.0 [2.17.11, Restrictions]
18614         // List items used in depend clauses cannot be zero-length array
18615         // sections.
18616         QualType ExprTy = RefExpr->getType().getNonReferenceType();
18617         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
18618         if (OASE) {
18619           QualType BaseType =
18620               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18621           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18622             ExprTy = ATy->getElementType();
18623           else
18624             ExprTy = BaseType->getPointeeType();
18625           ExprTy = ExprTy.getNonReferenceType();
18626           const Expr *Length = OASE->getLength();
18627           Expr::EvalResult Result;
18628           if (Length && !Length->isValueDependent() &&
18629               Length->EvaluateAsInt(Result, Context) &&
18630               Result.Val.getInt().isZero()) {
18631             Diag(ELoc,
18632                  diag::err_omp_depend_zero_length_array_section_not_allowed)
18633                 << SimpleExpr->getSourceRange();
18634             continue;
18635           }
18636         }
18637 
18638         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18639         // List items used in depend clauses with the in, out, inout or
18640         // mutexinoutset dependence types cannot be expressions of the
18641         // omp_depend_t type.
18642         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18643             !RefExpr->isInstantiationDependent() &&
18644             !RefExpr->containsUnexpandedParameterPack() &&
18645             (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
18646              (OMPDependTFound &&
18647               DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
18648           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18649               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18650               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18651           continue;
18652         }
18653 
18654         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
18655         if (ASE && !ASE->getBase()->isTypeDependent() &&
18656             !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
18657             !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
18658           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18659               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18660               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18661           continue;
18662         }
18663 
18664         ExprResult Res;
18665         {
18666           Sema::TentativeAnalysisScope Trap(*this);
18667           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
18668                                      RefExpr->IgnoreParenImpCasts());
18669         }
18670         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18671             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18672           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18673               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18674               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18675           continue;
18676         }
18677       }
18678     }
18679     Vars.push_back(RefExpr->IgnoreParenImpCasts());
18680   }
18681 
18682   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
18683       TotalDepCount > VarList.size() &&
18684       DSAStack->getParentOrderedRegionParam().first &&
18685       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
18686     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
18687         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
18688   }
18689   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
18690       Vars.empty())
18691     return nullptr;
18692 
18693   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18694                                     DepModifier, DepKind, DepLoc, ColonLoc,
18695                                     Vars, TotalDepCount.getZExtValue());
18696   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
18697       DSAStack->isParentOrderedRegion())
18698     DSAStack->addDoacrossDependClause(C, OpsOffs);
18699   return C;
18700 }
18701 
18702 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
18703                                          Expr *Device, SourceLocation StartLoc,
18704                                          SourceLocation LParenLoc,
18705                                          SourceLocation ModifierLoc,
18706                                          SourceLocation EndLoc) {
18707   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
18708          "Unexpected device modifier in OpenMP < 50.");
18709 
18710   bool ErrorFound = false;
18711   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
18712     std::string Values =
18713         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
18714     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
18715         << Values << getOpenMPClauseName(OMPC_device);
18716     ErrorFound = true;
18717   }
18718 
18719   Expr *ValExpr = Device;
18720   Stmt *HelperValStmt = nullptr;
18721 
18722   // OpenMP [2.9.1, Restrictions]
18723   // The device expression must evaluate to a non-negative integer value.
18724   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
18725                                           /*StrictlyPositive=*/false) ||
18726                ErrorFound;
18727   if (ErrorFound)
18728     return nullptr;
18729 
18730   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18731   OpenMPDirectiveKind CaptureRegion =
18732       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
18733   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18734     ValExpr = MakeFullExpr(ValExpr).get();
18735     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18736     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18737     HelperValStmt = buildPreInits(Context, Captures);
18738   }
18739 
18740   return new (Context)
18741       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18742                       LParenLoc, ModifierLoc, EndLoc);
18743 }
18744 
18745 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
18746                               DSAStackTy *Stack, QualType QTy,
18747                               bool FullCheck = true) {
18748   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
18749     return false;
18750   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
18751       !QTy.isTriviallyCopyableType(SemaRef.Context))
18752     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
18753   return true;
18754 }
18755 
18756 /// Return true if it can be proven that the provided array expression
18757 /// (array section or array subscript) does NOT specify the whole size of the
18758 /// array whose base type is \a BaseQTy.
18759 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
18760                                                         const Expr *E,
18761                                                         QualType BaseQTy) {
18762   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18763 
18764   // If this is an array subscript, it refers to the whole size if the size of
18765   // the dimension is constant and equals 1. Also, an array section assumes the
18766   // format of an array subscript if no colon is used.
18767   if (isa<ArraySubscriptExpr>(E) ||
18768       (OASE && OASE->getColonLocFirst().isInvalid())) {
18769     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18770       return ATy->getSize().getSExtValue() != 1;
18771     // Size can't be evaluated statically.
18772     return false;
18773   }
18774 
18775   assert(OASE && "Expecting array section if not an array subscript.");
18776   const Expr *LowerBound = OASE->getLowerBound();
18777   const Expr *Length = OASE->getLength();
18778 
18779   // If there is a lower bound that does not evaluates to zero, we are not
18780   // covering the whole dimension.
18781   if (LowerBound) {
18782     Expr::EvalResult Result;
18783     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18784       return false; // Can't get the integer value as a constant.
18785 
18786     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18787     if (ConstLowerBound.getSExtValue())
18788       return true;
18789   }
18790 
18791   // If we don't have a length we covering the whole dimension.
18792   if (!Length)
18793     return false;
18794 
18795   // If the base is a pointer, we don't have a way to get the size of the
18796   // pointee.
18797   if (BaseQTy->isPointerType())
18798     return false;
18799 
18800   // We can only check if the length is the same as the size of the dimension
18801   // if we have a constant array.
18802   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18803   if (!CATy)
18804     return false;
18805 
18806   Expr::EvalResult Result;
18807   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18808     return false; // Can't get the integer value as a constant.
18809 
18810   llvm::APSInt ConstLength = Result.Val.getInt();
18811   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18812 }
18813 
18814 // Return true if it can be proven that the provided array expression (array
18815 // section or array subscript) does NOT specify a single element of the array
18816 // whose base type is \a BaseQTy.
18817 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18818                                                         const Expr *E,
18819                                                         QualType BaseQTy) {
18820   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18821 
18822   // An array subscript always refer to a single element. Also, an array section
18823   // assumes the format of an array subscript if no colon is used.
18824   if (isa<ArraySubscriptExpr>(E) ||
18825       (OASE && OASE->getColonLocFirst().isInvalid()))
18826     return false;
18827 
18828   assert(OASE && "Expecting array section if not an array subscript.");
18829   const Expr *Length = OASE->getLength();
18830 
18831   // If we don't have a length we have to check if the array has unitary size
18832   // for this dimension. Also, we should always expect a length if the base type
18833   // is pointer.
18834   if (!Length) {
18835     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18836       return ATy->getSize().getSExtValue() != 1;
18837     // We cannot assume anything.
18838     return false;
18839   }
18840 
18841   // Check if the length evaluates to 1.
18842   Expr::EvalResult Result;
18843   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18844     return false; // Can't get the integer value as a constant.
18845 
18846   llvm::APSInt ConstLength = Result.Val.getInt();
18847   return ConstLength.getSExtValue() != 1;
18848 }
18849 
18850 // The base of elements of list in a map clause have to be either:
18851 //  - a reference to variable or field.
18852 //  - a member expression.
18853 //  - an array expression.
18854 //
18855 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18856 // reference to 'r'.
18857 //
18858 // If we have:
18859 //
18860 // struct SS {
18861 //   Bla S;
18862 //   foo() {
18863 //     #pragma omp target map (S.Arr[:12]);
18864 //   }
18865 // }
18866 //
18867 // We want to retrieve the member expression 'this->S';
18868 
18869 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18870 //  If a list item is an array section, it must specify contiguous storage.
18871 //
18872 // For this restriction it is sufficient that we make sure only references
18873 // to variables or fields and array expressions, and that no array sections
18874 // exist except in the rightmost expression (unless they cover the whole
18875 // dimension of the array). E.g. these would be invalid:
18876 //
18877 //   r.ArrS[3:5].Arr[6:7]
18878 //
18879 //   r.ArrS[3:5].x
18880 //
18881 // but these would be valid:
18882 //   r.ArrS[3].Arr[6:7]
18883 //
18884 //   r.ArrS[3].x
18885 namespace {
18886 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18887   Sema &SemaRef;
18888   OpenMPClauseKind CKind = OMPC_unknown;
18889   OpenMPDirectiveKind DKind = OMPD_unknown;
18890   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18891   bool IsNonContiguous = false;
18892   bool NoDiagnose = false;
18893   const Expr *RelevantExpr = nullptr;
18894   bool AllowUnitySizeArraySection = true;
18895   bool AllowWholeSizeArraySection = true;
18896   bool AllowAnotherPtr = true;
18897   SourceLocation ELoc;
18898   SourceRange ERange;
18899 
18900   void emitErrorMsg() {
18901     // If nothing else worked, this is not a valid map clause expression.
18902     if (SemaRef.getLangOpts().OpenMP < 50) {
18903       SemaRef.Diag(ELoc,
18904                    diag::err_omp_expected_named_var_member_or_array_expression)
18905           << ERange;
18906     } else {
18907       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18908           << getOpenMPClauseName(CKind) << ERange;
18909     }
18910   }
18911 
18912 public:
18913   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18914     if (!isa<VarDecl>(DRE->getDecl())) {
18915       emitErrorMsg();
18916       return false;
18917     }
18918     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18919     RelevantExpr = DRE;
18920     // Record the component.
18921     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18922     return true;
18923   }
18924 
18925   bool VisitMemberExpr(MemberExpr *ME) {
18926     Expr *E = ME;
18927     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18928 
18929     if (isa<CXXThisExpr>(BaseE)) {
18930       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18931       // We found a base expression: this->Val.
18932       RelevantExpr = ME;
18933     } else {
18934       E = BaseE;
18935     }
18936 
18937     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18938       if (!NoDiagnose) {
18939         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18940             << ME->getSourceRange();
18941         return false;
18942       }
18943       if (RelevantExpr)
18944         return false;
18945       return Visit(E);
18946     }
18947 
18948     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18949 
18950     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18951     //  A bit-field cannot appear in a map clause.
18952     //
18953     if (FD->isBitField()) {
18954       if (!NoDiagnose) {
18955         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18956             << ME->getSourceRange() << getOpenMPClauseName(CKind);
18957         return false;
18958       }
18959       if (RelevantExpr)
18960         return false;
18961       return Visit(E);
18962     }
18963 
18964     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18965     //  If the type of a list item is a reference to a type T then the type
18966     //  will be considered to be T for all purposes of this clause.
18967     QualType CurType = BaseE->getType().getNonReferenceType();
18968 
18969     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18970     //  A list item cannot be a variable that is a member of a structure with
18971     //  a union type.
18972     //
18973     if (CurType->isUnionType()) {
18974       if (!NoDiagnose) {
18975         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18976             << ME->getSourceRange();
18977         return false;
18978       }
18979       return RelevantExpr || Visit(E);
18980     }
18981 
18982     // If we got a member expression, we should not expect any array section
18983     // before that:
18984     //
18985     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18986     //  If a list item is an element of a structure, only the rightmost symbol
18987     //  of the variable reference can be an array section.
18988     //
18989     AllowUnitySizeArraySection = false;
18990     AllowWholeSizeArraySection = false;
18991 
18992     // Record the component.
18993     Components.emplace_back(ME, FD, IsNonContiguous);
18994     return RelevantExpr || Visit(E);
18995   }
18996 
18997   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18998     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18999 
19000     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
19001       if (!NoDiagnose) {
19002         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19003             << 0 << AE->getSourceRange();
19004         return false;
19005       }
19006       return RelevantExpr || Visit(E);
19007     }
19008 
19009     // If we got an array subscript that express the whole dimension we
19010     // can have any array expressions before. If it only expressing part of
19011     // the dimension, we can only have unitary-size array expressions.
19012     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
19013       AllowWholeSizeArraySection = false;
19014 
19015     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
19016       Expr::EvalResult Result;
19017       if (!AE->getIdx()->isValueDependent() &&
19018           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
19019           !Result.Val.getInt().isZero()) {
19020         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19021                      diag::err_omp_invalid_map_this_expr);
19022         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19023                      diag::note_omp_invalid_subscript_on_this_ptr_map);
19024       }
19025       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19026       RelevantExpr = TE;
19027     }
19028 
19029     // Record the component - we don't have any declaration associated.
19030     Components.emplace_back(AE, nullptr, IsNonContiguous);
19031 
19032     return RelevantExpr || Visit(E);
19033   }
19034 
19035   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
19036     // After OMP 5.0  Array section in reduction clause will be implicitly
19037     // mapped
19038     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
19039            "Array sections cannot be implicitly mapped.");
19040     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19041     QualType CurType =
19042         OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19043 
19044     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19045     //  If the type of a list item is a reference to a type T then the type
19046     //  will be considered to be T for all purposes of this clause.
19047     if (CurType->isReferenceType())
19048       CurType = CurType->getPointeeType();
19049 
19050     bool IsPointer = CurType->isAnyPointerType();
19051 
19052     if (!IsPointer && !CurType->isArrayType()) {
19053       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19054           << 0 << OASE->getSourceRange();
19055       return false;
19056     }
19057 
19058     bool NotWhole =
19059         checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
19060     bool NotUnity =
19061         checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
19062 
19063     if (AllowWholeSizeArraySection) {
19064       // Any array section is currently allowed. Allowing a whole size array
19065       // section implies allowing a unity array section as well.
19066       //
19067       // If this array section refers to the whole dimension we can still
19068       // accept other array sections before this one, except if the base is a
19069       // pointer. Otherwise, only unitary sections are accepted.
19070       if (NotWhole || IsPointer)
19071         AllowWholeSizeArraySection = false;
19072     } else if (DKind == OMPD_target_update &&
19073                SemaRef.getLangOpts().OpenMP >= 50) {
19074       if (IsPointer && !AllowAnotherPtr)
19075         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
19076             << /*array of unknown bound */ 1;
19077       else
19078         IsNonContiguous = true;
19079     } else if (AllowUnitySizeArraySection && NotUnity) {
19080       // A unity or whole array section is not allowed and that is not
19081       // compatible with the properties of the current array section.
19082       if (NoDiagnose)
19083         return false;
19084       SemaRef.Diag(ELoc,
19085                    diag::err_array_section_does_not_specify_contiguous_storage)
19086           << OASE->getSourceRange();
19087       return false;
19088     }
19089 
19090     if (IsPointer)
19091       AllowAnotherPtr = false;
19092 
19093     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
19094       Expr::EvalResult ResultR;
19095       Expr::EvalResult ResultL;
19096       if (!OASE->getLength()->isValueDependent() &&
19097           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
19098           !ResultR.Val.getInt().isOne()) {
19099         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19100                      diag::err_omp_invalid_map_this_expr);
19101         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19102                      diag::note_omp_invalid_length_on_this_ptr_mapping);
19103       }
19104       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
19105           OASE->getLowerBound()->EvaluateAsInt(ResultL,
19106                                                SemaRef.getASTContext()) &&
19107           !ResultL.Val.getInt().isZero()) {
19108         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19109                      diag::err_omp_invalid_map_this_expr);
19110         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19111                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
19112       }
19113       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19114       RelevantExpr = TE;
19115     }
19116 
19117     // Record the component - we don't have any declaration associated.
19118     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
19119     return RelevantExpr || Visit(E);
19120   }
19121   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
19122     Expr *Base = E->getBase();
19123 
19124     // Record the component - we don't have any declaration associated.
19125     Components.emplace_back(E, nullptr, IsNonContiguous);
19126 
19127     return Visit(Base->IgnoreParenImpCasts());
19128   }
19129 
19130   bool VisitUnaryOperator(UnaryOperator *UO) {
19131     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
19132         UO->getOpcode() != UO_Deref) {
19133       emitErrorMsg();
19134       return false;
19135     }
19136     if (!RelevantExpr) {
19137       // Record the component if haven't found base decl.
19138       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
19139     }
19140     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
19141   }
19142   bool VisitBinaryOperator(BinaryOperator *BO) {
19143     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
19144       emitErrorMsg();
19145       return false;
19146     }
19147 
19148     // Pointer arithmetic is the only thing we expect to happen here so after we
19149     // make sure the binary operator is a pointer type, the we only thing need
19150     // to to is to visit the subtree that has the same type as root (so that we
19151     // know the other subtree is just an offset)
19152     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
19153     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
19154     Components.emplace_back(BO, nullptr, false);
19155     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
19156             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
19157            "Either LHS or RHS have base decl inside");
19158     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
19159       return RelevantExpr || Visit(LE);
19160     return RelevantExpr || Visit(RE);
19161   }
19162   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
19163     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19164     RelevantExpr = CTE;
19165     Components.emplace_back(CTE, nullptr, IsNonContiguous);
19166     return true;
19167   }
19168   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
19169     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19170     Components.emplace_back(COCE, nullptr, IsNonContiguous);
19171     return true;
19172   }
19173   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
19174     Expr *Source = E->getSourceExpr();
19175     if (!Source) {
19176       emitErrorMsg();
19177       return false;
19178     }
19179     return Visit(Source);
19180   }
19181   bool VisitStmt(Stmt *) {
19182     emitErrorMsg();
19183     return false;
19184   }
19185   const Expr *getFoundBase() const { return RelevantExpr; }
19186   explicit MapBaseChecker(
19187       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
19188       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
19189       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
19190       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
19191         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
19192 };
19193 } // namespace
19194 
19195 /// Return the expression of the base of the mappable expression or null if it
19196 /// cannot be determined and do all the necessary checks to see if the
19197 /// expression is valid as a standalone mappable expression. In the process,
19198 /// record all the components of the expression.
19199 static const Expr *checkMapClauseExpressionBase(
19200     Sema &SemaRef, Expr *E,
19201     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
19202     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
19203   SourceLocation ELoc = E->getExprLoc();
19204   SourceRange ERange = E->getSourceRange();
19205   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
19206                          ERange);
19207   if (Checker.Visit(E->IgnoreParens())) {
19208     // Check if the highest dimension array section has length specified
19209     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
19210         (CKind == OMPC_to || CKind == OMPC_from)) {
19211       auto CI = CurComponents.rbegin();
19212       auto CE = CurComponents.rend();
19213       for (; CI != CE; ++CI) {
19214         const auto *OASE =
19215             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
19216         if (!OASE)
19217           continue;
19218         if (OASE && OASE->getLength())
19219           break;
19220         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
19221             << ERange;
19222       }
19223     }
19224     return Checker.getFoundBase();
19225   }
19226   return nullptr;
19227 }
19228 
19229 // Return true if expression E associated with value VD has conflicts with other
19230 // map information.
19231 static bool checkMapConflicts(
19232     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
19233     bool CurrentRegionOnly,
19234     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
19235     OpenMPClauseKind CKind) {
19236   assert(VD && E);
19237   SourceLocation ELoc = E->getExprLoc();
19238   SourceRange ERange = E->getSourceRange();
19239 
19240   // In order to easily check the conflicts we need to match each component of
19241   // the expression under test with the components of the expressions that are
19242   // already in the stack.
19243 
19244   assert(!CurComponents.empty() && "Map clause expression with no components!");
19245   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
19246          "Map clause expression with unexpected base!");
19247 
19248   // Variables to help detecting enclosing problems in data environment nests.
19249   bool IsEnclosedByDataEnvironmentExpr = false;
19250   const Expr *EnclosingExpr = nullptr;
19251 
19252   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
19253       VD, CurrentRegionOnly,
19254       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
19255        ERange, CKind, &EnclosingExpr,
19256        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
19257                           StackComponents,
19258                       OpenMPClauseKind Kind) {
19259         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
19260           return false;
19261         assert(!StackComponents.empty() &&
19262                "Map clause expression with no components!");
19263         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
19264                "Map clause expression with unexpected base!");
19265         (void)VD;
19266 
19267         // The whole expression in the stack.
19268         const Expr *RE = StackComponents.front().getAssociatedExpression();
19269 
19270         // Expressions must start from the same base. Here we detect at which
19271         // point both expressions diverge from each other and see if we can
19272         // detect if the memory referred to both expressions is contiguous and
19273         // do not overlap.
19274         auto CI = CurComponents.rbegin();
19275         auto CE = CurComponents.rend();
19276         auto SI = StackComponents.rbegin();
19277         auto SE = StackComponents.rend();
19278         for (; CI != CE && SI != SE; ++CI, ++SI) {
19279 
19280           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
19281           //  At most one list item can be an array item derived from a given
19282           //  variable in map clauses of the same construct.
19283           if (CurrentRegionOnly &&
19284               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
19285                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
19286                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
19287               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
19288                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
19289                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
19290             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
19291                          diag::err_omp_multiple_array_items_in_map_clause)
19292                 << CI->getAssociatedExpression()->getSourceRange();
19293             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
19294                          diag::note_used_here)
19295                 << SI->getAssociatedExpression()->getSourceRange();
19296             return true;
19297           }
19298 
19299           // Do both expressions have the same kind?
19300           if (CI->getAssociatedExpression()->getStmtClass() !=
19301               SI->getAssociatedExpression()->getStmtClass())
19302             break;
19303 
19304           // Are we dealing with different variables/fields?
19305           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
19306             break;
19307         }
19308         // Check if the extra components of the expressions in the enclosing
19309         // data environment are redundant for the current base declaration.
19310         // If they are, the maps completely overlap, which is legal.
19311         for (; SI != SE; ++SI) {
19312           QualType Type;
19313           if (const auto *ASE =
19314                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
19315             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
19316           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
19317                          SI->getAssociatedExpression())) {
19318             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19319             Type =
19320                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19321           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
19322                          SI->getAssociatedExpression())) {
19323             Type = OASE->getBase()->getType()->getPointeeType();
19324           }
19325           if (Type.isNull() || Type->isAnyPointerType() ||
19326               checkArrayExpressionDoesNotReferToWholeSize(
19327                   SemaRef, SI->getAssociatedExpression(), Type))
19328             break;
19329         }
19330 
19331         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19332         //  List items of map clauses in the same construct must not share
19333         //  original storage.
19334         //
19335         // If the expressions are exactly the same or one is a subset of the
19336         // other, it means they are sharing storage.
19337         if (CI == CE && SI == SE) {
19338           if (CurrentRegionOnly) {
19339             if (CKind == OMPC_map) {
19340               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19341             } else {
19342               assert(CKind == OMPC_to || CKind == OMPC_from);
19343               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19344                   << ERange;
19345             }
19346             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19347                 << RE->getSourceRange();
19348             return true;
19349           }
19350           // If we find the same expression in the enclosing data environment,
19351           // that is legal.
19352           IsEnclosedByDataEnvironmentExpr = true;
19353           return false;
19354         }
19355 
19356         QualType DerivedType =
19357             std::prev(CI)->getAssociatedDeclaration()->getType();
19358         SourceLocation DerivedLoc =
19359             std::prev(CI)->getAssociatedExpression()->getExprLoc();
19360 
19361         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19362         //  If the type of a list item is a reference to a type T then the type
19363         //  will be considered to be T for all purposes of this clause.
19364         DerivedType = DerivedType.getNonReferenceType();
19365 
19366         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
19367         //  A variable for which the type is pointer and an array section
19368         //  derived from that variable must not appear as list items of map
19369         //  clauses of the same construct.
19370         //
19371         // Also, cover one of the cases in:
19372         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19373         //  If any part of the original storage of a list item has corresponding
19374         //  storage in the device data environment, all of the original storage
19375         //  must have corresponding storage in the device data environment.
19376         //
19377         if (DerivedType->isAnyPointerType()) {
19378           if (CI == CE || SI == SE) {
19379             SemaRef.Diag(
19380                 DerivedLoc,
19381                 diag::err_omp_pointer_mapped_along_with_derived_section)
19382                 << DerivedLoc;
19383             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19384                 << RE->getSourceRange();
19385             return true;
19386           }
19387           if (CI->getAssociatedExpression()->getStmtClass() !=
19388                   SI->getAssociatedExpression()->getStmtClass() ||
19389               CI->getAssociatedDeclaration()->getCanonicalDecl() ==
19390                   SI->getAssociatedDeclaration()->getCanonicalDecl()) {
19391             assert(CI != CE && SI != SE);
19392             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
19393                 << DerivedLoc;
19394             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19395                 << RE->getSourceRange();
19396             return true;
19397           }
19398         }
19399 
19400         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19401         //  List items of map clauses in the same construct must not share
19402         //  original storage.
19403         //
19404         // An expression is a subset of the other.
19405         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
19406           if (CKind == OMPC_map) {
19407             if (CI != CE || SI != SE) {
19408               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
19409               // a pointer.
19410               auto Begin =
19411                   CI != CE ? CurComponents.begin() : StackComponents.begin();
19412               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
19413               auto It = Begin;
19414               while (It != End && !It->getAssociatedDeclaration())
19415                 std::advance(It, 1);
19416               assert(It != End &&
19417                      "Expected at least one component with the declaration.");
19418               if (It != Begin && It->getAssociatedDeclaration()
19419                                      ->getType()
19420                                      .getCanonicalType()
19421                                      ->isAnyPointerType()) {
19422                 IsEnclosedByDataEnvironmentExpr = false;
19423                 EnclosingExpr = nullptr;
19424                 return false;
19425               }
19426             }
19427             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19428           } else {
19429             assert(CKind == OMPC_to || CKind == OMPC_from);
19430             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19431                 << ERange;
19432           }
19433           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19434               << RE->getSourceRange();
19435           return true;
19436         }
19437 
19438         // The current expression uses the same base as other expression in the
19439         // data environment but does not contain it completely.
19440         if (!CurrentRegionOnly && SI != SE)
19441           EnclosingExpr = RE;
19442 
19443         // The current expression is a subset of the expression in the data
19444         // environment.
19445         IsEnclosedByDataEnvironmentExpr |=
19446             (!CurrentRegionOnly && CI != CE && SI == SE);
19447 
19448         return false;
19449       });
19450 
19451   if (CurrentRegionOnly)
19452     return FoundError;
19453 
19454   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19455   //  If any part of the original storage of a list item has corresponding
19456   //  storage in the device data environment, all of the original storage must
19457   //  have corresponding storage in the device data environment.
19458   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
19459   //  If a list item is an element of a structure, and a different element of
19460   //  the structure has a corresponding list item in the device data environment
19461   //  prior to a task encountering the construct associated with the map clause,
19462   //  then the list item must also have a corresponding list item in the device
19463   //  data environment prior to the task encountering the construct.
19464   //
19465   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
19466     SemaRef.Diag(ELoc,
19467                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
19468         << ERange;
19469     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
19470         << EnclosingExpr->getSourceRange();
19471     return true;
19472   }
19473 
19474   return FoundError;
19475 }
19476 
19477 // Look up the user-defined mapper given the mapper name and mapped type, and
19478 // build a reference to it.
19479 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
19480                                             CXXScopeSpec &MapperIdScopeSpec,
19481                                             const DeclarationNameInfo &MapperId,
19482                                             QualType Type,
19483                                             Expr *UnresolvedMapper) {
19484   if (MapperIdScopeSpec.isInvalid())
19485     return ExprError();
19486   // Get the actual type for the array type.
19487   if (Type->isArrayType()) {
19488     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
19489     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
19490   }
19491   // Find all user-defined mappers with the given MapperId.
19492   SmallVector<UnresolvedSet<8>, 4> Lookups;
19493   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
19494   Lookup.suppressDiagnostics();
19495   if (S) {
19496     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
19497       NamedDecl *D = Lookup.getRepresentativeDecl();
19498       while (S && !S->isDeclScope(D))
19499         S = S->getParent();
19500       if (S)
19501         S = S->getParent();
19502       Lookups.emplace_back();
19503       Lookups.back().append(Lookup.begin(), Lookup.end());
19504       Lookup.clear();
19505     }
19506   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
19507     // Extract the user-defined mappers with the given MapperId.
19508     Lookups.push_back(UnresolvedSet<8>());
19509     for (NamedDecl *D : ULE->decls()) {
19510       auto *DMD = cast<OMPDeclareMapperDecl>(D);
19511       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
19512       Lookups.back().addDecl(DMD);
19513     }
19514   }
19515   // Defer the lookup for dependent types. The results will be passed through
19516   // UnresolvedMapper on instantiation.
19517   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
19518       Type->isInstantiationDependentType() ||
19519       Type->containsUnexpandedParameterPack() ||
19520       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
19521         return !D->isInvalidDecl() &&
19522                (D->getType()->isDependentType() ||
19523                 D->getType()->isInstantiationDependentType() ||
19524                 D->getType()->containsUnexpandedParameterPack());
19525       })) {
19526     UnresolvedSet<8> URS;
19527     for (const UnresolvedSet<8> &Set : Lookups) {
19528       if (Set.empty())
19529         continue;
19530       URS.append(Set.begin(), Set.end());
19531     }
19532     return UnresolvedLookupExpr::Create(
19533         SemaRef.Context, /*NamingClass=*/nullptr,
19534         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
19535         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
19536   }
19537   SourceLocation Loc = MapperId.getLoc();
19538   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19539   //  The type must be of struct, union or class type in C and C++
19540   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
19541       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
19542     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
19543     return ExprError();
19544   }
19545   // Perform argument dependent lookup.
19546   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
19547     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
19548   // Return the first user-defined mapper with the desired type.
19549   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19550           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
19551             if (!D->isInvalidDecl() &&
19552                 SemaRef.Context.hasSameType(D->getType(), Type))
19553               return D;
19554             return nullptr;
19555           }))
19556     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19557   // Find the first user-defined mapper with a type derived from the desired
19558   // type.
19559   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19560           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
19561             if (!D->isInvalidDecl() &&
19562                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
19563                 !Type.isMoreQualifiedThan(D->getType()))
19564               return D;
19565             return nullptr;
19566           })) {
19567     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
19568                        /*DetectVirtual=*/false);
19569     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
19570       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
19571               VD->getType().getUnqualifiedType()))) {
19572         if (SemaRef.CheckBaseClassAccess(
19573                 Loc, VD->getType(), Type, Paths.front(),
19574                 /*DiagID=*/0) != Sema::AR_inaccessible) {
19575           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19576         }
19577       }
19578     }
19579   }
19580   // Report error if a mapper is specified, but cannot be found.
19581   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
19582     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
19583         << Type << MapperId.getName();
19584     return ExprError();
19585   }
19586   return ExprEmpty();
19587 }
19588 
19589 namespace {
19590 // Utility struct that gathers all the related lists associated with a mappable
19591 // expression.
19592 struct MappableVarListInfo {
19593   // The list of expressions.
19594   ArrayRef<Expr *> VarList;
19595   // The list of processed expressions.
19596   SmallVector<Expr *, 16> ProcessedVarList;
19597   // The mappble components for each expression.
19598   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
19599   // The base declaration of the variable.
19600   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
19601   // The reference to the user-defined mapper associated with every expression.
19602   SmallVector<Expr *, 16> UDMapperList;
19603 
19604   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
19605     // We have a list of components and base declarations for each entry in the
19606     // variable list.
19607     VarComponents.reserve(VarList.size());
19608     VarBaseDeclarations.reserve(VarList.size());
19609   }
19610 };
19611 } // namespace
19612 
19613 // Check the validity of the provided variable list for the provided clause kind
19614 // \a CKind. In the check process the valid expressions, mappable expression
19615 // components, variables, and user-defined mappers are extracted and used to
19616 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
19617 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
19618 // and \a MapperId are expected to be valid if the clause kind is 'map'.
19619 static void checkMappableExpressionList(
19620     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
19621     MappableVarListInfo &MVLI, SourceLocation StartLoc,
19622     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
19623     ArrayRef<Expr *> UnresolvedMappers,
19624     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
19625     ArrayRef<OpenMPMapModifierKind> Modifiers = None,
19626     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
19627   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
19628   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
19629          "Unexpected clause kind with mappable expressions!");
19630 
19631   // If the identifier of user-defined mapper is not specified, it is "default".
19632   // We do not change the actual name in this clause to distinguish whether a
19633   // mapper is specified explicitly, i.e., it is not explicitly specified when
19634   // MapperId.getName() is empty.
19635   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
19636     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
19637     MapperId.setName(DeclNames.getIdentifier(
19638         &SemaRef.getASTContext().Idents.get("default")));
19639     MapperId.setLoc(StartLoc);
19640   }
19641 
19642   // Iterators to find the current unresolved mapper expression.
19643   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
19644   bool UpdateUMIt = false;
19645   Expr *UnresolvedMapper = nullptr;
19646 
19647   bool HasHoldModifier =
19648       llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
19649 
19650   // Keep track of the mappable components and base declarations in this clause.
19651   // Each entry in the list is going to have a list of components associated. We
19652   // record each set of the components so that we can build the clause later on.
19653   // In the end we should have the same amount of declarations and component
19654   // lists.
19655 
19656   for (Expr *RE : MVLI.VarList) {
19657     assert(RE && "Null expr in omp to/from/map clause");
19658     SourceLocation ELoc = RE->getExprLoc();
19659 
19660     // Find the current unresolved mapper expression.
19661     if (UpdateUMIt && UMIt != UMEnd) {
19662       UMIt++;
19663       assert(
19664           UMIt != UMEnd &&
19665           "Expect the size of UnresolvedMappers to match with that of VarList");
19666     }
19667     UpdateUMIt = true;
19668     if (UMIt != UMEnd)
19669       UnresolvedMapper = *UMIt;
19670 
19671     const Expr *VE = RE->IgnoreParenLValueCasts();
19672 
19673     if (VE->isValueDependent() || VE->isTypeDependent() ||
19674         VE->isInstantiationDependent() ||
19675         VE->containsUnexpandedParameterPack()) {
19676       // Try to find the associated user-defined mapper.
19677       ExprResult ER = buildUserDefinedMapperRef(
19678           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19679           VE->getType().getCanonicalType(), UnresolvedMapper);
19680       if (ER.isInvalid())
19681         continue;
19682       MVLI.UDMapperList.push_back(ER.get());
19683       // We can only analyze this information once the missing information is
19684       // resolved.
19685       MVLI.ProcessedVarList.push_back(RE);
19686       continue;
19687     }
19688 
19689     Expr *SimpleExpr = RE->IgnoreParenCasts();
19690 
19691     if (!RE->isLValue()) {
19692       if (SemaRef.getLangOpts().OpenMP < 50) {
19693         SemaRef.Diag(
19694             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
19695             << RE->getSourceRange();
19696       } else {
19697         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19698             << getOpenMPClauseName(CKind) << RE->getSourceRange();
19699       }
19700       continue;
19701     }
19702 
19703     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
19704     ValueDecl *CurDeclaration = nullptr;
19705 
19706     // Obtain the array or member expression bases if required. Also, fill the
19707     // components array with all the components identified in the process.
19708     const Expr *BE =
19709         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
19710                                      DSAS->getCurrentDirective(), NoDiagnose);
19711     if (!BE)
19712       continue;
19713 
19714     assert(!CurComponents.empty() &&
19715            "Invalid mappable expression information.");
19716 
19717     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
19718       // Add store "this" pointer to class in DSAStackTy for future checking
19719       DSAS->addMappedClassesQualTypes(TE->getType());
19720       // Try to find the associated user-defined mapper.
19721       ExprResult ER = buildUserDefinedMapperRef(
19722           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19723           VE->getType().getCanonicalType(), UnresolvedMapper);
19724       if (ER.isInvalid())
19725         continue;
19726       MVLI.UDMapperList.push_back(ER.get());
19727       // Skip restriction checking for variable or field declarations
19728       MVLI.ProcessedVarList.push_back(RE);
19729       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19730       MVLI.VarComponents.back().append(CurComponents.begin(),
19731                                        CurComponents.end());
19732       MVLI.VarBaseDeclarations.push_back(nullptr);
19733       continue;
19734     }
19735 
19736     // For the following checks, we rely on the base declaration which is
19737     // expected to be associated with the last component. The declaration is
19738     // expected to be a variable or a field (if 'this' is being mapped).
19739     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
19740     assert(CurDeclaration && "Null decl on map clause.");
19741     assert(
19742         CurDeclaration->isCanonicalDecl() &&
19743         "Expecting components to have associated only canonical declarations.");
19744 
19745     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
19746     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
19747 
19748     assert((VD || FD) && "Only variables or fields are expected here!");
19749     (void)FD;
19750 
19751     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
19752     // threadprivate variables cannot appear in a map clause.
19753     // OpenMP 4.5 [2.10.5, target update Construct]
19754     // threadprivate variables cannot appear in a from clause.
19755     if (VD && DSAS->isThreadPrivate(VD)) {
19756       if (NoDiagnose)
19757         continue;
19758       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19759       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
19760           << getOpenMPClauseName(CKind);
19761       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
19762       continue;
19763     }
19764 
19765     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19766     //  A list item cannot appear in both a map clause and a data-sharing
19767     //  attribute clause on the same construct.
19768 
19769     // Check conflicts with other map clause expressions. We check the conflicts
19770     // with the current construct separately from the enclosing data
19771     // environment, because the restrictions are different. We only have to
19772     // check conflicts across regions for the map clauses.
19773     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19774                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
19775       break;
19776     if (CKind == OMPC_map &&
19777         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
19778         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19779                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
19780       break;
19781 
19782     // OpenMP 4.5 [2.10.5, target update Construct]
19783     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19784     //  If the type of a list item is a reference to a type T then the type will
19785     //  be considered to be T for all purposes of this clause.
19786     auto I = llvm::find_if(
19787         CurComponents,
19788         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19789           return MC.getAssociatedDeclaration();
19790         });
19791     assert(I != CurComponents.end() && "Null decl on map clause.");
19792     (void)I;
19793     QualType Type;
19794     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19795     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19796     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19797     if (ASE) {
19798       Type = ASE->getType().getNonReferenceType();
19799     } else if (OASE) {
19800       QualType BaseType =
19801           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19802       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19803         Type = ATy->getElementType();
19804       else
19805         Type = BaseType->getPointeeType();
19806       Type = Type.getNonReferenceType();
19807     } else if (OAShE) {
19808       Type = OAShE->getBase()->getType()->getPointeeType();
19809     } else {
19810       Type = VE->getType();
19811     }
19812 
19813     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19814     // A list item in a to or from clause must have a mappable type.
19815     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19816     //  A list item must have a mappable type.
19817     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19818                            DSAS, Type, /*FullCheck=*/true))
19819       continue;
19820 
19821     if (CKind == OMPC_map) {
19822       // target enter data
19823       // OpenMP [2.10.2, Restrictions, p. 99]
19824       // A map-type must be specified in all map clauses and must be either
19825       // to or alloc.
19826       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19827       if (DKind == OMPD_target_enter_data &&
19828           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19829         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19830             << (IsMapTypeImplicit ? 1 : 0)
19831             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19832             << getOpenMPDirectiveName(DKind);
19833         continue;
19834       }
19835 
19836       // target exit_data
19837       // OpenMP [2.10.3, Restrictions, p. 102]
19838       // A map-type must be specified in all map clauses and must be either
19839       // from, release, or delete.
19840       if (DKind == OMPD_target_exit_data &&
19841           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19842             MapType == OMPC_MAP_delete)) {
19843         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19844             << (IsMapTypeImplicit ? 1 : 0)
19845             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19846             << getOpenMPDirectiveName(DKind);
19847         continue;
19848       }
19849 
19850       // The 'ompx_hold' modifier is specifically intended to be used on a
19851       // 'target' or 'target data' directive to prevent data from being unmapped
19852       // during the associated statement.  It is not permitted on a 'target
19853       // enter data' or 'target exit data' directive, which have no associated
19854       // statement.
19855       if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
19856           HasHoldModifier) {
19857         SemaRef.Diag(StartLoc,
19858                      diag::err_omp_invalid_map_type_modifier_for_directive)
19859             << getOpenMPSimpleClauseTypeName(OMPC_map,
19860                                              OMPC_MAP_MODIFIER_ompx_hold)
19861             << getOpenMPDirectiveName(DKind);
19862         continue;
19863       }
19864 
19865       // target, target data
19866       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19867       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19868       // A map-type in a map clause must be to, from, tofrom or alloc
19869       if ((DKind == OMPD_target_data ||
19870            isOpenMPTargetExecutionDirective(DKind)) &&
19871           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19872             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19873         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19874             << (IsMapTypeImplicit ? 1 : 0)
19875             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19876             << getOpenMPDirectiveName(DKind);
19877         continue;
19878       }
19879 
19880       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19881       // A list item cannot appear in both a map clause and a data-sharing
19882       // attribute clause on the same construct
19883       //
19884       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19885       // A list item cannot appear in both a map clause and a data-sharing
19886       // attribute clause on the same construct unless the construct is a
19887       // combined construct.
19888       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19889                   isOpenMPTargetExecutionDirective(DKind)) ||
19890                  DKind == OMPD_target)) {
19891         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19892         if (isOpenMPPrivate(DVar.CKind)) {
19893           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19894               << getOpenMPClauseName(DVar.CKind)
19895               << getOpenMPClauseName(OMPC_map)
19896               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19897           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19898           continue;
19899         }
19900       }
19901     }
19902 
19903     // Try to find the associated user-defined mapper.
19904     ExprResult ER = buildUserDefinedMapperRef(
19905         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19906         Type.getCanonicalType(), UnresolvedMapper);
19907     if (ER.isInvalid())
19908       continue;
19909     MVLI.UDMapperList.push_back(ER.get());
19910 
19911     // Save the current expression.
19912     MVLI.ProcessedVarList.push_back(RE);
19913 
19914     // Store the components in the stack so that they can be used to check
19915     // against other clauses later on.
19916     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19917                                           /*WhereFoundClauseKind=*/OMPC_map);
19918 
19919     // Save the components and declaration to create the clause. For purposes of
19920     // the clause creation, any component list that has has base 'this' uses
19921     // null as base declaration.
19922     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19923     MVLI.VarComponents.back().append(CurComponents.begin(),
19924                                      CurComponents.end());
19925     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19926                                                            : CurDeclaration);
19927   }
19928 }
19929 
19930 OMPClause *Sema::ActOnOpenMPMapClause(
19931     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19932     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19933     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19934     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19935     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19936     const OMPVarListLocTy &Locs, bool NoDiagnose,
19937     ArrayRef<Expr *> UnresolvedMappers) {
19938   OpenMPMapModifierKind Modifiers[] = {
19939       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19940       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19941       OMPC_MAP_MODIFIER_unknown};
19942   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19943 
19944   // Process map-type-modifiers, flag errors for duplicate modifiers.
19945   unsigned Count = 0;
19946   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19947     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19948         llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
19949       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19950       continue;
19951     }
19952     assert(Count < NumberOfOMPMapClauseModifiers &&
19953            "Modifiers exceed the allowed number of map type modifiers");
19954     Modifiers[Count] = MapTypeModifiers[I];
19955     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19956     ++Count;
19957   }
19958 
19959   MappableVarListInfo MVLI(VarList);
19960   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19961                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19962                               MapType, Modifiers, IsMapTypeImplicit,
19963                               NoDiagnose);
19964 
19965   // We need to produce a map clause even if we don't have variables so that
19966   // other diagnostics related with non-existing map clauses are accurate.
19967   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19968                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19969                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19970                               MapperIdScopeSpec.getWithLocInContext(Context),
19971                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19972 }
19973 
19974 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19975                                                TypeResult ParsedType) {
19976   assert(ParsedType.isUsable());
19977 
19978   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19979   if (ReductionType.isNull())
19980     return QualType();
19981 
19982   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19983   // A type name in a declare reduction directive cannot be a function type, an
19984   // array type, a reference type, or a type qualified with const, volatile or
19985   // restrict.
19986   if (ReductionType.hasQualifiers()) {
19987     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19988     return QualType();
19989   }
19990 
19991   if (ReductionType->isFunctionType()) {
19992     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19993     return QualType();
19994   }
19995   if (ReductionType->isReferenceType()) {
19996     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19997     return QualType();
19998   }
19999   if (ReductionType->isArrayType()) {
20000     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
20001     return QualType();
20002   }
20003   return ReductionType;
20004 }
20005 
20006 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
20007     Scope *S, DeclContext *DC, DeclarationName Name,
20008     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
20009     AccessSpecifier AS, Decl *PrevDeclInScope) {
20010   SmallVector<Decl *, 8> Decls;
20011   Decls.reserve(ReductionTypes.size());
20012 
20013   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
20014                       forRedeclarationInCurContext());
20015   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
20016   // A reduction-identifier may not be re-declared in the current scope for the
20017   // same type or for a type that is compatible according to the base language
20018   // rules.
20019   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20020   OMPDeclareReductionDecl *PrevDRD = nullptr;
20021   bool InCompoundScope = true;
20022   if (S != nullptr) {
20023     // Find previous declaration with the same name not referenced in other
20024     // declarations.
20025     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20026     InCompoundScope =
20027         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20028     LookupName(Lookup, S);
20029     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20030                          /*AllowInlineNamespace=*/false);
20031     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
20032     LookupResult::Filter Filter = Lookup.makeFilter();
20033     while (Filter.hasNext()) {
20034       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
20035       if (InCompoundScope) {
20036         auto I = UsedAsPrevious.find(PrevDecl);
20037         if (I == UsedAsPrevious.end())
20038           UsedAsPrevious[PrevDecl] = false;
20039         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
20040           UsedAsPrevious[D] = true;
20041       }
20042       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20043           PrevDecl->getLocation();
20044     }
20045     Filter.done();
20046     if (InCompoundScope) {
20047       for (const auto &PrevData : UsedAsPrevious) {
20048         if (!PrevData.second) {
20049           PrevDRD = PrevData.first;
20050           break;
20051         }
20052       }
20053     }
20054   } else if (PrevDeclInScope != nullptr) {
20055     auto *PrevDRDInScope = PrevDRD =
20056         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
20057     do {
20058       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
20059           PrevDRDInScope->getLocation();
20060       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
20061     } while (PrevDRDInScope != nullptr);
20062   }
20063   for (const auto &TyData : ReductionTypes) {
20064     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
20065     bool Invalid = false;
20066     if (I != PreviousRedeclTypes.end()) {
20067       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
20068           << TyData.first;
20069       Diag(I->second, diag::note_previous_definition);
20070       Invalid = true;
20071     }
20072     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
20073     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
20074                                                 Name, TyData.first, PrevDRD);
20075     DC->addDecl(DRD);
20076     DRD->setAccess(AS);
20077     Decls.push_back(DRD);
20078     if (Invalid)
20079       DRD->setInvalidDecl();
20080     else
20081       PrevDRD = DRD;
20082   }
20083 
20084   return DeclGroupPtrTy::make(
20085       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
20086 }
20087 
20088 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
20089   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20090 
20091   // Enter new function scope.
20092   PushFunctionScope();
20093   setFunctionHasBranchProtectedScope();
20094   getCurFunction()->setHasOMPDeclareReductionCombiner();
20095 
20096   if (S != nullptr)
20097     PushDeclContext(S, DRD);
20098   else
20099     CurContext = DRD;
20100 
20101   PushExpressionEvaluationContext(
20102       ExpressionEvaluationContext::PotentiallyEvaluated);
20103 
20104   QualType ReductionType = DRD->getType();
20105   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
20106   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
20107   // uses semantics of argument handles by value, but it should be passed by
20108   // reference. C lang does not support references, so pass all parameters as
20109   // pointers.
20110   // Create 'T omp_in;' variable.
20111   VarDecl *OmpInParm =
20112       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
20113   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
20114   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
20115   // uses semantics of argument handles by value, but it should be passed by
20116   // reference. C lang does not support references, so pass all parameters as
20117   // pointers.
20118   // Create 'T omp_out;' variable.
20119   VarDecl *OmpOutParm =
20120       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
20121   if (S != nullptr) {
20122     PushOnScopeChains(OmpInParm, S);
20123     PushOnScopeChains(OmpOutParm, S);
20124   } else {
20125     DRD->addDecl(OmpInParm);
20126     DRD->addDecl(OmpOutParm);
20127   }
20128   Expr *InE =
20129       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
20130   Expr *OutE =
20131       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
20132   DRD->setCombinerData(InE, OutE);
20133 }
20134 
20135 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
20136   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20137   DiscardCleanupsInEvaluationContext();
20138   PopExpressionEvaluationContext();
20139 
20140   PopDeclContext();
20141   PopFunctionScopeInfo();
20142 
20143   if (Combiner != nullptr)
20144     DRD->setCombiner(Combiner);
20145   else
20146     DRD->setInvalidDecl();
20147 }
20148 
20149 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
20150   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20151 
20152   // Enter new function scope.
20153   PushFunctionScope();
20154   setFunctionHasBranchProtectedScope();
20155 
20156   if (S != nullptr)
20157     PushDeclContext(S, DRD);
20158   else
20159     CurContext = DRD;
20160 
20161   PushExpressionEvaluationContext(
20162       ExpressionEvaluationContext::PotentiallyEvaluated);
20163 
20164   QualType ReductionType = DRD->getType();
20165   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
20166   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
20167   // uses semantics of argument handles by value, but it should be passed by
20168   // reference. C lang does not support references, so pass all parameters as
20169   // pointers.
20170   // Create 'T omp_priv;' variable.
20171   VarDecl *OmpPrivParm =
20172       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
20173   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
20174   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
20175   // uses semantics of argument handles by value, but it should be passed by
20176   // reference. C lang does not support references, so pass all parameters as
20177   // pointers.
20178   // Create 'T omp_orig;' variable.
20179   VarDecl *OmpOrigParm =
20180       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
20181   if (S != nullptr) {
20182     PushOnScopeChains(OmpPrivParm, S);
20183     PushOnScopeChains(OmpOrigParm, S);
20184   } else {
20185     DRD->addDecl(OmpPrivParm);
20186     DRD->addDecl(OmpOrigParm);
20187   }
20188   Expr *OrigE =
20189       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
20190   Expr *PrivE =
20191       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
20192   DRD->setInitializerData(OrigE, PrivE);
20193   return OmpPrivParm;
20194 }
20195 
20196 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
20197                                                      VarDecl *OmpPrivParm) {
20198   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20199   DiscardCleanupsInEvaluationContext();
20200   PopExpressionEvaluationContext();
20201 
20202   PopDeclContext();
20203   PopFunctionScopeInfo();
20204 
20205   if (Initializer != nullptr) {
20206     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
20207   } else if (OmpPrivParm->hasInit()) {
20208     DRD->setInitializer(OmpPrivParm->getInit(),
20209                         OmpPrivParm->isDirectInit()
20210                             ? OMPDeclareReductionDecl::DirectInit
20211                             : OMPDeclareReductionDecl::CopyInit);
20212   } else {
20213     DRD->setInvalidDecl();
20214   }
20215 }
20216 
20217 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
20218     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
20219   for (Decl *D : DeclReductions.get()) {
20220     if (IsValid) {
20221       if (S)
20222         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
20223                           /*AddToContext=*/false);
20224     } else {
20225       D->setInvalidDecl();
20226     }
20227   }
20228   return DeclReductions;
20229 }
20230 
20231 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
20232   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
20233   QualType T = TInfo->getType();
20234   if (D.isInvalidType())
20235     return true;
20236 
20237   if (getLangOpts().CPlusPlus) {
20238     // Check that there are no default arguments (C++ only).
20239     CheckExtraCXXDefaultArguments(D);
20240   }
20241 
20242   return CreateParsedType(T, TInfo);
20243 }
20244 
20245 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
20246                                             TypeResult ParsedType) {
20247   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
20248 
20249   QualType MapperType = GetTypeFromParser(ParsedType.get());
20250   assert(!MapperType.isNull() && "Expect valid mapper type");
20251 
20252   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20253   //  The type must be of struct, union or class type in C and C++
20254   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
20255     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
20256     return QualType();
20257   }
20258   return MapperType;
20259 }
20260 
20261 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
20262     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
20263     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
20264     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
20265   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
20266                       forRedeclarationInCurContext());
20267   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20268   //  A mapper-identifier may not be redeclared in the current scope for the
20269   //  same type or for a type that is compatible according to the base language
20270   //  rules.
20271   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20272   OMPDeclareMapperDecl *PrevDMD = nullptr;
20273   bool InCompoundScope = true;
20274   if (S != nullptr) {
20275     // Find previous declaration with the same name not referenced in other
20276     // declarations.
20277     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20278     InCompoundScope =
20279         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20280     LookupName(Lookup, S);
20281     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20282                          /*AllowInlineNamespace=*/false);
20283     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
20284     LookupResult::Filter Filter = Lookup.makeFilter();
20285     while (Filter.hasNext()) {
20286       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
20287       if (InCompoundScope) {
20288         auto I = UsedAsPrevious.find(PrevDecl);
20289         if (I == UsedAsPrevious.end())
20290           UsedAsPrevious[PrevDecl] = false;
20291         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
20292           UsedAsPrevious[D] = true;
20293       }
20294       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20295           PrevDecl->getLocation();
20296     }
20297     Filter.done();
20298     if (InCompoundScope) {
20299       for (const auto &PrevData : UsedAsPrevious) {
20300         if (!PrevData.second) {
20301           PrevDMD = PrevData.first;
20302           break;
20303         }
20304       }
20305     }
20306   } else if (PrevDeclInScope) {
20307     auto *PrevDMDInScope = PrevDMD =
20308         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
20309     do {
20310       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
20311           PrevDMDInScope->getLocation();
20312       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
20313     } while (PrevDMDInScope != nullptr);
20314   }
20315   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
20316   bool Invalid = false;
20317   if (I != PreviousRedeclTypes.end()) {
20318     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
20319         << MapperType << Name;
20320     Diag(I->second, diag::note_previous_definition);
20321     Invalid = true;
20322   }
20323   // Build expressions for implicit maps of data members with 'default'
20324   // mappers.
20325   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
20326                                                   Clauses.end());
20327   if (LangOpts.OpenMP >= 50)
20328     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
20329   auto *DMD =
20330       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
20331                                    ClausesWithImplicit, PrevDMD);
20332   if (S)
20333     PushOnScopeChains(DMD, S);
20334   else
20335     DC->addDecl(DMD);
20336   DMD->setAccess(AS);
20337   if (Invalid)
20338     DMD->setInvalidDecl();
20339 
20340   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
20341   VD->setDeclContext(DMD);
20342   VD->setLexicalDeclContext(DMD);
20343   DMD->addDecl(VD);
20344   DMD->setMapperVarRef(MapperVarRef);
20345 
20346   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
20347 }
20348 
20349 ExprResult
20350 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
20351                                                SourceLocation StartLoc,
20352                                                DeclarationName VN) {
20353   TypeSourceInfo *TInfo =
20354       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
20355   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
20356                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
20357                              MapperType, TInfo, SC_None);
20358   if (S)
20359     PushOnScopeChains(VD, S, /*AddToContext=*/false);
20360   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
20361   DSAStack->addDeclareMapperVarRef(E);
20362   return E;
20363 }
20364 
20365 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
20366   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20367   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
20368   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
20369     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
20370       return true;
20371     if (VD->isUsableInConstantExpressions(Context))
20372       return true;
20373     return false;
20374   }
20375   return true;
20376 }
20377 
20378 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
20379   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20380   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
20381 }
20382 
20383 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
20384                                            SourceLocation StartLoc,
20385                                            SourceLocation LParenLoc,
20386                                            SourceLocation EndLoc) {
20387   Expr *ValExpr = NumTeams;
20388   Stmt *HelperValStmt = nullptr;
20389 
20390   // OpenMP [teams Constrcut, Restrictions]
20391   // The num_teams expression must evaluate to a positive integer value.
20392   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
20393                                  /*StrictlyPositive=*/true))
20394     return nullptr;
20395 
20396   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20397   OpenMPDirectiveKind CaptureRegion =
20398       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
20399   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20400     ValExpr = MakeFullExpr(ValExpr).get();
20401     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20402     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20403     HelperValStmt = buildPreInits(Context, Captures);
20404   }
20405 
20406   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
20407                                          StartLoc, LParenLoc, EndLoc);
20408 }
20409 
20410 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
20411                                               SourceLocation StartLoc,
20412                                               SourceLocation LParenLoc,
20413                                               SourceLocation EndLoc) {
20414   Expr *ValExpr = ThreadLimit;
20415   Stmt *HelperValStmt = nullptr;
20416 
20417   // OpenMP [teams Constrcut, Restrictions]
20418   // The thread_limit expression must evaluate to a positive integer value.
20419   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
20420                                  /*StrictlyPositive=*/true))
20421     return nullptr;
20422 
20423   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20424   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
20425       DKind, OMPC_thread_limit, LangOpts.OpenMP);
20426   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20427     ValExpr = MakeFullExpr(ValExpr).get();
20428     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20429     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20430     HelperValStmt = buildPreInits(Context, Captures);
20431   }
20432 
20433   return new (Context) OMPThreadLimitClause(
20434       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20435 }
20436 
20437 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
20438                                            SourceLocation StartLoc,
20439                                            SourceLocation LParenLoc,
20440                                            SourceLocation EndLoc) {
20441   Expr *ValExpr = Priority;
20442   Stmt *HelperValStmt = nullptr;
20443   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20444 
20445   // OpenMP [2.9.1, task Constrcut]
20446   // The priority-value is a non-negative numerical scalar expression.
20447   if (!isNonNegativeIntegerValue(
20448           ValExpr, *this, OMPC_priority,
20449           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
20450           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20451     return nullptr;
20452 
20453   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
20454                                          StartLoc, LParenLoc, EndLoc);
20455 }
20456 
20457 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
20458                                             SourceLocation StartLoc,
20459                                             SourceLocation LParenLoc,
20460                                             SourceLocation EndLoc) {
20461   Expr *ValExpr = Grainsize;
20462   Stmt *HelperValStmt = nullptr;
20463   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20464 
20465   // OpenMP [2.9.2, taskloop Constrcut]
20466   // The parameter of the grainsize clause must be a positive integer
20467   // expression.
20468   if (!isNonNegativeIntegerValue(
20469           ValExpr, *this, OMPC_grainsize,
20470           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20471           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20472     return nullptr;
20473 
20474   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
20475                                           StartLoc, LParenLoc, EndLoc);
20476 }
20477 
20478 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
20479                                            SourceLocation StartLoc,
20480                                            SourceLocation LParenLoc,
20481                                            SourceLocation EndLoc) {
20482   Expr *ValExpr = NumTasks;
20483   Stmt *HelperValStmt = nullptr;
20484   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20485 
20486   // OpenMP [2.9.2, taskloop Constrcut]
20487   // The parameter of the num_tasks clause must be a positive integer
20488   // expression.
20489   if (!isNonNegativeIntegerValue(
20490           ValExpr, *this, OMPC_num_tasks,
20491           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20492           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20493     return nullptr;
20494 
20495   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
20496                                          StartLoc, LParenLoc, EndLoc);
20497 }
20498 
20499 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
20500                                        SourceLocation LParenLoc,
20501                                        SourceLocation EndLoc) {
20502   // OpenMP [2.13.2, critical construct, Description]
20503   // ... where hint-expression is an integer constant expression that evaluates
20504   // to a valid lock hint.
20505   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
20506   if (HintExpr.isInvalid())
20507     return nullptr;
20508   return new (Context)
20509       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
20510 }
20511 
20512 /// Tries to find omp_event_handle_t type.
20513 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
20514                                 DSAStackTy *Stack) {
20515   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
20516   if (!OMPEventHandleT.isNull())
20517     return true;
20518   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
20519   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
20520   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20521     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
20522     return false;
20523   }
20524   Stack->setOMPEventHandleT(PT.get());
20525   return true;
20526 }
20527 
20528 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
20529                                          SourceLocation LParenLoc,
20530                                          SourceLocation EndLoc) {
20531   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
20532       !Evt->isInstantiationDependent() &&
20533       !Evt->containsUnexpandedParameterPack()) {
20534     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
20535       return nullptr;
20536     // OpenMP 5.0, 2.10.1 task Construct.
20537     // event-handle is a variable of the omp_event_handle_t type.
20538     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
20539     if (!Ref) {
20540       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20541           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20542       return nullptr;
20543     }
20544     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
20545     if (!VD) {
20546       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20547           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20548       return nullptr;
20549     }
20550     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
20551                                         VD->getType()) ||
20552         VD->getType().isConstant(Context)) {
20553       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20554           << "omp_event_handle_t" << 1 << VD->getType()
20555           << Evt->getSourceRange();
20556       return nullptr;
20557     }
20558     // OpenMP 5.0, 2.10.1 task Construct
20559     // [detach clause]... The event-handle will be considered as if it was
20560     // specified on a firstprivate clause.
20561     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
20562     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
20563         DVar.RefExpr) {
20564       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
20565           << getOpenMPClauseName(DVar.CKind)
20566           << getOpenMPClauseName(OMPC_firstprivate);
20567       reportOriginalDsa(*this, DSAStack, VD, DVar);
20568       return nullptr;
20569     }
20570   }
20571 
20572   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
20573 }
20574 
20575 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
20576     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
20577     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
20578     SourceLocation EndLoc) {
20579   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
20580     std::string Values;
20581     Values += "'";
20582     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
20583     Values += "'";
20584     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20585         << Values << getOpenMPClauseName(OMPC_dist_schedule);
20586     return nullptr;
20587   }
20588   Expr *ValExpr = ChunkSize;
20589   Stmt *HelperValStmt = nullptr;
20590   if (ChunkSize) {
20591     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
20592         !ChunkSize->isInstantiationDependent() &&
20593         !ChunkSize->containsUnexpandedParameterPack()) {
20594       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
20595       ExprResult Val =
20596           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
20597       if (Val.isInvalid())
20598         return nullptr;
20599 
20600       ValExpr = Val.get();
20601 
20602       // OpenMP [2.7.1, Restrictions]
20603       //  chunk_size must be a loop invariant integer expression with a positive
20604       //  value.
20605       if (Optional<llvm::APSInt> Result =
20606               ValExpr->getIntegerConstantExpr(Context)) {
20607         if (Result->isSigned() && !Result->isStrictlyPositive()) {
20608           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
20609               << "dist_schedule" << ChunkSize->getSourceRange();
20610           return nullptr;
20611         }
20612       } else if (getOpenMPCaptureRegionForClause(
20613                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
20614                      LangOpts.OpenMP) != OMPD_unknown &&
20615                  !CurContext->isDependentContext()) {
20616         ValExpr = MakeFullExpr(ValExpr).get();
20617         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20618         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20619         HelperValStmt = buildPreInits(Context, Captures);
20620       }
20621     }
20622   }
20623 
20624   return new (Context)
20625       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
20626                             Kind, ValExpr, HelperValStmt);
20627 }
20628 
20629 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
20630     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
20631     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
20632     SourceLocation KindLoc, SourceLocation EndLoc) {
20633   if (getLangOpts().OpenMP < 50) {
20634     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
20635         Kind != OMPC_DEFAULTMAP_scalar) {
20636       std::string Value;
20637       SourceLocation Loc;
20638       Value += "'";
20639       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
20640         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20641                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
20642         Loc = MLoc;
20643       } else {
20644         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20645                                                OMPC_DEFAULTMAP_scalar);
20646         Loc = KindLoc;
20647       }
20648       Value += "'";
20649       Diag(Loc, diag::err_omp_unexpected_clause_value)
20650           << Value << getOpenMPClauseName(OMPC_defaultmap);
20651       return nullptr;
20652     }
20653   } else {
20654     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
20655     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
20656                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
20657     if (!isDefaultmapKind || !isDefaultmapModifier) {
20658       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
20659       if (LangOpts.OpenMP == 50) {
20660         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
20661                                   "'firstprivate', 'none', 'default'";
20662         if (!isDefaultmapKind && isDefaultmapModifier) {
20663           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20664               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20665         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20666           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20667               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20668         } else {
20669           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20670               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20671           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20672               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20673         }
20674       } else {
20675         StringRef ModifierValue =
20676             "'alloc', 'from', 'to', 'tofrom', "
20677             "'firstprivate', 'none', 'default', 'present'";
20678         if (!isDefaultmapKind && isDefaultmapModifier) {
20679           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20680               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20681         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20682           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20683               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20684         } else {
20685           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20686               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20687           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20688               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20689         }
20690       }
20691       return nullptr;
20692     }
20693 
20694     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
20695     //  At most one defaultmap clause for each category can appear on the
20696     //  directive.
20697     if (DSAStack->checkDefaultmapCategory(Kind)) {
20698       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
20699       return nullptr;
20700     }
20701   }
20702   if (Kind == OMPC_DEFAULTMAP_unknown) {
20703     // Variable category is not specified - mark all categories.
20704     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
20705     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
20706     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
20707   } else {
20708     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
20709   }
20710 
20711   return new (Context)
20712       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
20713 }
20714 
20715 bool Sema::ActOnStartOpenMPDeclareTargetContext(
20716     DeclareTargetContextInfo &DTCI) {
20717   DeclContext *CurLexicalContext = getCurLexicalContext();
20718   if (!CurLexicalContext->isFileContext() &&
20719       !CurLexicalContext->isExternCContext() &&
20720       !CurLexicalContext->isExternCXXContext() &&
20721       !isa<CXXRecordDecl>(CurLexicalContext) &&
20722       !isa<ClassTemplateDecl>(CurLexicalContext) &&
20723       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
20724       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
20725     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
20726     return false;
20727   }
20728   DeclareTargetNesting.push_back(DTCI);
20729   return true;
20730 }
20731 
20732 const Sema::DeclareTargetContextInfo
20733 Sema::ActOnOpenMPEndDeclareTargetDirective() {
20734   assert(!DeclareTargetNesting.empty() &&
20735          "check isInOpenMPDeclareTargetContext() first!");
20736   return DeclareTargetNesting.pop_back_val();
20737 }
20738 
20739 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
20740     DeclareTargetContextInfo &DTCI) {
20741   for (auto &It : DTCI.ExplicitlyMapped)
20742     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT,
20743                                  DTCI.DT);
20744 }
20745 
20746 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
20747                                                CXXScopeSpec &ScopeSpec,
20748                                                const DeclarationNameInfo &Id) {
20749   LookupResult Lookup(*this, Id, LookupOrdinaryName);
20750   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
20751 
20752   if (Lookup.isAmbiguous())
20753     return nullptr;
20754   Lookup.suppressDiagnostics();
20755 
20756   if (!Lookup.isSingleResult()) {
20757     VarOrFuncDeclFilterCCC CCC(*this);
20758     if (TypoCorrection Corrected =
20759             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
20760                         CTK_ErrorRecovery)) {
20761       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
20762                                   << Id.getName());
20763       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
20764       return nullptr;
20765     }
20766 
20767     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
20768     return nullptr;
20769   }
20770 
20771   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
20772   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
20773       !isa<FunctionTemplateDecl>(ND)) {
20774     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
20775     return nullptr;
20776   }
20777   return ND;
20778 }
20779 
20780 void Sema::ActOnOpenMPDeclareTargetName(
20781     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
20782     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
20783   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
20784           isa<FunctionTemplateDecl>(ND)) &&
20785          "Expected variable, function or function template.");
20786 
20787   // Diagnose marking after use as it may lead to incorrect diagnosis and
20788   // codegen.
20789   if (LangOpts.OpenMP >= 50 &&
20790       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
20791     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
20792 
20793   // Explicit declare target lists have precedence.
20794   const unsigned Level = -1;
20795 
20796   auto *VD = cast<ValueDecl>(ND);
20797   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20798       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20799   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT &&
20800       ActiveAttr.getValue()->getLevel() == Level) {
20801     Diag(Loc, diag::err_omp_device_type_mismatch)
20802         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
20803         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
20804                ActiveAttr.getValue()->getDevType());
20805     return;
20806   }
20807   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
20808       ActiveAttr.getValue()->getLevel() == Level) {
20809     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20810     return;
20811   }
20812 
20813   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
20814     return;
20815 
20816   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level,
20817                                                      SourceRange(Loc, Loc));
20818   ND->addAttr(A);
20819   if (ASTMutationListener *ML = Context.getASTMutationListener())
20820     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
20821   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20822 }
20823 
20824 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20825                                      Sema &SemaRef, Decl *D) {
20826   if (!D || !isa<VarDecl>(D))
20827     return;
20828   auto *VD = cast<VarDecl>(D);
20829   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20830       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20831   if (SemaRef.LangOpts.OpenMP >= 50 &&
20832       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20833        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20834       VD->hasGlobalStorage()) {
20835     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20836       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20837       // If a lambda declaration and definition appears between a
20838       // declare target directive and the matching end declare target
20839       // directive, all variables that are captured by the lambda
20840       // expression must also appear in a to clause.
20841       SemaRef.Diag(VD->getLocation(),
20842                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20843       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20844           << VD << 0 << SR;
20845       return;
20846     }
20847   }
20848   if (MapTy.hasValue())
20849     return;
20850   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20851   SemaRef.Diag(SL, diag::note_used_here) << SR;
20852 }
20853 
20854 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20855                                    Sema &SemaRef, DSAStackTy *Stack,
20856                                    ValueDecl *VD) {
20857   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20858          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20859                            /*FullCheck=*/false);
20860 }
20861 
20862 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20863                                             SourceLocation IdLoc) {
20864   if (!D || D->isInvalidDecl())
20865     return;
20866   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20867   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20868   if (auto *VD = dyn_cast<VarDecl>(D)) {
20869     // Only global variables can be marked as declare target.
20870     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20871         !VD->isStaticDataMember())
20872       return;
20873     // 2.10.6: threadprivate variable cannot appear in a declare target
20874     // directive.
20875     if (DSAStack->isThreadPrivate(VD)) {
20876       Diag(SL, diag::err_omp_threadprivate_in_target);
20877       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20878       return;
20879     }
20880   }
20881   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20882     D = FTD->getTemplatedDecl();
20883   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20884     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20885         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20886     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20887       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20888       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20889       return;
20890     }
20891   }
20892   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20893     // Problem if any with var declared with incomplete type will be reported
20894     // as normal, so no need to check it here.
20895     if ((E || !VD->getType()->isIncompleteType()) &&
20896         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20897       return;
20898     if (!E && isInOpenMPDeclareTargetContext()) {
20899       // Checking declaration inside declare target region.
20900       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20901           isa<FunctionTemplateDecl>(D)) {
20902         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20903             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20904         unsigned Level = DeclareTargetNesting.size();
20905         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
20906           return;
20907         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
20908         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20909             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level,
20910             SourceRange(DTCI.Loc, DTCI.Loc));
20911         D->addAttr(A);
20912         if (ASTMutationListener *ML = Context.getASTMutationListener())
20913           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20914       }
20915       return;
20916     }
20917   }
20918   if (!E)
20919     return;
20920   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20921 }
20922 
20923 OMPClause *Sema::ActOnOpenMPToClause(
20924     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20925     ArrayRef<SourceLocation> MotionModifiersLoc,
20926     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20927     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20928     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20929   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20930                                           OMPC_MOTION_MODIFIER_unknown};
20931   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20932 
20933   // Process motion-modifiers, flag errors for duplicate modifiers.
20934   unsigned Count = 0;
20935   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20936     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20937         llvm::is_contained(Modifiers, MotionModifiers[I])) {
20938       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20939       continue;
20940     }
20941     assert(Count < NumberOfOMPMotionModifiers &&
20942            "Modifiers exceed the allowed number of motion modifiers");
20943     Modifiers[Count] = MotionModifiers[I];
20944     ModifiersLoc[Count] = MotionModifiersLoc[I];
20945     ++Count;
20946   }
20947 
20948   MappableVarListInfo MVLI(VarList);
20949   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20950                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20951   if (MVLI.ProcessedVarList.empty())
20952     return nullptr;
20953 
20954   return OMPToClause::Create(
20955       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20956       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20957       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20958 }
20959 
20960 OMPClause *Sema::ActOnOpenMPFromClause(
20961     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20962     ArrayRef<SourceLocation> MotionModifiersLoc,
20963     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20964     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20965     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20966   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20967                                           OMPC_MOTION_MODIFIER_unknown};
20968   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20969 
20970   // Process motion-modifiers, flag errors for duplicate modifiers.
20971   unsigned Count = 0;
20972   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20973     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20974         llvm::is_contained(Modifiers, MotionModifiers[I])) {
20975       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20976       continue;
20977     }
20978     assert(Count < NumberOfOMPMotionModifiers &&
20979            "Modifiers exceed the allowed number of motion modifiers");
20980     Modifiers[Count] = MotionModifiers[I];
20981     ModifiersLoc[Count] = MotionModifiersLoc[I];
20982     ++Count;
20983   }
20984 
20985   MappableVarListInfo MVLI(VarList);
20986   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20987                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20988   if (MVLI.ProcessedVarList.empty())
20989     return nullptr;
20990 
20991   return OMPFromClause::Create(
20992       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20993       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20994       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20995 }
20996 
20997 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20998                                                const OMPVarListLocTy &Locs) {
20999   MappableVarListInfo MVLI(VarList);
21000   SmallVector<Expr *, 8> PrivateCopies;
21001   SmallVector<Expr *, 8> Inits;
21002 
21003   for (Expr *RefExpr : VarList) {
21004     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
21005     SourceLocation ELoc;
21006     SourceRange ERange;
21007     Expr *SimpleRefExpr = RefExpr;
21008     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21009     if (Res.second) {
21010       // It will be analyzed later.
21011       MVLI.ProcessedVarList.push_back(RefExpr);
21012       PrivateCopies.push_back(nullptr);
21013       Inits.push_back(nullptr);
21014     }
21015     ValueDecl *D = Res.first;
21016     if (!D)
21017       continue;
21018 
21019     QualType Type = D->getType();
21020     Type = Type.getNonReferenceType().getUnqualifiedType();
21021 
21022     auto *VD = dyn_cast<VarDecl>(D);
21023 
21024     // Item should be a pointer or reference to pointer.
21025     if (!Type->isPointerType()) {
21026       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
21027           << 0 << RefExpr->getSourceRange();
21028       continue;
21029     }
21030 
21031     // Build the private variable and the expression that refers to it.
21032     auto VDPrivate =
21033         buildVarDecl(*this, ELoc, Type, D->getName(),
21034                      D->hasAttrs() ? &D->getAttrs() : nullptr,
21035                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
21036     if (VDPrivate->isInvalidDecl())
21037       continue;
21038 
21039     CurContext->addDecl(VDPrivate);
21040     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
21041         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
21042 
21043     // Add temporary variable to initialize the private copy of the pointer.
21044     VarDecl *VDInit =
21045         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
21046     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
21047         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
21048     AddInitializerToDecl(VDPrivate,
21049                          DefaultLvalueConversion(VDInitRefExpr).get(),
21050                          /*DirectInit=*/false);
21051 
21052     // If required, build a capture to implement the privatization initialized
21053     // with the current list item value.
21054     DeclRefExpr *Ref = nullptr;
21055     if (!VD)
21056       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21057     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21058     PrivateCopies.push_back(VDPrivateRefExpr);
21059     Inits.push_back(VDInitRefExpr);
21060 
21061     // We need to add a data sharing attribute for this variable to make sure it
21062     // is correctly captured. A variable that shows up in a use_device_ptr has
21063     // similar properties of a first private variable.
21064     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21065 
21066     // Create a mappable component for the list item. List items in this clause
21067     // only need a component.
21068     MVLI.VarBaseDeclarations.push_back(D);
21069     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21070     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
21071                                            /*IsNonContiguous=*/false);
21072   }
21073 
21074   if (MVLI.ProcessedVarList.empty())
21075     return nullptr;
21076 
21077   return OMPUseDevicePtrClause::Create(
21078       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
21079       MVLI.VarBaseDeclarations, MVLI.VarComponents);
21080 }
21081 
21082 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
21083                                                 const OMPVarListLocTy &Locs) {
21084   MappableVarListInfo MVLI(VarList);
21085 
21086   for (Expr *RefExpr : VarList) {
21087     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
21088     SourceLocation ELoc;
21089     SourceRange ERange;
21090     Expr *SimpleRefExpr = RefExpr;
21091     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21092                               /*AllowArraySection=*/true);
21093     if (Res.second) {
21094       // It will be analyzed later.
21095       MVLI.ProcessedVarList.push_back(RefExpr);
21096     }
21097     ValueDecl *D = Res.first;
21098     if (!D)
21099       continue;
21100     auto *VD = dyn_cast<VarDecl>(D);
21101 
21102     // If required, build a capture to implement the privatization initialized
21103     // with the current list item value.
21104     DeclRefExpr *Ref = nullptr;
21105     if (!VD)
21106       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21107     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21108 
21109     // We need to add a data sharing attribute for this variable to make sure it
21110     // is correctly captured. A variable that shows up in a use_device_addr has
21111     // similar properties of a first private variable.
21112     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21113 
21114     // Create a mappable component for the list item. List items in this clause
21115     // only need a component.
21116     MVLI.VarBaseDeclarations.push_back(D);
21117     MVLI.VarComponents.emplace_back();
21118     Expr *Component = SimpleRefExpr;
21119     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
21120                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
21121       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
21122     MVLI.VarComponents.back().emplace_back(Component, D,
21123                                            /*IsNonContiguous=*/false);
21124   }
21125 
21126   if (MVLI.ProcessedVarList.empty())
21127     return nullptr;
21128 
21129   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21130                                         MVLI.VarBaseDeclarations,
21131                                         MVLI.VarComponents);
21132 }
21133 
21134 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
21135                                               const OMPVarListLocTy &Locs) {
21136   MappableVarListInfo MVLI(VarList);
21137   for (Expr *RefExpr : VarList) {
21138     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
21139     SourceLocation ELoc;
21140     SourceRange ERange;
21141     Expr *SimpleRefExpr = RefExpr;
21142     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21143     if (Res.second) {
21144       // It will be analyzed later.
21145       MVLI.ProcessedVarList.push_back(RefExpr);
21146     }
21147     ValueDecl *D = Res.first;
21148     if (!D)
21149       continue;
21150 
21151     QualType Type = D->getType();
21152     // item should be a pointer or array or reference to pointer or array
21153     if (!Type.getNonReferenceType()->isPointerType() &&
21154         !Type.getNonReferenceType()->isArrayType()) {
21155       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
21156           << 0 << RefExpr->getSourceRange();
21157       continue;
21158     }
21159 
21160     // Check if the declaration in the clause does not show up in any data
21161     // sharing attribute.
21162     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21163     if (isOpenMPPrivate(DVar.CKind)) {
21164       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21165           << getOpenMPClauseName(DVar.CKind)
21166           << getOpenMPClauseName(OMPC_is_device_ptr)
21167           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
21168       reportOriginalDsa(*this, DSAStack, D, DVar);
21169       continue;
21170     }
21171 
21172     const Expr *ConflictExpr;
21173     if (DSAStack->checkMappableExprComponentListsForDecl(
21174             D, /*CurrentRegionOnly=*/true,
21175             [&ConflictExpr](
21176                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
21177                 OpenMPClauseKind) -> bool {
21178               ConflictExpr = R.front().getAssociatedExpression();
21179               return true;
21180             })) {
21181       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
21182       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
21183           << ConflictExpr->getSourceRange();
21184       continue;
21185     }
21186 
21187     // Store the components in the stack so that they can be used to check
21188     // against other clauses later on.
21189     OMPClauseMappableExprCommon::MappableComponent MC(
21190         SimpleRefExpr, D, /*IsNonContiguous=*/false);
21191     DSAStack->addMappableExpressionComponents(
21192         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
21193 
21194     // Record the expression we've just processed.
21195     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
21196 
21197     // Create a mappable component for the list item. List items in this clause
21198     // only need a component. We use a null declaration to signal fields in
21199     // 'this'.
21200     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
21201             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
21202            "Unexpected device pointer expression!");
21203     MVLI.VarBaseDeclarations.push_back(
21204         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
21205     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21206     MVLI.VarComponents.back().push_back(MC);
21207   }
21208 
21209   if (MVLI.ProcessedVarList.empty())
21210     return nullptr;
21211 
21212   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21213                                       MVLI.VarBaseDeclarations,
21214                                       MVLI.VarComponents);
21215 }
21216 
21217 OMPClause *Sema::ActOnOpenMPAllocateClause(
21218     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
21219     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
21220   if (Allocator) {
21221     // OpenMP [2.11.4 allocate Clause, Description]
21222     // allocator is an expression of omp_allocator_handle_t type.
21223     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
21224       return nullptr;
21225 
21226     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
21227     if (AllocatorRes.isInvalid())
21228       return nullptr;
21229     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
21230                                              DSAStack->getOMPAllocatorHandleT(),
21231                                              Sema::AA_Initializing,
21232                                              /*AllowExplicit=*/true);
21233     if (AllocatorRes.isInvalid())
21234       return nullptr;
21235     Allocator = AllocatorRes.get();
21236   } else {
21237     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
21238     // allocate clauses that appear on a target construct or on constructs in a
21239     // target region must specify an allocator expression unless a requires
21240     // directive with the dynamic_allocators clause is present in the same
21241     // compilation unit.
21242     if (LangOpts.OpenMPIsDevice &&
21243         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
21244       targetDiag(StartLoc, diag::err_expected_allocator_expression);
21245   }
21246   // Analyze and build list of variables.
21247   SmallVector<Expr *, 8> Vars;
21248   for (Expr *RefExpr : VarList) {
21249     assert(RefExpr && "NULL expr in OpenMP private clause.");
21250     SourceLocation ELoc;
21251     SourceRange ERange;
21252     Expr *SimpleRefExpr = RefExpr;
21253     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21254     if (Res.second) {
21255       // It will be analyzed later.
21256       Vars.push_back(RefExpr);
21257     }
21258     ValueDecl *D = Res.first;
21259     if (!D)
21260       continue;
21261 
21262     auto *VD = dyn_cast<VarDecl>(D);
21263     DeclRefExpr *Ref = nullptr;
21264     if (!VD && !CurContext->isDependentContext())
21265       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
21266     Vars.push_back((VD || CurContext->isDependentContext())
21267                        ? RefExpr->IgnoreParens()
21268                        : Ref);
21269   }
21270 
21271   if (Vars.empty())
21272     return nullptr;
21273 
21274   if (Allocator)
21275     DSAStack->addInnerAllocatorExpr(Allocator);
21276   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
21277                                    ColonLoc, EndLoc, Vars);
21278 }
21279 
21280 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
21281                                               SourceLocation StartLoc,
21282                                               SourceLocation LParenLoc,
21283                                               SourceLocation EndLoc) {
21284   SmallVector<Expr *, 8> Vars;
21285   for (Expr *RefExpr : VarList) {
21286     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21287     SourceLocation ELoc;
21288     SourceRange ERange;
21289     Expr *SimpleRefExpr = RefExpr;
21290     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21291     if (Res.second)
21292       // It will be analyzed later.
21293       Vars.push_back(RefExpr);
21294     ValueDecl *D = Res.first;
21295     if (!D)
21296       continue;
21297 
21298     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
21299     // A list-item cannot appear in more than one nontemporal clause.
21300     if (const Expr *PrevRef =
21301             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
21302       Diag(ELoc, diag::err_omp_used_in_clause_twice)
21303           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
21304       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
21305           << getOpenMPClauseName(OMPC_nontemporal);
21306       continue;
21307     }
21308 
21309     Vars.push_back(RefExpr);
21310   }
21311 
21312   if (Vars.empty())
21313     return nullptr;
21314 
21315   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21316                                       Vars);
21317 }
21318 
21319 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
21320                                             SourceLocation StartLoc,
21321                                             SourceLocation LParenLoc,
21322                                             SourceLocation EndLoc) {
21323   SmallVector<Expr *, 8> Vars;
21324   for (Expr *RefExpr : VarList) {
21325     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21326     SourceLocation ELoc;
21327     SourceRange ERange;
21328     Expr *SimpleRefExpr = RefExpr;
21329     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21330                               /*AllowArraySection=*/true);
21331     if (Res.second)
21332       // It will be analyzed later.
21333       Vars.push_back(RefExpr);
21334     ValueDecl *D = Res.first;
21335     if (!D)
21336       continue;
21337 
21338     const DSAStackTy::DSAVarData DVar =
21339         DSAStack->getTopDSA(D, /*FromParent=*/true);
21340     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21341     // A list item that appears in the inclusive or exclusive clause must appear
21342     // in a reduction clause with the inscan modifier on the enclosing
21343     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21344     if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
21345       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21346           << RefExpr->getSourceRange();
21347 
21348     if (DSAStack->getParentDirective() != OMPD_unknown)
21349       DSAStack->markDeclAsUsedInScanDirective(D);
21350     Vars.push_back(RefExpr);
21351   }
21352 
21353   if (Vars.empty())
21354     return nullptr;
21355 
21356   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21357 }
21358 
21359 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
21360                                             SourceLocation StartLoc,
21361                                             SourceLocation LParenLoc,
21362                                             SourceLocation EndLoc) {
21363   SmallVector<Expr *, 8> Vars;
21364   for (Expr *RefExpr : VarList) {
21365     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21366     SourceLocation ELoc;
21367     SourceRange ERange;
21368     Expr *SimpleRefExpr = RefExpr;
21369     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21370                               /*AllowArraySection=*/true);
21371     if (Res.second)
21372       // It will be analyzed later.
21373       Vars.push_back(RefExpr);
21374     ValueDecl *D = Res.first;
21375     if (!D)
21376       continue;
21377 
21378     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
21379     DSAStackTy::DSAVarData DVar;
21380     if (ParentDirective != OMPD_unknown)
21381       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
21382     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21383     // A list item that appears in the inclusive or exclusive clause must appear
21384     // in a reduction clause with the inscan modifier on the enclosing
21385     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21386     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
21387         DVar.Modifier != OMPC_REDUCTION_inscan) {
21388       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21389           << RefExpr->getSourceRange();
21390     } else {
21391       DSAStack->markDeclAsUsedInScanDirective(D);
21392     }
21393     Vars.push_back(RefExpr);
21394   }
21395 
21396   if (Vars.empty())
21397     return nullptr;
21398 
21399   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21400 }
21401 
21402 /// Tries to find omp_alloctrait_t type.
21403 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
21404   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
21405   if (!OMPAlloctraitT.isNull())
21406     return true;
21407   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
21408   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
21409   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21410     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
21411     return false;
21412   }
21413   Stack->setOMPAlloctraitT(PT.get());
21414   return true;
21415 }
21416 
21417 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
21418     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
21419     ArrayRef<UsesAllocatorsData> Data) {
21420   // OpenMP [2.12.5, target Construct]
21421   // allocator is an identifier of omp_allocator_handle_t type.
21422   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
21423     return nullptr;
21424   // OpenMP [2.12.5, target Construct]
21425   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
21426   if (llvm::any_of(
21427           Data,
21428           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
21429       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
21430     return nullptr;
21431   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
21432   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
21433     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
21434     StringRef Allocator =
21435         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
21436     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
21437     PredefinedAllocators.insert(LookupSingleName(
21438         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
21439   }
21440 
21441   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
21442   for (const UsesAllocatorsData &D : Data) {
21443     Expr *AllocatorExpr = nullptr;
21444     // Check allocator expression.
21445     if (D.Allocator->isTypeDependent()) {
21446       AllocatorExpr = D.Allocator;
21447     } else {
21448       // Traits were specified - need to assign new allocator to the specified
21449       // allocator, so it must be an lvalue.
21450       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
21451       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
21452       bool IsPredefinedAllocator = false;
21453       if (DRE)
21454         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
21455       if (!DRE ||
21456           !(Context.hasSameUnqualifiedType(
21457                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
21458             Context.typesAreCompatible(AllocatorExpr->getType(),
21459                                        DSAStack->getOMPAllocatorHandleT(),
21460                                        /*CompareUnqualified=*/true)) ||
21461           (!IsPredefinedAllocator &&
21462            (AllocatorExpr->getType().isConstant(Context) ||
21463             !AllocatorExpr->isLValue()))) {
21464         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
21465             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
21466             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
21467         continue;
21468       }
21469       // OpenMP [2.12.5, target Construct]
21470       // Predefined allocators appearing in a uses_allocators clause cannot have
21471       // traits specified.
21472       if (IsPredefinedAllocator && D.AllocatorTraits) {
21473         Diag(D.AllocatorTraits->getExprLoc(),
21474              diag::err_omp_predefined_allocator_with_traits)
21475             << D.AllocatorTraits->getSourceRange();
21476         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
21477             << cast<NamedDecl>(DRE->getDecl())->getName()
21478             << D.Allocator->getSourceRange();
21479         continue;
21480       }
21481       // OpenMP [2.12.5, target Construct]
21482       // Non-predefined allocators appearing in a uses_allocators clause must
21483       // have traits specified.
21484       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
21485         Diag(D.Allocator->getExprLoc(),
21486              diag::err_omp_nonpredefined_allocator_without_traits);
21487         continue;
21488       }
21489       // No allocator traits - just convert it to rvalue.
21490       if (!D.AllocatorTraits)
21491         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
21492       DSAStack->addUsesAllocatorsDecl(
21493           DRE->getDecl(),
21494           IsPredefinedAllocator
21495               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
21496               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
21497     }
21498     Expr *AllocatorTraitsExpr = nullptr;
21499     if (D.AllocatorTraits) {
21500       if (D.AllocatorTraits->isTypeDependent()) {
21501         AllocatorTraitsExpr = D.AllocatorTraits;
21502       } else {
21503         // OpenMP [2.12.5, target Construct]
21504         // Arrays that contain allocator traits that appear in a uses_allocators
21505         // clause must be constant arrays, have constant values and be defined
21506         // in the same scope as the construct in which the clause appears.
21507         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
21508         // Check that traits expr is a constant array.
21509         QualType TraitTy;
21510         if (const ArrayType *Ty =
21511                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
21512           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
21513             TraitTy = ConstArrayTy->getElementType();
21514         if (TraitTy.isNull() ||
21515             !(Context.hasSameUnqualifiedType(TraitTy,
21516                                              DSAStack->getOMPAlloctraitT()) ||
21517               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
21518                                          /*CompareUnqualified=*/true))) {
21519           Diag(D.AllocatorTraits->getExprLoc(),
21520                diag::err_omp_expected_array_alloctraits)
21521               << AllocatorTraitsExpr->getType();
21522           continue;
21523         }
21524         // Do not map by default allocator traits if it is a standalone
21525         // variable.
21526         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
21527           DSAStack->addUsesAllocatorsDecl(
21528               DRE->getDecl(),
21529               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
21530       }
21531     }
21532     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
21533     NewD.Allocator = AllocatorExpr;
21534     NewD.AllocatorTraits = AllocatorTraitsExpr;
21535     NewD.LParenLoc = D.LParenLoc;
21536     NewD.RParenLoc = D.RParenLoc;
21537   }
21538   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21539                                          NewData);
21540 }
21541 
21542 OMPClause *Sema::ActOnOpenMPAffinityClause(
21543     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
21544     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
21545   SmallVector<Expr *, 8> Vars;
21546   for (Expr *RefExpr : Locators) {
21547     assert(RefExpr && "NULL expr in OpenMP shared clause.");
21548     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
21549       // It will be analyzed later.
21550       Vars.push_back(RefExpr);
21551       continue;
21552     }
21553 
21554     SourceLocation ELoc = RefExpr->getExprLoc();
21555     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
21556 
21557     if (!SimpleExpr->isLValue()) {
21558       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21559           << 1 << 0 << RefExpr->getSourceRange();
21560       continue;
21561     }
21562 
21563     ExprResult Res;
21564     {
21565       Sema::TentativeAnalysisScope Trap(*this);
21566       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
21567     }
21568     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
21569         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
21570       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21571           << 1 << 0 << RefExpr->getSourceRange();
21572       continue;
21573     }
21574     Vars.push_back(SimpleExpr);
21575   }
21576 
21577   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
21578                                    EndLoc, Modifier, Vars);
21579 }
21580 
21581 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
21582                                        SourceLocation KindLoc,
21583                                        SourceLocation StartLoc,
21584                                        SourceLocation LParenLoc,
21585                                        SourceLocation EndLoc) {
21586   if (Kind == OMPC_BIND_unknown) {
21587     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21588         << getListOfPossibleValues(OMPC_bind, /*First=*/0,
21589                                    /*Last=*/unsigned(OMPC_BIND_unknown))
21590         << getOpenMPClauseName(OMPC_bind);
21591     return nullptr;
21592   }
21593 
21594   return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
21595                                EndLoc);
21596 }
21597