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/SmallSet.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Frontend/OpenMP/OMPAssume.h"
41 #include "llvm/Frontend/OpenMP/OMPConstants.h"
42 #include <set>
43 
44 using namespace clang;
45 using namespace llvm::omp;
46 
47 //===----------------------------------------------------------------------===//
48 // Stack of data-sharing attributes for variables
49 //===----------------------------------------------------------------------===//
50 
51 static const Expr *checkMapClauseExpressionBase(
52     Sema &SemaRef, Expr *E,
53     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
54     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
55 
56 namespace {
57 /// Default data sharing attributes, which can be applied to directive.
58 enum DefaultDataSharingAttributes {
59   DSA_unspecified = 0,       /// Data sharing attribute not specified.
60   DSA_none = 1 << 0,         /// Default data sharing attribute 'none'.
61   DSA_shared = 1 << 1,       /// Default data sharing attribute 'shared'.
62   DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
63 };
64 
65 /// Stack for tracking declarations used in OpenMP directives and
66 /// clauses and their data-sharing attributes.
67 class DSAStackTy {
68 public:
69   struct DSAVarData {
70     OpenMPDirectiveKind DKind = OMPD_unknown;
71     OpenMPClauseKind CKind = OMPC_unknown;
72     unsigned Modifier = 0;
73     const Expr *RefExpr = nullptr;
74     DeclRefExpr *PrivateCopy = nullptr;
75     SourceLocation ImplicitDSALoc;
76     bool AppliedToPointee = false;
77     DSAVarData() = default;
78     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
79                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
80                SourceLocation ImplicitDSALoc, unsigned Modifier,
81                bool AppliedToPointee)
82         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
83           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
84           AppliedToPointee(AppliedToPointee) {}
85   };
86   using OperatorOffsetTy =
87       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
88   using DoacrossDependMapTy =
89       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
90   /// Kind of the declaration used in the uses_allocators clauses.
91   enum class UsesAllocatorsDeclKind {
92     /// Predefined allocator
93     PredefinedAllocator,
94     /// User-defined allocator
95     UserDefinedAllocator,
96     /// The declaration that represent allocator trait
97     AllocatorTrait,
98   };
99 
100 private:
101   struct DSAInfo {
102     OpenMPClauseKind Attributes = OMPC_unknown;
103     unsigned Modifier = 0;
104     /// Pointer to a reference expression and a flag which shows that the
105     /// variable is marked as lastprivate(true) or not (false).
106     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
107     DeclRefExpr *PrivateCopy = nullptr;
108     /// true if the attribute is applied to the pointee, not the variable
109     /// itself.
110     bool AppliedToPointee = false;
111   };
112   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
113   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
114   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
115   using LoopControlVariablesMapTy =
116       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
117   /// Struct that associates a component with the clause kind where they are
118   /// found.
119   struct MappedExprComponentTy {
120     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
121     OpenMPClauseKind Kind = OMPC_unknown;
122   };
123   using MappedExprComponentsTy =
124       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
125   using CriticalsWithHintsTy =
126       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
127   struct ReductionData {
128     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
129     SourceRange ReductionRange;
130     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
131     ReductionData() = default;
132     void set(BinaryOperatorKind BO, SourceRange RR) {
133       ReductionRange = RR;
134       ReductionOp = BO;
135     }
136     void set(const Expr *RefExpr, SourceRange RR) {
137       ReductionRange = RR;
138       ReductionOp = RefExpr;
139     }
140   };
141   using DeclReductionMapTy =
142       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
143   struct DefaultmapInfo {
144     OpenMPDefaultmapClauseModifier ImplicitBehavior =
145         OMPC_DEFAULTMAP_MODIFIER_unknown;
146     SourceLocation SLoc;
147     DefaultmapInfo() = default;
148     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
149         : ImplicitBehavior(M), SLoc(Loc) {}
150   };
151 
152   struct SharingMapTy {
153     DeclSAMapTy SharingMap;
154     DeclReductionMapTy ReductionMap;
155     UsedRefMapTy AlignedMap;
156     UsedRefMapTy NontemporalMap;
157     MappedExprComponentsTy MappedExprComponents;
158     LoopControlVariablesMapTy LCVMap;
159     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
160     SourceLocation DefaultAttrLoc;
161     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
162     OpenMPDirectiveKind Directive = OMPD_unknown;
163     DeclarationNameInfo DirectiveName;
164     Scope *CurScope = nullptr;
165     DeclContext *Context = nullptr;
166     SourceLocation ConstructLoc;
167     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
168     /// get the data (loop counters etc.) about enclosing loop-based construct.
169     /// This data is required during codegen.
170     DoacrossDependMapTy DoacrossDepends;
171     /// First argument (Expr *) contains optional argument of the
172     /// 'ordered' clause, the second one is true if the regions has 'ordered'
173     /// clause, false otherwise.
174     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
175     unsigned AssociatedLoops = 1;
176     bool HasMutipleLoops = false;
177     const Decl *PossiblyLoopCounter = nullptr;
178     bool NowaitRegion = false;
179     bool UntiedRegion = false;
180     bool CancelRegion = false;
181     bool LoopStart = false;
182     bool BodyComplete = false;
183     SourceLocation PrevScanLocation;
184     SourceLocation PrevOrderedLocation;
185     SourceLocation InnerTeamsRegionLoc;
186     /// Reference to the taskgroup task_reduction reference expression.
187     Expr *TaskgroupReductionRef = nullptr;
188     llvm::DenseSet<QualType> MappedClassesQualTypes;
189     SmallVector<Expr *, 4> InnerUsedAllocators;
190     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
191     /// List of globals marked as declare target link in this target region
192     /// (isOpenMPTargetExecutionDirective(Directive) == true).
193     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
194     /// List of decls used in inclusive/exclusive clauses of the scan directive.
195     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
196     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
197         UsesAllocatorsDecls;
198     Expr *DeclareMapperVar = nullptr;
199     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
200                  Scope *CurScope, SourceLocation Loc)
201         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
202           ConstructLoc(Loc) {}
203     SharingMapTy() = default;
204   };
205 
206   using StackTy = SmallVector<SharingMapTy, 4>;
207 
208   /// Stack of used declaration and their data-sharing attributes.
209   DeclSAMapTy Threadprivates;
210   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
211   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
212   /// true, if check for DSA must be from parent directive, false, if
213   /// from current directive.
214   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
215   Sema &SemaRef;
216   bool ForceCapturing = false;
217   /// true if all the variables in the target executable directives must be
218   /// captured by reference.
219   bool ForceCaptureByReferenceInTargetExecutable = false;
220   CriticalsWithHintsTy Criticals;
221   unsigned IgnoredStackElements = 0;
222 
223   /// Iterators over the stack iterate in order from innermost to outermost
224   /// directive.
225   using const_iterator = StackTy::const_reverse_iterator;
226   const_iterator begin() const {
227     return Stack.empty() ? const_iterator()
228                          : Stack.back().first.rbegin() + IgnoredStackElements;
229   }
230   const_iterator end() const {
231     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
232   }
233   using iterator = StackTy::reverse_iterator;
234   iterator begin() {
235     return Stack.empty() ? iterator()
236                          : Stack.back().first.rbegin() + IgnoredStackElements;
237   }
238   iterator end() {
239     return Stack.empty() ? iterator() : Stack.back().first.rend();
240   }
241 
242   // Convenience operations to get at the elements of the stack.
243 
244   bool isStackEmpty() const {
245     return Stack.empty() ||
246            Stack.back().second != CurrentNonCapturingFunctionScope ||
247            Stack.back().first.size() <= IgnoredStackElements;
248   }
249   size_t getStackSize() const {
250     return isStackEmpty() ? 0
251                           : Stack.back().first.size() - IgnoredStackElements;
252   }
253 
254   SharingMapTy *getTopOfStackOrNull() {
255     size_t Size = getStackSize();
256     if (Size == 0)
257       return nullptr;
258     return &Stack.back().first[Size - 1];
259   }
260   const SharingMapTy *getTopOfStackOrNull() const {
261     return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
262   }
263   SharingMapTy &getTopOfStack() {
264     assert(!isStackEmpty() && "no current directive");
265     return *getTopOfStackOrNull();
266   }
267   const SharingMapTy &getTopOfStack() const {
268     return const_cast<DSAStackTy &>(*this).getTopOfStack();
269   }
270 
271   SharingMapTy *getSecondOnStackOrNull() {
272     size_t Size = getStackSize();
273     if (Size <= 1)
274       return nullptr;
275     return &Stack.back().first[Size - 2];
276   }
277   const SharingMapTy *getSecondOnStackOrNull() const {
278     return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
279   }
280 
281   /// Get the stack element at a certain level (previously returned by
282   /// \c getNestingLevel).
283   ///
284   /// Note that nesting levels count from outermost to innermost, and this is
285   /// the reverse of our iteration order where new inner levels are pushed at
286   /// the front of the stack.
287   SharingMapTy &getStackElemAtLevel(unsigned Level) {
288     assert(Level < getStackSize() && "no such stack element");
289     return Stack.back().first[Level];
290   }
291   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
292     return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
293   }
294 
295   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
296 
297   /// Checks if the variable is a local for OpenMP region.
298   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
299 
300   /// Vector of previously declared requires directives
301   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
302   /// omp_allocator_handle_t type.
303   QualType OMPAllocatorHandleT;
304   /// omp_depend_t type.
305   QualType OMPDependT;
306   /// omp_event_handle_t type.
307   QualType OMPEventHandleT;
308   /// omp_alloctrait_t type.
309   QualType OMPAlloctraitT;
310   /// Expression for the predefined allocators.
311   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
312       nullptr};
313   /// Vector of previously encountered target directives
314   SmallVector<SourceLocation, 2> TargetLocations;
315   SourceLocation AtomicLocation;
316   /// Vector of declare variant construct traits.
317   SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
318 
319 public:
320   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
321 
322   /// Sets omp_allocator_handle_t type.
323   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
324   /// Gets omp_allocator_handle_t type.
325   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
326   /// Sets omp_alloctrait_t type.
327   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
328   /// Gets omp_alloctrait_t type.
329   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
330   /// Sets the given default allocator.
331   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
332                     Expr *Allocator) {
333     OMPPredefinedAllocators[AllocatorKind] = Allocator;
334   }
335   /// Returns the specified default allocator.
336   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
337     return OMPPredefinedAllocators[AllocatorKind];
338   }
339   /// Sets omp_depend_t type.
340   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
341   /// Gets omp_depend_t type.
342   QualType getOMPDependT() const { return OMPDependT; }
343 
344   /// Sets omp_event_handle_t type.
345   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
346   /// Gets omp_event_handle_t type.
347   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
348 
349   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
350   OpenMPClauseKind getClauseParsingMode() const {
351     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
352     return ClauseKindMode;
353   }
354   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
355 
356   bool isBodyComplete() const {
357     const SharingMapTy *Top = getTopOfStackOrNull();
358     return Top && Top->BodyComplete;
359   }
360   void setBodyComplete() { getTopOfStack().BodyComplete = true; }
361 
362   bool isForceVarCapturing() const { return ForceCapturing; }
363   void setForceVarCapturing(bool V) { ForceCapturing = V; }
364 
365   void setForceCaptureByReferenceInTargetExecutable(bool V) {
366     ForceCaptureByReferenceInTargetExecutable = V;
367   }
368   bool isForceCaptureByReferenceInTargetExecutable() const {
369     return ForceCaptureByReferenceInTargetExecutable;
370   }
371 
372   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
373             Scope *CurScope, SourceLocation Loc) {
374     assert(!IgnoredStackElements &&
375            "cannot change stack while ignoring elements");
376     if (Stack.empty() ||
377         Stack.back().second != CurrentNonCapturingFunctionScope)
378       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
379     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
380     Stack.back().first.back().DefaultAttrLoc = Loc;
381   }
382 
383   void pop() {
384     assert(!IgnoredStackElements &&
385            "cannot change stack while ignoring elements");
386     assert(!Stack.back().first.empty() &&
387            "Data-sharing attributes stack is empty!");
388     Stack.back().first.pop_back();
389   }
390 
391   /// RAII object to temporarily leave the scope of a directive when we want to
392   /// logically operate in its parent.
393   class ParentDirectiveScope {
394     DSAStackTy &Self;
395     bool Active;
396 
397   public:
398     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
399         : Self(Self), Active(false) {
400       if (Activate)
401         enable();
402     }
403     ~ParentDirectiveScope() { disable(); }
404     void disable() {
405       if (Active) {
406         --Self.IgnoredStackElements;
407         Active = false;
408       }
409     }
410     void enable() {
411       if (!Active) {
412         ++Self.IgnoredStackElements;
413         Active = true;
414       }
415     }
416   };
417 
418   /// Marks that we're started loop parsing.
419   void loopInit() {
420     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
421            "Expected loop-based directive.");
422     getTopOfStack().LoopStart = true;
423   }
424   /// Start capturing of the variables in the loop context.
425   void loopStart() {
426     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
427            "Expected loop-based directive.");
428     getTopOfStack().LoopStart = false;
429   }
430   /// true, if variables are captured, false otherwise.
431   bool isLoopStarted() const {
432     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
433            "Expected loop-based directive.");
434     return !getTopOfStack().LoopStart;
435   }
436   /// Marks (or clears) declaration as possibly loop counter.
437   void resetPossibleLoopCounter(const Decl *D = nullptr) {
438     getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
439   }
440   /// Gets the possible loop counter decl.
441   const Decl *getPossiblyLoopCunter() const {
442     return getTopOfStack().PossiblyLoopCounter;
443   }
444   /// Start new OpenMP region stack in new non-capturing function.
445   void pushFunction() {
446     assert(!IgnoredStackElements &&
447            "cannot change stack while ignoring elements");
448     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
449     assert(!isa<CapturingScopeInfo>(CurFnScope));
450     CurrentNonCapturingFunctionScope = CurFnScope;
451   }
452   /// Pop region stack for non-capturing function.
453   void popFunction(const FunctionScopeInfo *OldFSI) {
454     assert(!IgnoredStackElements &&
455            "cannot change stack while ignoring elements");
456     if (!Stack.empty() && Stack.back().second == OldFSI) {
457       assert(Stack.back().first.empty());
458       Stack.pop_back();
459     }
460     CurrentNonCapturingFunctionScope = nullptr;
461     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
462       if (!isa<CapturingScopeInfo>(FSI)) {
463         CurrentNonCapturingFunctionScope = FSI;
464         break;
465       }
466     }
467   }
468 
469   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
470     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
471   }
472   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
473   getCriticalWithHint(const DeclarationNameInfo &Name) const {
474     auto I = Criticals.find(Name.getAsString());
475     if (I != Criticals.end())
476       return I->second;
477     return std::make_pair(nullptr, llvm::APSInt());
478   }
479   /// If 'aligned' declaration for given variable \a D was not seen yet,
480   /// add it and return NULL; otherwise return previous occurrence's expression
481   /// for diagnostics.
482   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
483   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
484   /// add it and return NULL; otherwise return previous occurrence's expression
485   /// for diagnostics.
486   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
487 
488   /// Register specified variable as loop control variable.
489   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
490   /// Check if the specified variable is a loop control variable for
491   /// current region.
492   /// \return The index of the loop control variable in the list of associated
493   /// for-loops (from outer to inner).
494   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
495   /// Check if the specified variable is a loop control variable for
496   /// parent region.
497   /// \return The index of the loop control variable in the list of associated
498   /// for-loops (from outer to inner).
499   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
500   /// Check if the specified variable is a loop control variable for
501   /// current region.
502   /// \return The index of the loop control variable in the list of associated
503   /// for-loops (from outer to inner).
504   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
505                                          unsigned Level) const;
506   /// Get the loop control variable for the I-th loop (or nullptr) in
507   /// parent directive.
508   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
509 
510   /// Marks the specified decl \p D as used in scan directive.
511   void markDeclAsUsedInScanDirective(ValueDecl *D) {
512     if (SharingMapTy *Stack = getSecondOnStackOrNull())
513       Stack->UsedInScanDirective.insert(D);
514   }
515 
516   /// Checks if the specified declaration was used in the inner scan directive.
517   bool isUsedInScanDirective(ValueDecl *D) const {
518     if (const SharingMapTy *Stack = getTopOfStackOrNull())
519       return Stack->UsedInScanDirective.contains(D);
520     return false;
521   }
522 
523   /// Adds explicit data sharing attribute to the specified declaration.
524   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
525               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
526               bool AppliedToPointee = false);
527 
528   /// Adds additional information for the reduction items with the reduction id
529   /// represented as an operator.
530   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
531                                  BinaryOperatorKind BOK);
532   /// Adds additional information for the reduction items with the reduction id
533   /// represented as reduction identifier.
534   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
535                                  const Expr *ReductionRef);
536   /// Returns the location and reduction operation from the innermost parent
537   /// region for the given \p D.
538   const DSAVarData
539   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
540                                    BinaryOperatorKind &BOK,
541                                    Expr *&TaskgroupDescriptor) const;
542   /// Returns the location and reduction operation from the innermost parent
543   /// region for the given \p D.
544   const DSAVarData
545   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
546                                    const Expr *&ReductionRef,
547                                    Expr *&TaskgroupDescriptor) const;
548   /// Return reduction reference expression for the current taskgroup or
549   /// parallel/worksharing directives with task reductions.
550   Expr *getTaskgroupReductionRef() const {
551     assert((getTopOfStack().Directive == OMPD_taskgroup ||
552             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
553               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
554              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
555            "taskgroup reference expression requested for non taskgroup or "
556            "parallel/worksharing directive.");
557     return getTopOfStack().TaskgroupReductionRef;
558   }
559   /// Checks if the given \p VD declaration is actually a taskgroup reduction
560   /// descriptor variable at the \p Level of OpenMP regions.
561   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
562     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
563            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
564                    ->getDecl() == VD;
565   }
566 
567   /// Returns data sharing attributes from top of the stack for the
568   /// specified declaration.
569   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
570   /// Returns data-sharing attributes for the specified declaration.
571   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
572   /// Returns data-sharing attributes for the specified declaration.
573   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
574   /// Checks if the specified variables has data-sharing attributes which
575   /// match specified \a CPred predicate in any directive which matches \a DPred
576   /// predicate.
577   const DSAVarData
578   hasDSA(ValueDecl *D,
579          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
580          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
581          bool FromParent) const;
582   /// Checks if the specified variables has data-sharing attributes which
583   /// match specified \a CPred predicate in any innermost directive which
584   /// matches \a DPred predicate.
585   const DSAVarData
586   hasInnermostDSA(ValueDecl *D,
587                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
588                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
589                   bool FromParent) const;
590   /// Checks if the specified variables has explicit data-sharing
591   /// attributes which match specified \a CPred predicate at the specified
592   /// OpenMP region.
593   bool
594   hasExplicitDSA(const ValueDecl *D,
595                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
596                  unsigned Level, bool NotLastprivate = false) const;
597 
598   /// Returns true if the directive at level \Level matches in the
599   /// specified \a DPred predicate.
600   bool hasExplicitDirective(
601       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
602       unsigned Level) const;
603 
604   /// Finds a directive which matches specified \a DPred predicate.
605   bool hasDirective(
606       const llvm::function_ref<bool(
607           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
608           DPred,
609       bool FromParent) const;
610 
611   /// Returns currently analyzed directive.
612   OpenMPDirectiveKind getCurrentDirective() const {
613     const SharingMapTy *Top = getTopOfStackOrNull();
614     return Top ? Top->Directive : OMPD_unknown;
615   }
616   /// Returns directive kind at specified level.
617   OpenMPDirectiveKind getDirective(unsigned Level) const {
618     assert(!isStackEmpty() && "No directive at specified level.");
619     return getStackElemAtLevel(Level).Directive;
620   }
621   /// Returns the capture region at the specified level.
622   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
623                                        unsigned OpenMPCaptureLevel) const {
624     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
625     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
626     return CaptureRegions[OpenMPCaptureLevel];
627   }
628   /// Returns parent directive.
629   OpenMPDirectiveKind getParentDirective() const {
630     const SharingMapTy *Parent = getSecondOnStackOrNull();
631     return Parent ? Parent->Directive : OMPD_unknown;
632   }
633 
634   /// Add requires decl to internal vector
635   void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
636 
637   /// Checks if the defined 'requires' directive has specified type of clause.
638   template <typename ClauseType> bool hasRequiresDeclWithClause() const {
639     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
640       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
641         return isa<ClauseType>(C);
642       });
643     });
644   }
645 
646   /// Checks for a duplicate clause amongst previously declared requires
647   /// directives
648   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
649     bool IsDuplicate = false;
650     for (OMPClause *CNew : ClauseList) {
651       for (const OMPRequiresDecl *D : RequiresDecls) {
652         for (const OMPClause *CPrev : D->clauselists()) {
653           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
654             SemaRef.Diag(CNew->getBeginLoc(),
655                          diag::err_omp_requires_clause_redeclaration)
656                 << getOpenMPClauseName(CNew->getClauseKind());
657             SemaRef.Diag(CPrev->getBeginLoc(),
658                          diag::note_omp_requires_previous_clause)
659                 << getOpenMPClauseName(CPrev->getClauseKind());
660             IsDuplicate = true;
661           }
662         }
663       }
664     }
665     return IsDuplicate;
666   }
667 
668   /// Add location of previously encountered target to internal vector
669   void addTargetDirLocation(SourceLocation LocStart) {
670     TargetLocations.push_back(LocStart);
671   }
672 
673   /// Add location for the first encountered atomicc directive.
674   void addAtomicDirectiveLoc(SourceLocation Loc) {
675     if (AtomicLocation.isInvalid())
676       AtomicLocation = Loc;
677   }
678 
679   /// Returns the location of the first encountered atomic directive in the
680   /// module.
681   SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
682 
683   // Return previously encountered target region locations.
684   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
685     return TargetLocations;
686   }
687 
688   /// Set default data sharing attribute to none.
689   void setDefaultDSANone(SourceLocation Loc) {
690     getTopOfStack().DefaultAttr = DSA_none;
691     getTopOfStack().DefaultAttrLoc = Loc;
692   }
693   /// Set default data sharing attribute to shared.
694   void setDefaultDSAShared(SourceLocation Loc) {
695     getTopOfStack().DefaultAttr = DSA_shared;
696     getTopOfStack().DefaultAttrLoc = Loc;
697   }
698   /// Set default data sharing attribute to firstprivate.
699   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
700     getTopOfStack().DefaultAttr = DSA_firstprivate;
701     getTopOfStack().DefaultAttrLoc = Loc;
702   }
703   /// Set default data mapping attribute to Modifier:Kind
704   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
705                          OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
706     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
707     DMI.ImplicitBehavior = M;
708     DMI.SLoc = Loc;
709   }
710   /// Check whether the implicit-behavior has been set in defaultmap
711   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
712     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
713       return getTopOfStack()
714                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
715                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
716              getTopOfStack()
717                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
718                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
719              getTopOfStack()
720                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
721                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
722     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
723            OMPC_DEFAULTMAP_MODIFIER_unknown;
724   }
725 
726   ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
727     return ConstructTraits;
728   }
729   void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
730                             bool ScopeEntry) {
731     if (ScopeEntry)
732       ConstructTraits.append(Traits.begin(), Traits.end());
733     else
734       for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
735         llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
736         assert(Top == Trait && "Something left a trait on the stack!");
737         (void)Trait;
738         (void)Top;
739       }
740   }
741 
742   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
743     return getStackSize() <= Level ? DSA_unspecified
744                                    : getStackElemAtLevel(Level).DefaultAttr;
745   }
746   DefaultDataSharingAttributes getDefaultDSA() const {
747     return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
748   }
749   SourceLocation getDefaultDSALocation() const {
750     return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
751   }
752   OpenMPDefaultmapClauseModifier
753   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
754     return isStackEmpty()
755                ? OMPC_DEFAULTMAP_MODIFIER_unknown
756                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
757   }
758   OpenMPDefaultmapClauseModifier
759   getDefaultmapModifierAtLevel(unsigned Level,
760                                OpenMPDefaultmapClauseKind Kind) const {
761     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
762   }
763   bool isDefaultmapCapturedByRef(unsigned Level,
764                                  OpenMPDefaultmapClauseKind Kind) const {
765     OpenMPDefaultmapClauseModifier M =
766         getDefaultmapModifierAtLevel(Level, Kind);
767     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
768       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
769              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
770              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
771              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
772     }
773     return true;
774   }
775   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
776                                      OpenMPDefaultmapClauseKind Kind) {
777     switch (Kind) {
778     case OMPC_DEFAULTMAP_scalar:
779     case OMPC_DEFAULTMAP_pointer:
780       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
781              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
782              (M == OMPC_DEFAULTMAP_MODIFIER_default);
783     case OMPC_DEFAULTMAP_aggregate:
784       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
785     default:
786       break;
787     }
788     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
789   }
790   bool mustBeFirstprivateAtLevel(unsigned Level,
791                                  OpenMPDefaultmapClauseKind Kind) const {
792     OpenMPDefaultmapClauseModifier M =
793         getDefaultmapModifierAtLevel(Level, Kind);
794     return mustBeFirstprivateBase(M, Kind);
795   }
796   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
797     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
798     return mustBeFirstprivateBase(M, Kind);
799   }
800 
801   /// Checks if the specified variable is a threadprivate.
802   bool isThreadPrivate(VarDecl *D) {
803     const DSAVarData DVar = getTopDSA(D, false);
804     return isOpenMPThreadPrivate(DVar.CKind);
805   }
806 
807   /// Marks current region as ordered (it has an 'ordered' clause).
808   void setOrderedRegion(bool IsOrdered, const Expr *Param,
809                         OMPOrderedClause *Clause) {
810     if (IsOrdered)
811       getTopOfStack().OrderedRegion.emplace(Param, Clause);
812     else
813       getTopOfStack().OrderedRegion.reset();
814   }
815   /// Returns true, if region is ordered (has associated 'ordered' clause),
816   /// false - otherwise.
817   bool isOrderedRegion() const {
818     if (const SharingMapTy *Top = getTopOfStackOrNull())
819       return Top->OrderedRegion.hasValue();
820     return false;
821   }
822   /// Returns optional parameter for the ordered region.
823   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
824     if (const SharingMapTy *Top = getTopOfStackOrNull())
825       if (Top->OrderedRegion.hasValue())
826         return Top->OrderedRegion.getValue();
827     return std::make_pair(nullptr, nullptr);
828   }
829   /// Returns true, if parent region is ordered (has associated
830   /// 'ordered' clause), false - otherwise.
831   bool isParentOrderedRegion() const {
832     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
833       return Parent->OrderedRegion.hasValue();
834     return false;
835   }
836   /// Returns optional parameter for the ordered region.
837   std::pair<const Expr *, OMPOrderedClause *>
838   getParentOrderedRegionParam() const {
839     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
840       if (Parent->OrderedRegion.hasValue())
841         return Parent->OrderedRegion.getValue();
842     return std::make_pair(nullptr, nullptr);
843   }
844   /// Marks current region as nowait (it has a 'nowait' clause).
845   void setNowaitRegion(bool IsNowait = true) {
846     getTopOfStack().NowaitRegion = IsNowait;
847   }
848   /// Returns true, if parent region is nowait (has associated
849   /// 'nowait' clause), false - otherwise.
850   bool isParentNowaitRegion() const {
851     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
852       return Parent->NowaitRegion;
853     return false;
854   }
855   /// Marks current region as untied (it has a 'untied' clause).
856   void setUntiedRegion(bool IsUntied = true) {
857     getTopOfStack().UntiedRegion = IsUntied;
858   }
859   /// Return true if current region is untied.
860   bool isUntiedRegion() const {
861     const SharingMapTy *Top = getTopOfStackOrNull();
862     return Top ? Top->UntiedRegion : false;
863   }
864   /// Marks parent region as cancel region.
865   void setParentCancelRegion(bool Cancel = true) {
866     if (SharingMapTy *Parent = getSecondOnStackOrNull())
867       Parent->CancelRegion |= Cancel;
868   }
869   /// Return true if current region has inner cancel construct.
870   bool isCancelRegion() const {
871     const SharingMapTy *Top = getTopOfStackOrNull();
872     return Top ? Top->CancelRegion : false;
873   }
874 
875   /// Mark that parent region already has scan directive.
876   void setParentHasScanDirective(SourceLocation Loc) {
877     if (SharingMapTy *Parent = getSecondOnStackOrNull())
878       Parent->PrevScanLocation = Loc;
879   }
880   /// Return true if current region has inner cancel construct.
881   bool doesParentHasScanDirective() const {
882     const SharingMapTy *Top = getSecondOnStackOrNull();
883     return Top ? Top->PrevScanLocation.isValid() : false;
884   }
885   /// Return true if current region has inner cancel construct.
886   SourceLocation getParentScanDirectiveLoc() const {
887     const SharingMapTy *Top = getSecondOnStackOrNull();
888     return Top ? Top->PrevScanLocation : SourceLocation();
889   }
890   /// Mark that parent region already has ordered directive.
891   void setParentHasOrderedDirective(SourceLocation Loc) {
892     if (SharingMapTy *Parent = getSecondOnStackOrNull())
893       Parent->PrevOrderedLocation = Loc;
894   }
895   /// Return true if current region has inner ordered construct.
896   bool doesParentHasOrderedDirective() const {
897     const SharingMapTy *Top = getSecondOnStackOrNull();
898     return Top ? Top->PrevOrderedLocation.isValid() : false;
899   }
900   /// Returns the location of the previously specified ordered directive.
901   SourceLocation getParentOrderedDirectiveLoc() const {
902     const SharingMapTy *Top = getSecondOnStackOrNull();
903     return Top ? Top->PrevOrderedLocation : SourceLocation();
904   }
905 
906   /// Set collapse value for the region.
907   void setAssociatedLoops(unsigned Val) {
908     getTopOfStack().AssociatedLoops = Val;
909     if (Val > 1)
910       getTopOfStack().HasMutipleLoops = true;
911   }
912   /// Return collapse value for region.
913   unsigned getAssociatedLoops() const {
914     const SharingMapTy *Top = getTopOfStackOrNull();
915     return Top ? Top->AssociatedLoops : 0;
916   }
917   /// Returns true if the construct is associated with multiple loops.
918   bool hasMutipleLoops() const {
919     const SharingMapTy *Top = getTopOfStackOrNull();
920     return Top ? Top->HasMutipleLoops : false;
921   }
922 
923   /// Marks current target region as one with closely nested teams
924   /// region.
925   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
926     if (SharingMapTy *Parent = getSecondOnStackOrNull())
927       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
928   }
929   /// Returns true, if current region has closely nested teams region.
930   bool hasInnerTeamsRegion() const {
931     return getInnerTeamsRegionLoc().isValid();
932   }
933   /// Returns location of the nested teams region (if any).
934   SourceLocation getInnerTeamsRegionLoc() const {
935     const SharingMapTy *Top = getTopOfStackOrNull();
936     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
937   }
938 
939   Scope *getCurScope() const {
940     const SharingMapTy *Top = getTopOfStackOrNull();
941     return Top ? Top->CurScope : nullptr;
942   }
943   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
944   SourceLocation getConstructLoc() const {
945     const SharingMapTy *Top = getTopOfStackOrNull();
946     return Top ? Top->ConstructLoc : SourceLocation();
947   }
948 
949   /// Do the check specified in \a Check to all component lists and return true
950   /// if any issue is found.
951   bool checkMappableExprComponentListsForDecl(
952       const ValueDecl *VD, bool CurrentRegionOnly,
953       const llvm::function_ref<
954           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
955                OpenMPClauseKind)>
956           Check) const {
957     if (isStackEmpty())
958       return false;
959     auto SI = begin();
960     auto SE = end();
961 
962     if (SI == SE)
963       return false;
964 
965     if (CurrentRegionOnly)
966       SE = std::next(SI);
967     else
968       std::advance(SI, 1);
969 
970     for (; SI != SE; ++SI) {
971       auto MI = SI->MappedExprComponents.find(VD);
972       if (MI != SI->MappedExprComponents.end())
973         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
974              MI->second.Components)
975           if (Check(L, MI->second.Kind))
976             return true;
977     }
978     return false;
979   }
980 
981   /// Do the check specified in \a Check to all component lists at a given level
982   /// and return true if any issue is found.
983   bool checkMappableExprComponentListsForDeclAtLevel(
984       const ValueDecl *VD, unsigned Level,
985       const llvm::function_ref<
986           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
987                OpenMPClauseKind)>
988           Check) const {
989     if (getStackSize() <= Level)
990       return false;
991 
992     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
993     auto MI = StackElem.MappedExprComponents.find(VD);
994     if (MI != StackElem.MappedExprComponents.end())
995       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
996            MI->second.Components)
997         if (Check(L, MI->second.Kind))
998           return true;
999     return false;
1000   }
1001 
1002   /// Create a new mappable expression component list associated with a given
1003   /// declaration and initialize it with the provided list of components.
1004   void addMappableExpressionComponents(
1005       const ValueDecl *VD,
1006       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
1007       OpenMPClauseKind WhereFoundClauseKind) {
1008     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
1009     // Create new entry and append the new components there.
1010     MEC.Components.resize(MEC.Components.size() + 1);
1011     MEC.Components.back().append(Components.begin(), Components.end());
1012     MEC.Kind = WhereFoundClauseKind;
1013   }
1014 
1015   unsigned getNestingLevel() const {
1016     assert(!isStackEmpty());
1017     return getStackSize() - 1;
1018   }
1019   void addDoacrossDependClause(OMPDependClause *C,
1020                                const OperatorOffsetTy &OpsOffs) {
1021     SharingMapTy *Parent = getSecondOnStackOrNull();
1022     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1023     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1024   }
1025   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1026   getDoacrossDependClauses() const {
1027     const SharingMapTy &StackElem = getTopOfStack();
1028     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1029       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1030       return llvm::make_range(Ref.begin(), Ref.end());
1031     }
1032     return llvm::make_range(StackElem.DoacrossDepends.end(),
1033                             StackElem.DoacrossDepends.end());
1034   }
1035 
1036   // Store types of classes which have been explicitly mapped
1037   void addMappedClassesQualTypes(QualType QT) {
1038     SharingMapTy &StackElem = getTopOfStack();
1039     StackElem.MappedClassesQualTypes.insert(QT);
1040   }
1041 
1042   // Return set of mapped classes types
1043   bool isClassPreviouslyMapped(QualType QT) const {
1044     const SharingMapTy &StackElem = getTopOfStack();
1045     return StackElem.MappedClassesQualTypes.contains(QT);
1046   }
1047 
1048   /// Adds global declare target to the parent target region.
1049   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1050     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1051                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1052            "Expected declare target link global.");
1053     for (auto &Elem : *this) {
1054       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1055         Elem.DeclareTargetLinkVarDecls.push_back(E);
1056         return;
1057       }
1058     }
1059   }
1060 
1061   /// Returns the list of globals with declare target link if current directive
1062   /// is target.
1063   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1064     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1065            "Expected target executable directive.");
1066     return getTopOfStack().DeclareTargetLinkVarDecls;
1067   }
1068 
1069   /// Adds list of allocators expressions.
1070   void addInnerAllocatorExpr(Expr *E) {
1071     getTopOfStack().InnerUsedAllocators.push_back(E);
1072   }
1073   /// Return list of used allocators.
1074   ArrayRef<Expr *> getInnerAllocators() const {
1075     return getTopOfStack().InnerUsedAllocators;
1076   }
1077   /// Marks the declaration as implicitly firstprivate nin the task-based
1078   /// regions.
1079   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1080     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1081   }
1082   /// Checks if the decl is implicitly firstprivate in the task-based region.
1083   bool isImplicitTaskFirstprivate(Decl *D) const {
1084     return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1085   }
1086 
1087   /// Marks decl as used in uses_allocators clause as the allocator.
1088   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1089     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1090   }
1091   /// Checks if specified decl is used in uses allocator clause as the
1092   /// allocator.
1093   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1094                                                         const Decl *D) const {
1095     const SharingMapTy &StackElem = getTopOfStack();
1096     auto I = StackElem.UsesAllocatorsDecls.find(D);
1097     if (I == StackElem.UsesAllocatorsDecls.end())
1098       return None;
1099     return I->getSecond();
1100   }
1101   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1102     const SharingMapTy &StackElem = getTopOfStack();
1103     auto I = StackElem.UsesAllocatorsDecls.find(D);
1104     if (I == StackElem.UsesAllocatorsDecls.end())
1105       return None;
1106     return I->getSecond();
1107   }
1108 
1109   void addDeclareMapperVarRef(Expr *Ref) {
1110     SharingMapTy &StackElem = getTopOfStack();
1111     StackElem.DeclareMapperVar = Ref;
1112   }
1113   const Expr *getDeclareMapperVarRef() const {
1114     const SharingMapTy *Top = getTopOfStackOrNull();
1115     return Top ? Top->DeclareMapperVar : nullptr;
1116   }
1117 };
1118 
1119 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1120   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1121 }
1122 
1123 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1124   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1125          DKind == OMPD_unknown;
1126 }
1127 
1128 } // namespace
1129 
1130 static const Expr *getExprAsWritten(const Expr *E) {
1131   if (const auto *FE = dyn_cast<FullExpr>(E))
1132     E = FE->getSubExpr();
1133 
1134   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1135     E = MTE->getSubExpr();
1136 
1137   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1138     E = Binder->getSubExpr();
1139 
1140   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1141     E = ICE->getSubExprAsWritten();
1142   return E->IgnoreParens();
1143 }
1144 
1145 static Expr *getExprAsWritten(Expr *E) {
1146   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1147 }
1148 
1149 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1150   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1151     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1152       D = ME->getMemberDecl();
1153   const auto *VD = dyn_cast<VarDecl>(D);
1154   const auto *FD = dyn_cast<FieldDecl>(D);
1155   if (VD != nullptr) {
1156     VD = VD->getCanonicalDecl();
1157     D = VD;
1158   } else {
1159     assert(FD);
1160     FD = FD->getCanonicalDecl();
1161     D = FD;
1162   }
1163   return D;
1164 }
1165 
1166 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1167   return const_cast<ValueDecl *>(
1168       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1169 }
1170 
1171 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1172                                           ValueDecl *D) const {
1173   D = getCanonicalDecl(D);
1174   auto *VD = dyn_cast<VarDecl>(D);
1175   const auto *FD = dyn_cast<FieldDecl>(D);
1176   DSAVarData DVar;
1177   if (Iter == end()) {
1178     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1179     // in a region but not in construct]
1180     //  File-scope or namespace-scope variables referenced in called routines
1181     //  in the region are shared unless they appear in a threadprivate
1182     //  directive.
1183     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1184       DVar.CKind = OMPC_shared;
1185 
1186     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1187     // in a region but not in construct]
1188     //  Variables with static storage duration that are declared in called
1189     //  routines in the region are shared.
1190     if (VD && VD->hasGlobalStorage())
1191       DVar.CKind = OMPC_shared;
1192 
1193     // Non-static data members are shared by default.
1194     if (FD)
1195       DVar.CKind = OMPC_shared;
1196 
1197     return DVar;
1198   }
1199 
1200   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1201   // in a Construct, C/C++, predetermined, p.1]
1202   // Variables with automatic storage duration that are declared in a scope
1203   // inside the construct are private.
1204   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1205       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1206     DVar.CKind = OMPC_private;
1207     return DVar;
1208   }
1209 
1210   DVar.DKind = Iter->Directive;
1211   // Explicitly specified attributes and local variables with predetermined
1212   // attributes.
1213   if (Iter->SharingMap.count(D)) {
1214     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1215     DVar.RefExpr = Data.RefExpr.getPointer();
1216     DVar.PrivateCopy = Data.PrivateCopy;
1217     DVar.CKind = Data.Attributes;
1218     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1219     DVar.Modifier = Data.Modifier;
1220     DVar.AppliedToPointee = Data.AppliedToPointee;
1221     return DVar;
1222   }
1223 
1224   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1225   // in a Construct, C/C++, implicitly determined, p.1]
1226   //  In a parallel or task construct, the data-sharing attributes of these
1227   //  variables are determined by the default clause, if present.
1228   switch (Iter->DefaultAttr) {
1229   case DSA_shared:
1230     DVar.CKind = OMPC_shared;
1231     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1232     return DVar;
1233   case DSA_none:
1234     return DVar;
1235   case DSA_firstprivate:
1236     if (VD->getStorageDuration() == SD_Static &&
1237         VD->getDeclContext()->isFileContext()) {
1238       DVar.CKind = OMPC_unknown;
1239     } else {
1240       DVar.CKind = OMPC_firstprivate;
1241     }
1242     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1243     return DVar;
1244   case DSA_unspecified:
1245     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1246     // in a Construct, implicitly determined, p.2]
1247     //  In a parallel construct, if no default clause is present, these
1248     //  variables are shared.
1249     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1250     if ((isOpenMPParallelDirective(DVar.DKind) &&
1251          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1252         isOpenMPTeamsDirective(DVar.DKind)) {
1253       DVar.CKind = OMPC_shared;
1254       return DVar;
1255     }
1256 
1257     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1258     // in a Construct, implicitly determined, p.4]
1259     //  In a task construct, if no default clause is present, a variable that in
1260     //  the enclosing context is determined to be shared by all implicit tasks
1261     //  bound to the current team is shared.
1262     if (isOpenMPTaskingDirective(DVar.DKind)) {
1263       DSAVarData DVarTemp;
1264       const_iterator I = Iter, E = end();
1265       do {
1266         ++I;
1267         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1268         // Referenced in a Construct, implicitly determined, p.6]
1269         //  In a task construct, if no default clause is present, a variable
1270         //  whose data-sharing attribute is not determined by the rules above is
1271         //  firstprivate.
1272         DVarTemp = getDSA(I, D);
1273         if (DVarTemp.CKind != OMPC_shared) {
1274           DVar.RefExpr = nullptr;
1275           DVar.CKind = OMPC_firstprivate;
1276           return DVar;
1277         }
1278       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1279       DVar.CKind =
1280           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1281       return DVar;
1282     }
1283   }
1284   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1285   // in a Construct, implicitly determined, p.3]
1286   //  For constructs other than task, if no default clause is present, these
1287   //  variables inherit their data-sharing attributes from the enclosing
1288   //  context.
1289   return getDSA(++Iter, D);
1290 }
1291 
1292 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1293                                          const Expr *NewDE) {
1294   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1295   D = getCanonicalDecl(D);
1296   SharingMapTy &StackElem = getTopOfStack();
1297   auto It = StackElem.AlignedMap.find(D);
1298   if (It == StackElem.AlignedMap.end()) {
1299     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1300     StackElem.AlignedMap[D] = NewDE;
1301     return nullptr;
1302   }
1303   assert(It->second && "Unexpected nullptr expr in the aligned map");
1304   return It->second;
1305 }
1306 
1307 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1308                                              const Expr *NewDE) {
1309   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1310   D = getCanonicalDecl(D);
1311   SharingMapTy &StackElem = getTopOfStack();
1312   auto It = StackElem.NontemporalMap.find(D);
1313   if (It == StackElem.NontemporalMap.end()) {
1314     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1315     StackElem.NontemporalMap[D] = NewDE;
1316     return nullptr;
1317   }
1318   assert(It->second && "Unexpected nullptr expr in the aligned map");
1319   return It->second;
1320 }
1321 
1322 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1323   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1324   D = getCanonicalDecl(D);
1325   SharingMapTy &StackElem = getTopOfStack();
1326   StackElem.LCVMap.try_emplace(
1327       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1328 }
1329 
1330 const DSAStackTy::LCDeclInfo
1331 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1332   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1333   D = getCanonicalDecl(D);
1334   const SharingMapTy &StackElem = getTopOfStack();
1335   auto It = StackElem.LCVMap.find(D);
1336   if (It != StackElem.LCVMap.end())
1337     return It->second;
1338   return {0, nullptr};
1339 }
1340 
1341 const DSAStackTy::LCDeclInfo
1342 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1343   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1344   D = getCanonicalDecl(D);
1345   for (unsigned I = Level + 1; I > 0; --I) {
1346     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1347     auto It = StackElem.LCVMap.find(D);
1348     if (It != StackElem.LCVMap.end())
1349       return It->second;
1350   }
1351   return {0, nullptr};
1352 }
1353 
1354 const DSAStackTy::LCDeclInfo
1355 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1356   const SharingMapTy *Parent = getSecondOnStackOrNull();
1357   assert(Parent && "Data-sharing attributes stack is empty");
1358   D = getCanonicalDecl(D);
1359   auto It = Parent->LCVMap.find(D);
1360   if (It != Parent->LCVMap.end())
1361     return It->second;
1362   return {0, nullptr};
1363 }
1364 
1365 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1366   const SharingMapTy *Parent = getSecondOnStackOrNull();
1367   assert(Parent && "Data-sharing attributes stack is empty");
1368   if (Parent->LCVMap.size() < I)
1369     return nullptr;
1370   for (const auto &Pair : Parent->LCVMap)
1371     if (Pair.second.first == I)
1372       return Pair.first;
1373   return nullptr;
1374 }
1375 
1376 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1377                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1378                         bool AppliedToPointee) {
1379   D = getCanonicalDecl(D);
1380   if (A == OMPC_threadprivate) {
1381     DSAInfo &Data = Threadprivates[D];
1382     Data.Attributes = A;
1383     Data.RefExpr.setPointer(E);
1384     Data.PrivateCopy = nullptr;
1385     Data.Modifier = Modifier;
1386   } else {
1387     DSAInfo &Data = getTopOfStack().SharingMap[D];
1388     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1389            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1390            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1391            (isLoopControlVariable(D).first && A == OMPC_private));
1392     Data.Modifier = Modifier;
1393     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1394       Data.RefExpr.setInt(/*IntVal=*/true);
1395       return;
1396     }
1397     const bool IsLastprivate =
1398         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1399     Data.Attributes = A;
1400     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1401     Data.PrivateCopy = PrivateCopy;
1402     Data.AppliedToPointee = AppliedToPointee;
1403     if (PrivateCopy) {
1404       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1405       Data.Modifier = Modifier;
1406       Data.Attributes = A;
1407       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1408       Data.PrivateCopy = nullptr;
1409       Data.AppliedToPointee = AppliedToPointee;
1410     }
1411   }
1412 }
1413 
1414 /// Build a variable declaration for OpenMP loop iteration variable.
1415 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1416                              StringRef Name, const AttrVec *Attrs = nullptr,
1417                              DeclRefExpr *OrigRef = nullptr) {
1418   DeclContext *DC = SemaRef.CurContext;
1419   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1420   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1421   auto *Decl =
1422       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1423   if (Attrs) {
1424     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1425          I != E; ++I)
1426       Decl->addAttr(*I);
1427   }
1428   Decl->setImplicit();
1429   if (OrigRef) {
1430     Decl->addAttr(
1431         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1432   }
1433   return Decl;
1434 }
1435 
1436 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1437                                      SourceLocation Loc,
1438                                      bool RefersToCapture = false) {
1439   D->setReferenced();
1440   D->markUsed(S.Context);
1441   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1442                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1443                              VK_LValue);
1444 }
1445 
1446 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1447                                            BinaryOperatorKind BOK) {
1448   D = getCanonicalDecl(D);
1449   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1450   assert(
1451       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1452       "Additional reduction info may be specified only for reduction items.");
1453   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1454   assert(ReductionData.ReductionRange.isInvalid() &&
1455          (getTopOfStack().Directive == OMPD_taskgroup ||
1456           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1457             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1458            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1459          "Additional reduction info may be specified only once for reduction "
1460          "items.");
1461   ReductionData.set(BOK, SR);
1462   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1463   if (!TaskgroupReductionRef) {
1464     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1465                                SemaRef.Context.VoidPtrTy, ".task_red.");
1466     TaskgroupReductionRef =
1467         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1468   }
1469 }
1470 
1471 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1472                                            const Expr *ReductionRef) {
1473   D = getCanonicalDecl(D);
1474   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1475   assert(
1476       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1477       "Additional reduction info may be specified only for reduction items.");
1478   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1479   assert(ReductionData.ReductionRange.isInvalid() &&
1480          (getTopOfStack().Directive == OMPD_taskgroup ||
1481           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1482             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1483            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1484          "Additional reduction info may be specified only once for reduction "
1485          "items.");
1486   ReductionData.set(ReductionRef, SR);
1487   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1488   if (!TaskgroupReductionRef) {
1489     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1490                                SemaRef.Context.VoidPtrTy, ".task_red.");
1491     TaskgroupReductionRef =
1492         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1493   }
1494 }
1495 
1496 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1497     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1498     Expr *&TaskgroupDescriptor) const {
1499   D = getCanonicalDecl(D);
1500   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1501   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1502     const DSAInfo &Data = I->SharingMap.lookup(D);
1503     if (Data.Attributes != OMPC_reduction ||
1504         Data.Modifier != OMPC_REDUCTION_task)
1505       continue;
1506     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1507     if (!ReductionData.ReductionOp ||
1508         ReductionData.ReductionOp.is<const Expr *>())
1509       return DSAVarData();
1510     SR = ReductionData.ReductionRange;
1511     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1512     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1513                                        "expression for the descriptor is not "
1514                                        "set.");
1515     TaskgroupDescriptor = I->TaskgroupReductionRef;
1516     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1517                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1518                       /*AppliedToPointee=*/false);
1519   }
1520   return DSAVarData();
1521 }
1522 
1523 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1524     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1525     Expr *&TaskgroupDescriptor) const {
1526   D = getCanonicalDecl(D);
1527   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1528   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1529     const DSAInfo &Data = I->SharingMap.lookup(D);
1530     if (Data.Attributes != OMPC_reduction ||
1531         Data.Modifier != OMPC_REDUCTION_task)
1532       continue;
1533     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1534     if (!ReductionData.ReductionOp ||
1535         !ReductionData.ReductionOp.is<const Expr *>())
1536       return DSAVarData();
1537     SR = ReductionData.ReductionRange;
1538     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1539     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1540                                        "expression for the descriptor is not "
1541                                        "set.");
1542     TaskgroupDescriptor = I->TaskgroupReductionRef;
1543     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1544                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1545                       /*AppliedToPointee=*/false);
1546   }
1547   return DSAVarData();
1548 }
1549 
1550 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1551   D = D->getCanonicalDecl();
1552   for (const_iterator E = end(); I != E; ++I) {
1553     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1554         isOpenMPTargetExecutionDirective(I->Directive)) {
1555       if (I->CurScope) {
1556         Scope *TopScope = I->CurScope->getParent();
1557         Scope *CurScope = getCurScope();
1558         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1559           CurScope = CurScope->getParent();
1560         return CurScope != TopScope;
1561       }
1562       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1563         if (I->Context == DC)
1564           return true;
1565       return false;
1566     }
1567   }
1568   return false;
1569 }
1570 
1571 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1572                                   bool AcceptIfMutable = true,
1573                                   bool *IsClassType = nullptr) {
1574   ASTContext &Context = SemaRef.getASTContext();
1575   Type = Type.getNonReferenceType().getCanonicalType();
1576   bool IsConstant = Type.isConstant(Context);
1577   Type = Context.getBaseElementType(Type);
1578   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1579                                 ? Type->getAsCXXRecordDecl()
1580                                 : nullptr;
1581   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1582     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1583       RD = CTD->getTemplatedDecl();
1584   if (IsClassType)
1585     *IsClassType = RD;
1586   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1587                          RD->hasDefinition() && RD->hasMutableFields());
1588 }
1589 
1590 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1591                                       QualType Type, OpenMPClauseKind CKind,
1592                                       SourceLocation ELoc,
1593                                       bool AcceptIfMutable = true,
1594                                       bool ListItemNotVar = false) {
1595   ASTContext &Context = SemaRef.getASTContext();
1596   bool IsClassType;
1597   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1598     unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1599                     : IsClassType  ? diag::err_omp_const_not_mutable_variable
1600                                    : diag::err_omp_const_variable;
1601     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1602     if (!ListItemNotVar && D) {
1603       const VarDecl *VD = dyn_cast<VarDecl>(D);
1604       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1605                                VarDecl::DeclarationOnly;
1606       SemaRef.Diag(D->getLocation(),
1607                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1608           << D;
1609     }
1610     return true;
1611   }
1612   return false;
1613 }
1614 
1615 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1616                                                    bool FromParent) {
1617   D = getCanonicalDecl(D);
1618   DSAVarData DVar;
1619 
1620   auto *VD = dyn_cast<VarDecl>(D);
1621   auto TI = Threadprivates.find(D);
1622   if (TI != Threadprivates.end()) {
1623     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1624     DVar.CKind = OMPC_threadprivate;
1625     DVar.Modifier = TI->getSecond().Modifier;
1626     return DVar;
1627   }
1628   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1629     DVar.RefExpr = buildDeclRefExpr(
1630         SemaRef, VD, D->getType().getNonReferenceType(),
1631         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1632     DVar.CKind = OMPC_threadprivate;
1633     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1634     return DVar;
1635   }
1636   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1637   // in a Construct, C/C++, predetermined, p.1]
1638   //  Variables appearing in threadprivate directives are threadprivate.
1639   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1640        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1641          SemaRef.getLangOpts().OpenMPUseTLS &&
1642          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1643       (VD && VD->getStorageClass() == SC_Register &&
1644        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1645     DVar.RefExpr = buildDeclRefExpr(
1646         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1647     DVar.CKind = OMPC_threadprivate;
1648     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1649     return DVar;
1650   }
1651   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1652       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1653       !isLoopControlVariable(D).first) {
1654     const_iterator IterTarget =
1655         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1656           return isOpenMPTargetExecutionDirective(Data.Directive);
1657         });
1658     if (IterTarget != end()) {
1659       const_iterator ParentIterTarget = IterTarget + 1;
1660       for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1661         if (isOpenMPLocal(VD, Iter)) {
1662           DVar.RefExpr =
1663               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1664                                D->getLocation());
1665           DVar.CKind = OMPC_threadprivate;
1666           return DVar;
1667         }
1668       }
1669       if (!isClauseParsingMode() || IterTarget != begin()) {
1670         auto DSAIter = IterTarget->SharingMap.find(D);
1671         if (DSAIter != IterTarget->SharingMap.end() &&
1672             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1673           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1674           DVar.CKind = OMPC_threadprivate;
1675           return DVar;
1676         }
1677         const_iterator End = end();
1678         if (!SemaRef.isOpenMPCapturedByRef(D,
1679                                            std::distance(ParentIterTarget, End),
1680                                            /*OpenMPCaptureLevel=*/0)) {
1681           DVar.RefExpr =
1682               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1683                                IterTarget->ConstructLoc);
1684           DVar.CKind = OMPC_threadprivate;
1685           return DVar;
1686         }
1687       }
1688     }
1689   }
1690 
1691   if (isStackEmpty())
1692     // Not in OpenMP execution region and top scope was already checked.
1693     return DVar;
1694 
1695   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1696   // in a Construct, C/C++, predetermined, p.4]
1697   //  Static data members are shared.
1698   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1699   // in a Construct, C/C++, predetermined, p.7]
1700   //  Variables with static storage duration that are declared in a scope
1701   //  inside the construct are shared.
1702   if (VD && VD->isStaticDataMember()) {
1703     // Check for explicitly specified attributes.
1704     const_iterator I = begin();
1705     const_iterator EndI = end();
1706     if (FromParent && I != EndI)
1707       ++I;
1708     if (I != EndI) {
1709       auto It = I->SharingMap.find(D);
1710       if (It != I->SharingMap.end()) {
1711         const DSAInfo &Data = It->getSecond();
1712         DVar.RefExpr = Data.RefExpr.getPointer();
1713         DVar.PrivateCopy = Data.PrivateCopy;
1714         DVar.CKind = Data.Attributes;
1715         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1716         DVar.DKind = I->Directive;
1717         DVar.Modifier = Data.Modifier;
1718         DVar.AppliedToPointee = Data.AppliedToPointee;
1719         return DVar;
1720       }
1721     }
1722 
1723     DVar.CKind = OMPC_shared;
1724     return DVar;
1725   }
1726 
1727   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1728   // The predetermined shared attribute for const-qualified types having no
1729   // mutable members was removed after OpenMP 3.1.
1730   if (SemaRef.LangOpts.OpenMP <= 31) {
1731     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1732     // in a Construct, C/C++, predetermined, p.6]
1733     //  Variables with const qualified type having no mutable member are
1734     //  shared.
1735     if (isConstNotMutableType(SemaRef, D->getType())) {
1736       // Variables with const-qualified type having no mutable member may be
1737       // listed in a firstprivate clause, even if they are static data members.
1738       DSAVarData DVarTemp = hasInnermostDSA(
1739           D,
1740           [](OpenMPClauseKind C, bool) {
1741             return C == OMPC_firstprivate || C == OMPC_shared;
1742           },
1743           MatchesAlways, FromParent);
1744       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1745         return DVarTemp;
1746 
1747       DVar.CKind = OMPC_shared;
1748       return DVar;
1749     }
1750   }
1751 
1752   // Explicitly specified attributes and local variables with predetermined
1753   // attributes.
1754   const_iterator I = begin();
1755   const_iterator EndI = end();
1756   if (FromParent && I != EndI)
1757     ++I;
1758   if (I == EndI)
1759     return DVar;
1760   auto It = I->SharingMap.find(D);
1761   if (It != I->SharingMap.end()) {
1762     const DSAInfo &Data = It->getSecond();
1763     DVar.RefExpr = Data.RefExpr.getPointer();
1764     DVar.PrivateCopy = Data.PrivateCopy;
1765     DVar.CKind = Data.Attributes;
1766     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1767     DVar.DKind = I->Directive;
1768     DVar.Modifier = Data.Modifier;
1769     DVar.AppliedToPointee = Data.AppliedToPointee;
1770   }
1771 
1772   return DVar;
1773 }
1774 
1775 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1776                                                         bool FromParent) const {
1777   if (isStackEmpty()) {
1778     const_iterator I;
1779     return getDSA(I, D);
1780   }
1781   D = getCanonicalDecl(D);
1782   const_iterator StartI = begin();
1783   const_iterator EndI = end();
1784   if (FromParent && StartI != EndI)
1785     ++StartI;
1786   return getDSA(StartI, D);
1787 }
1788 
1789 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1790                                                         unsigned Level) const {
1791   if (getStackSize() <= Level)
1792     return DSAVarData();
1793   D = getCanonicalDecl(D);
1794   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1795   return getDSA(StartI, D);
1796 }
1797 
1798 const DSAStackTy::DSAVarData
1799 DSAStackTy::hasDSA(ValueDecl *D,
1800                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1801                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1802                    bool FromParent) const {
1803   if (isStackEmpty())
1804     return {};
1805   D = getCanonicalDecl(D);
1806   const_iterator I = begin();
1807   const_iterator EndI = end();
1808   if (FromParent && I != EndI)
1809     ++I;
1810   for (; I != EndI; ++I) {
1811     if (!DPred(I->Directive) &&
1812         !isImplicitOrExplicitTaskingRegion(I->Directive))
1813       continue;
1814     const_iterator NewI = I;
1815     DSAVarData DVar = getDSA(NewI, D);
1816     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1817       return DVar;
1818   }
1819   return {};
1820 }
1821 
1822 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1823     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1824     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1825     bool FromParent) const {
1826   if (isStackEmpty())
1827     return {};
1828   D = getCanonicalDecl(D);
1829   const_iterator StartI = begin();
1830   const_iterator EndI = end();
1831   if (FromParent && StartI != EndI)
1832     ++StartI;
1833   if (StartI == EndI || !DPred(StartI->Directive))
1834     return {};
1835   const_iterator NewI = StartI;
1836   DSAVarData DVar = getDSA(NewI, D);
1837   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1838              ? DVar
1839              : DSAVarData();
1840 }
1841 
1842 bool DSAStackTy::hasExplicitDSA(
1843     const ValueDecl *D,
1844     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1845     unsigned Level, bool NotLastprivate) const {
1846   if (getStackSize() <= Level)
1847     return false;
1848   D = getCanonicalDecl(D);
1849   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1850   auto I = StackElem.SharingMap.find(D);
1851   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1852       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1853       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1854     return true;
1855   // Check predetermined rules for the loop control variables.
1856   auto LI = StackElem.LCVMap.find(D);
1857   if (LI != StackElem.LCVMap.end())
1858     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1859   return false;
1860 }
1861 
1862 bool DSAStackTy::hasExplicitDirective(
1863     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1864     unsigned Level) const {
1865   if (getStackSize() <= Level)
1866     return false;
1867   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1868   return DPred(StackElem.Directive);
1869 }
1870 
1871 bool DSAStackTy::hasDirective(
1872     const llvm::function_ref<bool(OpenMPDirectiveKind,
1873                                   const DeclarationNameInfo &, SourceLocation)>
1874         DPred,
1875     bool FromParent) const {
1876   // We look only in the enclosing region.
1877   size_t Skip = FromParent ? 2 : 1;
1878   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1879        I != E; ++I) {
1880     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1881       return true;
1882   }
1883   return false;
1884 }
1885 
1886 void Sema::InitDataSharingAttributesStack() {
1887   VarDataSharingAttributesStack = new DSAStackTy(*this);
1888 }
1889 
1890 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1891 
1892 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
1893 
1894 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1895   DSAStack->popFunction(OldFSI);
1896 }
1897 
1898 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1899   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1900          "Expected OpenMP device compilation.");
1901   return !S.isInOpenMPTargetExecutionDirective();
1902 }
1903 
1904 namespace {
1905 /// Status of the function emission on the host/device.
1906 enum class FunctionEmissionStatus {
1907   Emitted,
1908   Discarded,
1909   Unknown,
1910 };
1911 } // anonymous namespace
1912 
1913 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1914                                                          unsigned DiagID,
1915                                                          FunctionDecl *FD) {
1916   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1917          "Expected OpenMP device compilation.");
1918 
1919   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1920   if (FD) {
1921     FunctionEmissionStatus FES = getEmissionStatus(FD);
1922     switch (FES) {
1923     case FunctionEmissionStatus::Emitted:
1924       Kind = SemaDiagnosticBuilder::K_Immediate;
1925       break;
1926     case FunctionEmissionStatus::Unknown:
1927       // TODO: We should always delay diagnostics here in case a target
1928       //       region is in a function we do not emit. However, as the
1929       //       current diagnostics are associated with the function containing
1930       //       the target region and we do not emit that one, we would miss out
1931       //       on diagnostics for the target region itself. We need to anchor
1932       //       the diagnostics with the new generated function *or* ensure we
1933       //       emit diagnostics associated with the surrounding function.
1934       Kind = isOpenMPDeviceDelayedContext(*this)
1935                  ? SemaDiagnosticBuilder::K_Deferred
1936                  : SemaDiagnosticBuilder::K_Immediate;
1937       break;
1938     case FunctionEmissionStatus::TemplateDiscarded:
1939     case FunctionEmissionStatus::OMPDiscarded:
1940       Kind = SemaDiagnosticBuilder::K_Nop;
1941       break;
1942     case FunctionEmissionStatus::CUDADiscarded:
1943       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1944       break;
1945     }
1946   }
1947 
1948   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1949 }
1950 
1951 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1952                                                        unsigned DiagID,
1953                                                        FunctionDecl *FD) {
1954   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1955          "Expected OpenMP host compilation.");
1956 
1957   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1958   if (FD) {
1959     FunctionEmissionStatus FES = getEmissionStatus(FD);
1960     switch (FES) {
1961     case FunctionEmissionStatus::Emitted:
1962       Kind = SemaDiagnosticBuilder::K_Immediate;
1963       break;
1964     case FunctionEmissionStatus::Unknown:
1965       Kind = SemaDiagnosticBuilder::K_Deferred;
1966       break;
1967     case FunctionEmissionStatus::TemplateDiscarded:
1968     case FunctionEmissionStatus::OMPDiscarded:
1969     case FunctionEmissionStatus::CUDADiscarded:
1970       Kind = SemaDiagnosticBuilder::K_Nop;
1971       break;
1972     }
1973   }
1974 
1975   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1976 }
1977 
1978 static OpenMPDefaultmapClauseKind
1979 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1980   if (LO.OpenMP <= 45) {
1981     if (VD->getType().getNonReferenceType()->isScalarType())
1982       return OMPC_DEFAULTMAP_scalar;
1983     return OMPC_DEFAULTMAP_aggregate;
1984   }
1985   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1986     return OMPC_DEFAULTMAP_pointer;
1987   if (VD->getType().getNonReferenceType()->isScalarType())
1988     return OMPC_DEFAULTMAP_scalar;
1989   return OMPC_DEFAULTMAP_aggregate;
1990 }
1991 
1992 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1993                                  unsigned OpenMPCaptureLevel) const {
1994   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1995 
1996   ASTContext &Ctx = getASTContext();
1997   bool IsByRef = true;
1998 
1999   // Find the directive that is associated with the provided scope.
2000   D = cast<ValueDecl>(D->getCanonicalDecl());
2001   QualType Ty = D->getType();
2002 
2003   bool IsVariableUsedInMapClause = false;
2004   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
2005     // This table summarizes how a given variable should be passed to the device
2006     // given its type and the clauses where it appears. This table is based on
2007     // the description in OpenMP 4.5 [2.10.4, target Construct] and
2008     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
2009     //
2010     // =========================================================================
2011     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
2012     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
2013     // =========================================================================
2014     // | scl  |               |     |       |       -       |          | bycopy|
2015     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2016     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2017     // | scl  |       x       |     |       |       -       |          | byref |
2018     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2019     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2020     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2021     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2022     //
2023     // | agg  |      n.a.     |     |       |       -       |          | byref |
2024     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2025     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2026     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2027     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2028     //
2029     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2030     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2031     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2032     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2033     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2034     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2035     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2036     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2037     // =========================================================================
2038     // Legend:
2039     //  scl - scalar
2040     //  ptr - pointer
2041     //  agg - aggregate
2042     //  x - applies
2043     //  - - invalid in this combination
2044     //  [] - mapped with an array section
2045     //  byref - should be mapped by reference
2046     //  byval - should be mapped by value
2047     //  null - initialize a local variable to null on the device
2048     //
2049     // Observations:
2050     //  - All scalar declarations that show up in a map clause have to be passed
2051     //    by reference, because they may have been mapped in the enclosing data
2052     //    environment.
2053     //  - If the scalar value does not fit the size of uintptr, it has to be
2054     //    passed by reference, regardless the result in the table above.
2055     //  - For pointers mapped by value that have either an implicit map or an
2056     //    array section, the runtime library may pass the NULL value to the
2057     //    device instead of the value passed to it by the compiler.
2058 
2059     if (Ty->isReferenceType())
2060       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2061 
2062     // Locate map clauses and see if the variable being captured is referred to
2063     // in any of those clauses. Here we only care about variables, not fields,
2064     // because fields are part of aggregates.
2065     bool IsVariableAssociatedWithSection = false;
2066 
2067     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2068         D, Level,
2069         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2070          D](OMPClauseMappableExprCommon::MappableExprComponentListRef
2071                 MapExprComponents,
2072             OpenMPClauseKind WhereFoundClauseKind) {
2073           // Only the map clause information influences how a variable is
2074           // captured. E.g. is_device_ptr does not require changing the default
2075           // behavior.
2076           if (WhereFoundClauseKind != OMPC_map)
2077             return false;
2078 
2079           auto EI = MapExprComponents.rbegin();
2080           auto EE = MapExprComponents.rend();
2081 
2082           assert(EI != EE && "Invalid map expression!");
2083 
2084           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2085             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2086 
2087           ++EI;
2088           if (EI == EE)
2089             return false;
2090 
2091           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2092               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2093               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2094               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2095             IsVariableAssociatedWithSection = true;
2096             // There is nothing more we need to know about this variable.
2097             return true;
2098           }
2099 
2100           // Keep looking for more map info.
2101           return false;
2102         });
2103 
2104     if (IsVariableUsedInMapClause) {
2105       // If variable is identified in a map clause it is always captured by
2106       // reference except if it is a pointer that is dereferenced somehow.
2107       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2108     } else {
2109       // By default, all the data that has a scalar type is mapped by copy
2110       // (except for reduction variables).
2111       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2112       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2113                  !Ty->isAnyPointerType()) ||
2114                 !Ty->isScalarType() ||
2115                 DSAStack->isDefaultmapCapturedByRef(
2116                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2117                 DSAStack->hasExplicitDSA(
2118                     D,
2119                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2120                       return K == OMPC_reduction && !AppliedToPointee;
2121                     },
2122                     Level);
2123     }
2124   }
2125 
2126   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2127     IsByRef =
2128         ((IsVariableUsedInMapClause &&
2129           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2130               OMPD_target) ||
2131          !(DSAStack->hasExplicitDSA(
2132                D,
2133                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2134                  return K == OMPC_firstprivate ||
2135                         (K == OMPC_reduction && AppliedToPointee);
2136                },
2137                Level, /*NotLastprivate=*/true) ||
2138            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2139         // If the variable is artificial and must be captured by value - try to
2140         // capture by value.
2141         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2142           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2143         // If the variable is implicitly firstprivate and scalar - capture by
2144         // copy
2145         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2146           !DSAStack->hasExplicitDSA(
2147               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2148               Level) &&
2149           !DSAStack->isLoopControlVariable(D, Level).first);
2150   }
2151 
2152   // When passing data by copy, we need to make sure it fits the uintptr size
2153   // and alignment, because the runtime library only deals with uintptr types.
2154   // If it does not fit the uintptr size, we need to pass the data by reference
2155   // instead.
2156   if (!IsByRef &&
2157       (Ctx.getTypeSizeInChars(Ty) >
2158            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2159        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2160     IsByRef = true;
2161   }
2162 
2163   return IsByRef;
2164 }
2165 
2166 unsigned Sema::getOpenMPNestingLevel() const {
2167   assert(getLangOpts().OpenMP);
2168   return DSAStack->getNestingLevel();
2169 }
2170 
2171 bool Sema::isInOpenMPTaskUntiedContext() const {
2172   return isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2173          DSAStack->isUntiedRegion();
2174 }
2175 
2176 bool Sema::isInOpenMPTargetExecutionDirective() const {
2177   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2178           !DSAStack->isClauseParsingMode()) ||
2179          DSAStack->hasDirective(
2180              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2181                 SourceLocation) -> bool {
2182                return isOpenMPTargetExecutionDirective(K);
2183              },
2184              false);
2185 }
2186 
2187 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2188                                     unsigned StopAt) {
2189   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2190   D = getCanonicalDecl(D);
2191 
2192   auto *VD = dyn_cast<VarDecl>(D);
2193   // Do not capture constexpr variables.
2194   if (VD && VD->isConstexpr())
2195     return nullptr;
2196 
2197   // If we want to determine whether the variable should be captured from the
2198   // perspective of the current capturing scope, and we've already left all the
2199   // capturing scopes of the top directive on the stack, check from the
2200   // perspective of its parent directive (if any) instead.
2201   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2202       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2203 
2204   // If we are attempting to capture a global variable in a directive with
2205   // 'target' we return true so that this global is also mapped to the device.
2206   //
2207   if (VD && !VD->hasLocalStorage() &&
2208       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2209     if (isInOpenMPTargetExecutionDirective()) {
2210       DSAStackTy::DSAVarData DVarTop =
2211           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2212       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2213         return VD;
2214       // If the declaration is enclosed in a 'declare target' directive,
2215       // then it should not be captured.
2216       //
2217       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2218         return nullptr;
2219       CapturedRegionScopeInfo *CSI = nullptr;
2220       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2221                llvm::reverse(FunctionScopes),
2222                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2223         if (!isa<CapturingScopeInfo>(FSI))
2224           return nullptr;
2225         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2226           if (RSI->CapRegionKind == CR_OpenMP) {
2227             CSI = RSI;
2228             break;
2229           }
2230       }
2231       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2232       SmallVector<OpenMPDirectiveKind, 4> Regions;
2233       getOpenMPCaptureRegions(Regions,
2234                               DSAStack->getDirective(CSI->OpenMPLevel));
2235       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2236         return VD;
2237     }
2238     if (isInOpenMPDeclareTargetContext()) {
2239       // Try to mark variable as declare target if it is used in capturing
2240       // regions.
2241       if (LangOpts.OpenMP <= 45 &&
2242           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2243         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2244       return nullptr;
2245     }
2246   }
2247 
2248   if (CheckScopeInfo) {
2249     bool OpenMPFound = false;
2250     for (unsigned I = StopAt + 1; I > 0; --I) {
2251       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2252       if (!isa<CapturingScopeInfo>(FSI))
2253         return nullptr;
2254       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2255         if (RSI->CapRegionKind == CR_OpenMP) {
2256           OpenMPFound = true;
2257           break;
2258         }
2259     }
2260     if (!OpenMPFound)
2261       return nullptr;
2262   }
2263 
2264   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2265       (!DSAStack->isClauseParsingMode() ||
2266        DSAStack->getParentDirective() != OMPD_unknown)) {
2267     auto &&Info = DSAStack->isLoopControlVariable(D);
2268     if (Info.first ||
2269         (VD && VD->hasLocalStorage() &&
2270          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2271         (VD && DSAStack->isForceVarCapturing()))
2272       return VD ? VD : Info.second;
2273     DSAStackTy::DSAVarData DVarTop =
2274         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2275     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2276         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2277       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2278     // Threadprivate variables must not be captured.
2279     if (isOpenMPThreadPrivate(DVarTop.CKind))
2280       return nullptr;
2281     // The variable is not private or it is the variable in the directive with
2282     // default(none) clause and not used in any clause.
2283     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2284         D,
2285         [](OpenMPClauseKind C, bool AppliedToPointee) {
2286           return isOpenMPPrivate(C) && !AppliedToPointee;
2287         },
2288         [](OpenMPDirectiveKind) { return true; },
2289         DSAStack->isClauseParsingMode());
2290     // Global shared must not be captured.
2291     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2292         ((DSAStack->getDefaultDSA() != DSA_none &&
2293           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2294          DVarTop.CKind == OMPC_shared))
2295       return nullptr;
2296     if (DVarPrivate.CKind != OMPC_unknown ||
2297         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2298                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2299       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2300   }
2301   return nullptr;
2302 }
2303 
2304 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2305                                         unsigned Level) const {
2306   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2307 }
2308 
2309 void Sema::startOpenMPLoop() {
2310   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2311   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2312     DSAStack->loopInit();
2313 }
2314 
2315 void Sema::startOpenMPCXXRangeFor() {
2316   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2317   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2318     DSAStack->resetPossibleLoopCounter();
2319     DSAStack->loopStart();
2320   }
2321 }
2322 
2323 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2324                                            unsigned CapLevel) const {
2325   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2326   if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
2327     bool IsTriviallyCopyable =
2328         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2329         !D->getType()
2330              .getNonReferenceType()
2331              .getCanonicalType()
2332              ->getAsCXXRecordDecl();
2333     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2334     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2335     getOpenMPCaptureRegions(CaptureRegions, DKind);
2336     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2337         (IsTriviallyCopyable ||
2338          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2339       if (DSAStack->hasExplicitDSA(
2340               D,
2341               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2342               Level, /*NotLastprivate=*/true))
2343         return OMPC_firstprivate;
2344       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2345       if (DVar.CKind != OMPC_shared &&
2346           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2347         DSAStack->addImplicitTaskFirstprivate(Level, D);
2348         return OMPC_firstprivate;
2349       }
2350     }
2351   }
2352   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2353     if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2354       DSAStack->resetPossibleLoopCounter(D);
2355       DSAStack->loopStart();
2356       return OMPC_private;
2357     }
2358     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2359          DSAStack->isLoopControlVariable(D).first) &&
2360         !DSAStack->hasExplicitDSA(
2361             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2362             Level) &&
2363         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2364       return OMPC_private;
2365   }
2366   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2367     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2368         DSAStack->isForceVarCapturing() &&
2369         !DSAStack->hasExplicitDSA(
2370             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2371             Level))
2372       return OMPC_private;
2373   }
2374   // User-defined allocators are private since they must be defined in the
2375   // context of target region.
2376   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2377       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2378           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2379           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2380     return OMPC_private;
2381   return (DSAStack->hasExplicitDSA(
2382               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2383               Level) ||
2384           (DSAStack->isClauseParsingMode() &&
2385            DSAStack->getClauseParsingMode() == OMPC_private) ||
2386           // Consider taskgroup reduction descriptor variable a private
2387           // to avoid possible capture in the region.
2388           (DSAStack->hasExplicitDirective(
2389                [](OpenMPDirectiveKind K) {
2390                  return K == OMPD_taskgroup ||
2391                         ((isOpenMPParallelDirective(K) ||
2392                           isOpenMPWorksharingDirective(K)) &&
2393                          !isOpenMPSimdDirective(K));
2394                },
2395                Level) &&
2396            DSAStack->isTaskgroupReductionRef(D, Level)))
2397              ? OMPC_private
2398              : OMPC_unknown;
2399 }
2400 
2401 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2402                                 unsigned Level) {
2403   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2404   D = getCanonicalDecl(D);
2405   OpenMPClauseKind OMPC = OMPC_unknown;
2406   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2407     const unsigned NewLevel = I - 1;
2408     if (DSAStack->hasExplicitDSA(
2409             D,
2410             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2411               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2412                 OMPC = K;
2413                 return true;
2414               }
2415               return false;
2416             },
2417             NewLevel))
2418       break;
2419     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2420             D, NewLevel,
2421             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2422                OpenMPClauseKind) { return true; })) {
2423       OMPC = OMPC_map;
2424       break;
2425     }
2426     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2427                                        NewLevel)) {
2428       OMPC = OMPC_map;
2429       if (DSAStack->mustBeFirstprivateAtLevel(
2430               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2431         OMPC = OMPC_firstprivate;
2432       break;
2433     }
2434   }
2435   if (OMPC != OMPC_unknown)
2436     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2437 }
2438 
2439 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2440                                       unsigned CaptureLevel) const {
2441   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2442   // Return true if the current level is no longer enclosed in a target region.
2443 
2444   SmallVector<OpenMPDirectiveKind, 4> Regions;
2445   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2446   const auto *VD = dyn_cast<VarDecl>(D);
2447   return VD && !VD->hasLocalStorage() &&
2448          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2449                                         Level) &&
2450          Regions[CaptureLevel] != OMPD_task;
2451 }
2452 
2453 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2454                                       unsigned CaptureLevel) const {
2455   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2456   // Return true if the current level is no longer enclosed in a target region.
2457 
2458   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2459     if (!VD->hasLocalStorage()) {
2460       if (isInOpenMPTargetExecutionDirective())
2461         return true;
2462       DSAStackTy::DSAVarData TopDVar =
2463           DSAStack->getTopDSA(D, /*FromParent=*/false);
2464       unsigned NumLevels =
2465           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2466       if (Level == 0)
2467         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2468       do {
2469         --Level;
2470         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2471         if (DVar.CKind != OMPC_shared)
2472           return true;
2473       } while (Level > 0);
2474     }
2475   }
2476   return true;
2477 }
2478 
2479 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2480 
2481 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2482                                           OMPTraitInfo &TI) {
2483   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2484 }
2485 
2486 void Sema::ActOnOpenMPEndDeclareVariant() {
2487   assert(isInOpenMPDeclareVariantScope() &&
2488          "Not in OpenMP declare variant scope!");
2489 
2490   OMPDeclareVariantScopes.pop_back();
2491 }
2492 
2493 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2494                                          const FunctionDecl *Callee,
2495                                          SourceLocation Loc) {
2496   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2497   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2498       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2499   // Ignore host functions during device analyzis.
2500   if (LangOpts.OpenMPIsDevice &&
2501       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2502     return;
2503   // Ignore nohost functions during host analyzis.
2504   if (!LangOpts.OpenMPIsDevice && DevTy &&
2505       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2506     return;
2507   const FunctionDecl *FD = Callee->getMostRecentDecl();
2508   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2509   if (LangOpts.OpenMPIsDevice && DevTy &&
2510       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2511     // Diagnose host function called during device codegen.
2512     StringRef HostDevTy =
2513         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2514     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2515     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2516          diag::note_omp_marked_device_type_here)
2517         << HostDevTy;
2518     return;
2519   }
2520   if (!LangOpts.OpenMPIsDevice && !LangOpts.OpenMPOffloadMandatory && DevTy &&
2521       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2522     // Diagnose nohost function called during host codegen.
2523     StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2524         OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2525     Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2526     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2527          diag::note_omp_marked_device_type_here)
2528         << NoHostDevTy;
2529   }
2530 }
2531 
2532 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2533                                const DeclarationNameInfo &DirName,
2534                                Scope *CurScope, SourceLocation Loc) {
2535   DSAStack->push(DKind, DirName, CurScope, Loc);
2536   PushExpressionEvaluationContext(
2537       ExpressionEvaluationContext::PotentiallyEvaluated);
2538 }
2539 
2540 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2541   DSAStack->setClauseParsingMode(K);
2542 }
2543 
2544 void Sema::EndOpenMPClause() {
2545   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2546   CleanupVarDeclMarking();
2547 }
2548 
2549 static std::pair<ValueDecl *, bool>
2550 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2551                SourceRange &ERange, bool AllowArraySection = false);
2552 
2553 /// Check consistency of the reduction clauses.
2554 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2555                                   ArrayRef<OMPClause *> Clauses) {
2556   bool InscanFound = false;
2557   SourceLocation InscanLoc;
2558   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2559   // A reduction clause without the inscan reduction-modifier may not appear on
2560   // a construct on which a reduction clause with the inscan reduction-modifier
2561   // appears.
2562   for (OMPClause *C : Clauses) {
2563     if (C->getClauseKind() != OMPC_reduction)
2564       continue;
2565     auto *RC = cast<OMPReductionClause>(C);
2566     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2567       InscanFound = true;
2568       InscanLoc = RC->getModifierLoc();
2569       continue;
2570     }
2571     if (RC->getModifier() == OMPC_REDUCTION_task) {
2572       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2573       // A reduction clause with the task reduction-modifier may only appear on
2574       // a parallel construct, a worksharing construct or a combined or
2575       // composite construct for which any of the aforementioned constructs is a
2576       // constituent construct and simd or loop are not constituent constructs.
2577       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2578       if (!(isOpenMPParallelDirective(CurDir) ||
2579             isOpenMPWorksharingDirective(CurDir)) ||
2580           isOpenMPSimdDirective(CurDir))
2581         S.Diag(RC->getModifierLoc(),
2582                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2583       continue;
2584     }
2585   }
2586   if (InscanFound) {
2587     for (OMPClause *C : Clauses) {
2588       if (C->getClauseKind() != OMPC_reduction)
2589         continue;
2590       auto *RC = cast<OMPReductionClause>(C);
2591       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2592         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2593                    ? RC->getBeginLoc()
2594                    : RC->getModifierLoc(),
2595                diag::err_omp_inscan_reduction_expected);
2596         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2597         continue;
2598       }
2599       for (Expr *Ref : RC->varlists()) {
2600         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2601         SourceLocation ELoc;
2602         SourceRange ERange;
2603         Expr *SimpleRefExpr = Ref;
2604         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2605                                   /*AllowArraySection=*/true);
2606         ValueDecl *D = Res.first;
2607         if (!D)
2608           continue;
2609         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2610           S.Diag(Ref->getExprLoc(),
2611                  diag::err_omp_reduction_not_inclusive_exclusive)
2612               << Ref->getSourceRange();
2613         }
2614       }
2615     }
2616   }
2617 }
2618 
2619 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2620                                  ArrayRef<OMPClause *> Clauses);
2621 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2622                                  bool WithInit);
2623 
2624 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2625                               const ValueDecl *D,
2626                               const DSAStackTy::DSAVarData &DVar,
2627                               bool IsLoopIterVar = false);
2628 
2629 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2630   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2631   //  A variable of class type (or array thereof) that appears in a lastprivate
2632   //  clause requires an accessible, unambiguous default constructor for the
2633   //  class type, unless the list item is also specified in a firstprivate
2634   //  clause.
2635   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2636     for (OMPClause *C : D->clauses()) {
2637       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2638         SmallVector<Expr *, 8> PrivateCopies;
2639         for (Expr *DE : Clause->varlists()) {
2640           if (DE->isValueDependent() || DE->isTypeDependent()) {
2641             PrivateCopies.push_back(nullptr);
2642             continue;
2643           }
2644           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2645           auto *VD = cast<VarDecl>(DRE->getDecl());
2646           QualType Type = VD->getType().getNonReferenceType();
2647           const DSAStackTy::DSAVarData DVar =
2648               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2649           if (DVar.CKind == OMPC_lastprivate) {
2650             // Generate helper private variable and initialize it with the
2651             // default value. The address of the original variable is replaced
2652             // by the address of the new private variable in CodeGen. This new
2653             // variable is not added to IdResolver, so the code in the OpenMP
2654             // region uses original variable for proper diagnostics.
2655             VarDecl *VDPrivate = buildVarDecl(
2656                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2657                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2658             ActOnUninitializedDecl(VDPrivate);
2659             if (VDPrivate->isInvalidDecl()) {
2660               PrivateCopies.push_back(nullptr);
2661               continue;
2662             }
2663             PrivateCopies.push_back(buildDeclRefExpr(
2664                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2665           } else {
2666             // The variable is also a firstprivate, so initialization sequence
2667             // for private copy is generated already.
2668             PrivateCopies.push_back(nullptr);
2669           }
2670         }
2671         Clause->setPrivateCopies(PrivateCopies);
2672         continue;
2673       }
2674       // Finalize nontemporal clause by handling private copies, if any.
2675       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2676         SmallVector<Expr *, 8> PrivateRefs;
2677         for (Expr *RefExpr : Clause->varlists()) {
2678           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2679           SourceLocation ELoc;
2680           SourceRange ERange;
2681           Expr *SimpleRefExpr = RefExpr;
2682           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2683           if (Res.second)
2684             // It will be analyzed later.
2685             PrivateRefs.push_back(RefExpr);
2686           ValueDecl *D = Res.first;
2687           if (!D)
2688             continue;
2689 
2690           const DSAStackTy::DSAVarData DVar =
2691               DSAStack->getTopDSA(D, /*FromParent=*/false);
2692           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2693                                                  : SimpleRefExpr);
2694         }
2695         Clause->setPrivateRefs(PrivateRefs);
2696         continue;
2697       }
2698       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2699         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2700           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2701           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2702           if (!DRE)
2703             continue;
2704           ValueDecl *VD = DRE->getDecl();
2705           if (!VD || !isa<VarDecl>(VD))
2706             continue;
2707           DSAStackTy::DSAVarData DVar =
2708               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2709           // OpenMP [2.12.5, target Construct]
2710           // Memory allocators that appear in a uses_allocators clause cannot
2711           // appear in other data-sharing attribute clauses or data-mapping
2712           // attribute clauses in the same construct.
2713           Expr *MapExpr = nullptr;
2714           if (DVar.RefExpr ||
2715               DSAStack->checkMappableExprComponentListsForDecl(
2716                   VD, /*CurrentRegionOnly=*/true,
2717                   [VD, &MapExpr](
2718                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2719                           MapExprComponents,
2720                       OpenMPClauseKind C) {
2721                     auto MI = MapExprComponents.rbegin();
2722                     auto ME = MapExprComponents.rend();
2723                     if (MI != ME &&
2724                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2725                             VD->getCanonicalDecl()) {
2726                       MapExpr = MI->getAssociatedExpression();
2727                       return true;
2728                     }
2729                     return false;
2730                   })) {
2731             Diag(D.Allocator->getExprLoc(),
2732                  diag::err_omp_allocator_used_in_clauses)
2733                 << D.Allocator->getSourceRange();
2734             if (DVar.RefExpr)
2735               reportOriginalDsa(*this, DSAStack, VD, DVar);
2736             else
2737               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2738                   << MapExpr->getSourceRange();
2739           }
2740         }
2741         continue;
2742       }
2743     }
2744     // Check allocate clauses.
2745     if (!CurContext->isDependentContext())
2746       checkAllocateClauses(*this, DSAStack, D->clauses());
2747     checkReductionClauses(*this, DSAStack, D->clauses());
2748   }
2749 
2750   DSAStack->pop();
2751   DiscardCleanupsInEvaluationContext();
2752   PopExpressionEvaluationContext();
2753 }
2754 
2755 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2756                                      Expr *NumIterations, Sema &SemaRef,
2757                                      Scope *S, DSAStackTy *Stack);
2758 
2759 namespace {
2760 
2761 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2762 private:
2763   Sema &SemaRef;
2764 
2765 public:
2766   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2767   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2768     NamedDecl *ND = Candidate.getCorrectionDecl();
2769     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2770       return VD->hasGlobalStorage() &&
2771              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2772                                    SemaRef.getCurScope());
2773     }
2774     return false;
2775   }
2776 
2777   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2778     return std::make_unique<VarDeclFilterCCC>(*this);
2779   }
2780 };
2781 
2782 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2783 private:
2784   Sema &SemaRef;
2785 
2786 public:
2787   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2788   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2789     NamedDecl *ND = Candidate.getCorrectionDecl();
2790     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2791                isa<FunctionDecl>(ND))) {
2792       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2793                                    SemaRef.getCurScope());
2794     }
2795     return false;
2796   }
2797 
2798   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2799     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2800   }
2801 };
2802 
2803 } // namespace
2804 
2805 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2806                                          CXXScopeSpec &ScopeSpec,
2807                                          const DeclarationNameInfo &Id,
2808                                          OpenMPDirectiveKind Kind) {
2809   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2810   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2811 
2812   if (Lookup.isAmbiguous())
2813     return ExprError();
2814 
2815   VarDecl *VD;
2816   if (!Lookup.isSingleResult()) {
2817     VarDeclFilterCCC CCC(*this);
2818     if (TypoCorrection Corrected =
2819             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2820                         CTK_ErrorRecovery)) {
2821       diagnoseTypo(Corrected,
2822                    PDiag(Lookup.empty()
2823                              ? diag::err_undeclared_var_use_suggest
2824                              : diag::err_omp_expected_var_arg_suggest)
2825                        << Id.getName());
2826       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2827     } else {
2828       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2829                                        : diag::err_omp_expected_var_arg)
2830           << Id.getName();
2831       return ExprError();
2832     }
2833   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2834     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2835     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2836     return ExprError();
2837   }
2838   Lookup.suppressDiagnostics();
2839 
2840   // OpenMP [2.9.2, Syntax, C/C++]
2841   //   Variables must be file-scope, namespace-scope, or static block-scope.
2842   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2843     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2844         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2845     bool IsDecl =
2846         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2847     Diag(VD->getLocation(),
2848          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2849         << VD;
2850     return ExprError();
2851   }
2852 
2853   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2854   NamedDecl *ND = CanonicalVD;
2855   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2856   //   A threadprivate directive for file-scope variables must appear outside
2857   //   any definition or declaration.
2858   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2859       !getCurLexicalContext()->isTranslationUnit()) {
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.3]
2870   //   A threadprivate directive for static class member variables must appear
2871   //   in the class definition, in the same scope in which the member
2872   //   variables are declared.
2873   if (CanonicalVD->isStaticDataMember() &&
2874       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2875     Diag(Id.getLoc(), diag::err_omp_var_scope)
2876         << getOpenMPDirectiveName(Kind) << VD;
2877     bool IsDecl =
2878         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2879     Diag(VD->getLocation(),
2880          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2881         << VD;
2882     return ExprError();
2883   }
2884   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2885   //   A threadprivate directive for namespace-scope variables must appear
2886   //   outside any definition or declaration other than the namespace
2887   //   definition itself.
2888   if (CanonicalVD->getDeclContext()->isNamespace() &&
2889       (!getCurLexicalContext()->isFileContext() ||
2890        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2891     Diag(Id.getLoc(), diag::err_omp_var_scope)
2892         << getOpenMPDirectiveName(Kind) << VD;
2893     bool IsDecl =
2894         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2895     Diag(VD->getLocation(),
2896          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2897         << VD;
2898     return ExprError();
2899   }
2900   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2901   //   A threadprivate directive for static block-scope variables must appear
2902   //   in the scope of the variable and not in a nested scope.
2903   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2904       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2905     Diag(Id.getLoc(), diag::err_omp_var_scope)
2906         << getOpenMPDirectiveName(Kind) << VD;
2907     bool IsDecl =
2908         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2909     Diag(VD->getLocation(),
2910          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2911         << VD;
2912     return ExprError();
2913   }
2914 
2915   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2916   //   A threadprivate directive must lexically precede all references to any
2917   //   of the variables in its list.
2918   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2919       !DSAStack->isThreadPrivate(VD)) {
2920     Diag(Id.getLoc(), diag::err_omp_var_used)
2921         << getOpenMPDirectiveName(Kind) << VD;
2922     return ExprError();
2923   }
2924 
2925   QualType ExprType = VD->getType().getNonReferenceType();
2926   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2927                              SourceLocation(), VD,
2928                              /*RefersToEnclosingVariableOrCapture=*/false,
2929                              Id.getLoc(), ExprType, VK_LValue);
2930 }
2931 
2932 Sema::DeclGroupPtrTy
2933 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2934                                         ArrayRef<Expr *> VarList) {
2935   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2936     CurContext->addDecl(D);
2937     return DeclGroupPtrTy::make(DeclGroupRef(D));
2938   }
2939   return nullptr;
2940 }
2941 
2942 namespace {
2943 class LocalVarRefChecker final
2944     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2945   Sema &SemaRef;
2946 
2947 public:
2948   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2949     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2950       if (VD->hasLocalStorage()) {
2951         SemaRef.Diag(E->getBeginLoc(),
2952                      diag::err_omp_local_var_in_threadprivate_init)
2953             << E->getSourceRange();
2954         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2955             << VD << VD->getSourceRange();
2956         return true;
2957       }
2958     }
2959     return false;
2960   }
2961   bool VisitStmt(const Stmt *S) {
2962     for (const Stmt *Child : S->children()) {
2963       if (Child && Visit(Child))
2964         return true;
2965     }
2966     return false;
2967   }
2968   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2969 };
2970 } // namespace
2971 
2972 OMPThreadPrivateDecl *
2973 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2974   SmallVector<Expr *, 8> Vars;
2975   for (Expr *RefExpr : VarList) {
2976     auto *DE = cast<DeclRefExpr>(RefExpr);
2977     auto *VD = cast<VarDecl>(DE->getDecl());
2978     SourceLocation ILoc = DE->getExprLoc();
2979 
2980     // Mark variable as used.
2981     VD->setReferenced();
2982     VD->markUsed(Context);
2983 
2984     QualType QType = VD->getType();
2985     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2986       // It will be analyzed later.
2987       Vars.push_back(DE);
2988       continue;
2989     }
2990 
2991     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2992     //   A threadprivate variable must not have an incomplete type.
2993     if (RequireCompleteType(ILoc, VD->getType(),
2994                             diag::err_omp_threadprivate_incomplete_type)) {
2995       continue;
2996     }
2997 
2998     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2999     //   A threadprivate variable must not have a reference type.
3000     if (VD->getType()->isReferenceType()) {
3001       Diag(ILoc, diag::err_omp_ref_type_arg)
3002           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
3003       bool IsDecl =
3004           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3005       Diag(VD->getLocation(),
3006            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3007           << VD;
3008       continue;
3009     }
3010 
3011     // Check if this is a TLS variable. If TLS is not being supported, produce
3012     // the corresponding diagnostic.
3013     if ((VD->getTLSKind() != VarDecl::TLS_None &&
3014          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
3015            getLangOpts().OpenMPUseTLS &&
3016            getASTContext().getTargetInfo().isTLSSupported())) ||
3017         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3018          !VD->isLocalVarDecl())) {
3019       Diag(ILoc, diag::err_omp_var_thread_local)
3020           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3021       bool IsDecl =
3022           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3023       Diag(VD->getLocation(),
3024            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3025           << VD;
3026       continue;
3027     }
3028 
3029     // Check if initial value of threadprivate variable reference variable with
3030     // local storage (it is not supported by runtime).
3031     if (const Expr *Init = VD->getAnyInitializer()) {
3032       LocalVarRefChecker Checker(*this);
3033       if (Checker.Visit(Init))
3034         continue;
3035     }
3036 
3037     Vars.push_back(RefExpr);
3038     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3039     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3040         Context, SourceRange(Loc, Loc)));
3041     if (ASTMutationListener *ML = Context.getASTMutationListener())
3042       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3043   }
3044   OMPThreadPrivateDecl *D = nullptr;
3045   if (!Vars.empty()) {
3046     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3047                                      Vars);
3048     D->setAccess(AS_public);
3049   }
3050   return D;
3051 }
3052 
3053 static OMPAllocateDeclAttr::AllocatorTypeTy
3054 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3055   if (!Allocator)
3056     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3057   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3058       Allocator->isInstantiationDependent() ||
3059       Allocator->containsUnexpandedParameterPack())
3060     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3061   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3062   const Expr *AE = Allocator->IgnoreParenImpCasts();
3063   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3064     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3065     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3066     llvm::FoldingSetNodeID AEId, DAEId;
3067     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3068     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3069     if (AEId == DAEId) {
3070       AllocatorKindRes = AllocatorKind;
3071       break;
3072     }
3073   }
3074   return AllocatorKindRes;
3075 }
3076 
3077 static bool checkPreviousOMPAllocateAttribute(
3078     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3079     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3080   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3081     return false;
3082   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3083   Expr *PrevAllocator = A->getAllocator();
3084   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3085       getAllocatorKind(S, Stack, PrevAllocator);
3086   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3087   if (AllocatorsMatch &&
3088       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3089       Allocator && PrevAllocator) {
3090     const Expr *AE = Allocator->IgnoreParenImpCasts();
3091     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3092     llvm::FoldingSetNodeID AEId, PAEId;
3093     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3094     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3095     AllocatorsMatch = AEId == PAEId;
3096   }
3097   if (!AllocatorsMatch) {
3098     SmallString<256> AllocatorBuffer;
3099     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3100     if (Allocator)
3101       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3102     SmallString<256> PrevAllocatorBuffer;
3103     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3104     if (PrevAllocator)
3105       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3106                                  S.getPrintingPolicy());
3107 
3108     SourceLocation AllocatorLoc =
3109         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3110     SourceRange AllocatorRange =
3111         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3112     SourceLocation PrevAllocatorLoc =
3113         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3114     SourceRange PrevAllocatorRange =
3115         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3116     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3117         << (Allocator ? 1 : 0) << AllocatorStream.str()
3118         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3119         << AllocatorRange;
3120     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3121         << PrevAllocatorRange;
3122     return true;
3123   }
3124   return false;
3125 }
3126 
3127 static void
3128 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3129                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3130                           Expr *Allocator, Expr *Alignment, SourceRange SR) {
3131   if (VD->hasAttr<OMPAllocateDeclAttr>())
3132     return;
3133   if (Alignment &&
3134       (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3135        Alignment->isInstantiationDependent() ||
3136        Alignment->containsUnexpandedParameterPack()))
3137     // Apply later when we have a usable value.
3138     return;
3139   if (Allocator &&
3140       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3141        Allocator->isInstantiationDependent() ||
3142        Allocator->containsUnexpandedParameterPack()))
3143     return;
3144   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3145                                                 Allocator, Alignment, SR);
3146   VD->addAttr(A);
3147   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3148     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3149 }
3150 
3151 Sema::DeclGroupPtrTy
3152 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
3153                                    ArrayRef<OMPClause *> Clauses,
3154                                    DeclContext *Owner) {
3155   assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3156   Expr *Alignment = nullptr;
3157   Expr *Allocator = nullptr;
3158   if (Clauses.empty()) {
3159     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3160     // allocate directives that appear in a target region must specify an
3161     // allocator clause unless a requires directive with the dynamic_allocators
3162     // clause is present in the same compilation unit.
3163     if (LangOpts.OpenMPIsDevice &&
3164         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3165       targetDiag(Loc, diag::err_expected_allocator_clause);
3166   } else {
3167     for (const OMPClause *C : Clauses)
3168       if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3169         Allocator = AC->getAllocator();
3170       else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3171         Alignment = AC->getAlignment();
3172       else
3173         llvm_unreachable("Unexpected clause on allocate directive");
3174   }
3175   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3176       getAllocatorKind(*this, DSAStack, Allocator);
3177   SmallVector<Expr *, 8> Vars;
3178   for (Expr *RefExpr : VarList) {
3179     auto *DE = cast<DeclRefExpr>(RefExpr);
3180     auto *VD = cast<VarDecl>(DE->getDecl());
3181 
3182     // Check if this is a TLS variable or global register.
3183     if (VD->getTLSKind() != VarDecl::TLS_None ||
3184         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3185         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3186          !VD->isLocalVarDecl()))
3187       continue;
3188 
3189     // If the used several times in the allocate directive, the same allocator
3190     // must be used.
3191     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3192                                           AllocatorKind, Allocator))
3193       continue;
3194 
3195     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3196     // If a list item has a static storage type, the allocator expression in the
3197     // allocator clause must be a constant expression that evaluates to one of
3198     // the predefined memory allocator values.
3199     if (Allocator && VD->hasGlobalStorage()) {
3200       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3201         Diag(Allocator->getExprLoc(),
3202              diag::err_omp_expected_predefined_allocator)
3203             << Allocator->getSourceRange();
3204         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3205                       VarDecl::DeclarationOnly;
3206         Diag(VD->getLocation(),
3207              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3208             << VD;
3209         continue;
3210       }
3211     }
3212 
3213     Vars.push_back(RefExpr);
3214     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
3215                               DE->getSourceRange());
3216   }
3217   if (Vars.empty())
3218     return nullptr;
3219   if (!Owner)
3220     Owner = getCurLexicalContext();
3221   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3222   D->setAccess(AS_public);
3223   Owner->addDecl(D);
3224   return DeclGroupPtrTy::make(DeclGroupRef(D));
3225 }
3226 
3227 Sema::DeclGroupPtrTy
3228 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3229                                    ArrayRef<OMPClause *> ClauseList) {
3230   OMPRequiresDecl *D = nullptr;
3231   if (!CurContext->isFileContext()) {
3232     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3233   } else {
3234     D = CheckOMPRequiresDecl(Loc, ClauseList);
3235     if (D) {
3236       CurContext->addDecl(D);
3237       DSAStack->addRequiresDecl(D);
3238     }
3239   }
3240   return DeclGroupPtrTy::make(DeclGroupRef(D));
3241 }
3242 
3243 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3244                                        OpenMPDirectiveKind DKind,
3245                                        ArrayRef<std::string> Assumptions,
3246                                        bool SkippedClauses) {
3247   if (!SkippedClauses && Assumptions.empty())
3248     Diag(Loc, diag::err_omp_no_clause_for_directive)
3249         << llvm::omp::getAllAssumeClauseOptions()
3250         << llvm::omp::getOpenMPDirectiveName(DKind);
3251 
3252   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3253   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3254     OMPAssumeScoped.push_back(AA);
3255     return;
3256   }
3257 
3258   // Global assumes without assumption clauses are ignored.
3259   if (Assumptions.empty())
3260     return;
3261 
3262   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3263          "Unexpected omp assumption directive!");
3264   OMPAssumeGlobal.push_back(AA);
3265 
3266   // The OMPAssumeGlobal scope above will take care of new declarations but
3267   // we also want to apply the assumption to existing ones, e.g., to
3268   // declarations in included headers. To this end, we traverse all existing
3269   // declaration contexts and annotate function declarations here.
3270   SmallVector<DeclContext *, 8> DeclContexts;
3271   auto *Ctx = CurContext;
3272   while (Ctx->getLexicalParent())
3273     Ctx = Ctx->getLexicalParent();
3274   DeclContexts.push_back(Ctx);
3275   while (!DeclContexts.empty()) {
3276     DeclContext *DC = DeclContexts.pop_back_val();
3277     for (auto *SubDC : DC->decls()) {
3278       if (SubDC->isInvalidDecl())
3279         continue;
3280       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3281         DeclContexts.push_back(CTD->getTemplatedDecl());
3282         llvm::append_range(DeclContexts, CTD->specializations());
3283         continue;
3284       }
3285       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3286         DeclContexts.push_back(DC);
3287       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3288         F->addAttr(AA);
3289         continue;
3290       }
3291     }
3292   }
3293 }
3294 
3295 void Sema::ActOnOpenMPEndAssumesDirective() {
3296   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3297   OMPAssumeScoped.pop_back();
3298 }
3299 
3300 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3301                                             ArrayRef<OMPClause *> ClauseList) {
3302   /// For target specific clauses, the requires directive cannot be
3303   /// specified after the handling of any of the target regions in the
3304   /// current compilation unit.
3305   ArrayRef<SourceLocation> TargetLocations =
3306       DSAStack->getEncounteredTargetLocs();
3307   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3308   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3309     for (const OMPClause *CNew : ClauseList) {
3310       // Check if any of the requires clauses affect target regions.
3311       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3312           isa<OMPUnifiedAddressClause>(CNew) ||
3313           isa<OMPReverseOffloadClause>(CNew) ||
3314           isa<OMPDynamicAllocatorsClause>(CNew)) {
3315         Diag(Loc, diag::err_omp_directive_before_requires)
3316             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3317         for (SourceLocation TargetLoc : TargetLocations) {
3318           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3319               << "target";
3320         }
3321       } else if (!AtomicLoc.isInvalid() &&
3322                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3323         Diag(Loc, diag::err_omp_directive_before_requires)
3324             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3325         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3326             << "atomic";
3327       }
3328     }
3329   }
3330 
3331   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3332     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3333                                    ClauseList);
3334   return nullptr;
3335 }
3336 
3337 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3338                               const ValueDecl *D,
3339                               const DSAStackTy::DSAVarData &DVar,
3340                               bool IsLoopIterVar) {
3341   if (DVar.RefExpr) {
3342     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3343         << getOpenMPClauseName(DVar.CKind);
3344     return;
3345   }
3346   enum {
3347     PDSA_StaticMemberShared,
3348     PDSA_StaticLocalVarShared,
3349     PDSA_LoopIterVarPrivate,
3350     PDSA_LoopIterVarLinear,
3351     PDSA_LoopIterVarLastprivate,
3352     PDSA_ConstVarShared,
3353     PDSA_GlobalVarShared,
3354     PDSA_TaskVarFirstprivate,
3355     PDSA_LocalVarPrivate,
3356     PDSA_Implicit
3357   } Reason = PDSA_Implicit;
3358   bool ReportHint = false;
3359   auto ReportLoc = D->getLocation();
3360   auto *VD = dyn_cast<VarDecl>(D);
3361   if (IsLoopIterVar) {
3362     if (DVar.CKind == OMPC_private)
3363       Reason = PDSA_LoopIterVarPrivate;
3364     else if (DVar.CKind == OMPC_lastprivate)
3365       Reason = PDSA_LoopIterVarLastprivate;
3366     else
3367       Reason = PDSA_LoopIterVarLinear;
3368   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3369              DVar.CKind == OMPC_firstprivate) {
3370     Reason = PDSA_TaskVarFirstprivate;
3371     ReportLoc = DVar.ImplicitDSALoc;
3372   } else if (VD && VD->isStaticLocal())
3373     Reason = PDSA_StaticLocalVarShared;
3374   else if (VD && VD->isStaticDataMember())
3375     Reason = PDSA_StaticMemberShared;
3376   else if (VD && VD->isFileVarDecl())
3377     Reason = PDSA_GlobalVarShared;
3378   else if (D->getType().isConstant(SemaRef.getASTContext()))
3379     Reason = PDSA_ConstVarShared;
3380   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3381     ReportHint = true;
3382     Reason = PDSA_LocalVarPrivate;
3383   }
3384   if (Reason != PDSA_Implicit) {
3385     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3386         << Reason << ReportHint
3387         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3388   } else if (DVar.ImplicitDSALoc.isValid()) {
3389     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3390         << getOpenMPClauseName(DVar.CKind);
3391   }
3392 }
3393 
3394 static OpenMPMapClauseKind
3395 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3396                              bool IsAggregateOrDeclareTarget) {
3397   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3398   switch (M) {
3399   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3400     Kind = OMPC_MAP_alloc;
3401     break;
3402   case OMPC_DEFAULTMAP_MODIFIER_to:
3403     Kind = OMPC_MAP_to;
3404     break;
3405   case OMPC_DEFAULTMAP_MODIFIER_from:
3406     Kind = OMPC_MAP_from;
3407     break;
3408   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3409     Kind = OMPC_MAP_tofrom;
3410     break;
3411   case OMPC_DEFAULTMAP_MODIFIER_present:
3412     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3413     // If implicit-behavior is present, each variable referenced in the
3414     // construct in the category specified by variable-category is treated as if
3415     // it had been listed in a map clause with the map-type of alloc and
3416     // map-type-modifier of present.
3417     Kind = OMPC_MAP_alloc;
3418     break;
3419   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3420   case OMPC_DEFAULTMAP_MODIFIER_last:
3421     llvm_unreachable("Unexpected defaultmap implicit behavior");
3422   case OMPC_DEFAULTMAP_MODIFIER_none:
3423   case OMPC_DEFAULTMAP_MODIFIER_default:
3424   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3425     // IsAggregateOrDeclareTarget could be true if:
3426     // 1. the implicit behavior for aggregate is tofrom
3427     // 2. it's a declare target link
3428     if (IsAggregateOrDeclareTarget) {
3429       Kind = OMPC_MAP_tofrom;
3430       break;
3431     }
3432     llvm_unreachable("Unexpected defaultmap implicit behavior");
3433   }
3434   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3435   return Kind;
3436 }
3437 
3438 namespace {
3439 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3440   DSAStackTy *Stack;
3441   Sema &SemaRef;
3442   bool ErrorFound = false;
3443   bool TryCaptureCXXThisMembers = false;
3444   CapturedStmt *CS = nullptr;
3445   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3446   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3447   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3448   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3449       ImplicitMapModifier[DefaultmapKindNum];
3450   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3451   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3452 
3453   void VisitSubCaptures(OMPExecutableDirective *S) {
3454     // Check implicitly captured variables.
3455     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3456       return;
3457     if (S->getDirectiveKind() == OMPD_atomic ||
3458         S->getDirectiveKind() == OMPD_critical ||
3459         S->getDirectiveKind() == OMPD_section ||
3460         S->getDirectiveKind() == OMPD_master ||
3461         S->getDirectiveKind() == OMPD_masked ||
3462         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3463       Visit(S->getAssociatedStmt());
3464       return;
3465     }
3466     visitSubCaptures(S->getInnermostCapturedStmt());
3467     // Try to capture inner this->member references to generate correct mappings
3468     // and diagnostics.
3469     if (TryCaptureCXXThisMembers ||
3470         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3471          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3472                       [](const CapturedStmt::Capture &C) {
3473                         return C.capturesThis();
3474                       }))) {
3475       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3476       TryCaptureCXXThisMembers = true;
3477       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3478       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3479     }
3480     // In tasks firstprivates are not captured anymore, need to analyze them
3481     // explicitly.
3482     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3483         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3484       for (OMPClause *C : S->clauses())
3485         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3486           for (Expr *Ref : FC->varlists())
3487             Visit(Ref);
3488         }
3489     }
3490   }
3491 
3492 public:
3493   void VisitDeclRefExpr(DeclRefExpr *E) {
3494     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3495         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3496         E->isInstantiationDependent())
3497       return;
3498     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3499       // Check the datasharing rules for the expressions in the clauses.
3500       if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
3501                   !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
3502         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3503           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3504             Visit(CED->getInit());
3505             return;
3506           }
3507       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3508         // Do not analyze internal variables and do not enclose them into
3509         // implicit clauses.
3510         return;
3511       VD = VD->getCanonicalDecl();
3512       // Skip internally declared variables.
3513       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3514           !Stack->isImplicitTaskFirstprivate(VD))
3515         return;
3516       // Skip allocators in uses_allocators clauses.
3517       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3518         return;
3519 
3520       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3521       // Check if the variable has explicit DSA set and stop analysis if it so.
3522       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3523         return;
3524 
3525       // Skip internally declared static variables.
3526       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3527           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3528       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3529           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3530            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3531           !Stack->isImplicitTaskFirstprivate(VD))
3532         return;
3533 
3534       SourceLocation ELoc = E->getExprLoc();
3535       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3536       // The default(none) clause requires that each variable that is referenced
3537       // in the construct, and does not have a predetermined data-sharing
3538       // attribute, must have its data-sharing attribute explicitly determined
3539       // by being listed in a data-sharing attribute clause.
3540       if (DVar.CKind == OMPC_unknown &&
3541           (Stack->getDefaultDSA() == DSA_none ||
3542            Stack->getDefaultDSA() == DSA_firstprivate) &&
3543           isImplicitOrExplicitTaskingRegion(DKind) &&
3544           VarsWithInheritedDSA.count(VD) == 0) {
3545         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3546         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3547           DSAStackTy::DSAVarData DVar =
3548               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3549           InheritedDSA = DVar.CKind == OMPC_unknown;
3550         }
3551         if (InheritedDSA)
3552           VarsWithInheritedDSA[VD] = E;
3553         return;
3554       }
3555 
3556       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3557       // If implicit-behavior is none, each variable referenced in the
3558       // construct that does not have a predetermined data-sharing attribute
3559       // and does not appear in a to or link clause on a declare target
3560       // directive must be listed in a data-mapping attribute clause, a
3561       // data-haring attribute clause (including a data-sharing attribute
3562       // clause on a combined construct where target. is one of the
3563       // constituent constructs), or an is_device_ptr clause.
3564       OpenMPDefaultmapClauseKind ClauseKind =
3565           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3566       if (SemaRef.getLangOpts().OpenMP >= 50) {
3567         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3568                               OMPC_DEFAULTMAP_MODIFIER_none;
3569         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3570             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3571           // Only check for data-mapping attribute and is_device_ptr here
3572           // since we have already make sure that the declaration does not
3573           // have a data-sharing attribute above
3574           if (!Stack->checkMappableExprComponentListsForDecl(
3575                   VD, /*CurrentRegionOnly=*/true,
3576                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3577                            MapExprComponents,
3578                        OpenMPClauseKind) {
3579                     auto MI = MapExprComponents.rbegin();
3580                     auto ME = MapExprComponents.rend();
3581                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3582                   })) {
3583             VarsWithInheritedDSA[VD] = E;
3584             return;
3585           }
3586         }
3587       }
3588       if (SemaRef.getLangOpts().OpenMP > 50) {
3589         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3590                                  OMPC_DEFAULTMAP_MODIFIER_present;
3591         if (IsModifierPresent) {
3592           if (llvm::find(ImplicitMapModifier[ClauseKind],
3593                          OMPC_MAP_MODIFIER_present) ==
3594               std::end(ImplicitMapModifier[ClauseKind])) {
3595             ImplicitMapModifier[ClauseKind].push_back(
3596                 OMPC_MAP_MODIFIER_present);
3597           }
3598         }
3599       }
3600 
3601       if (isOpenMPTargetExecutionDirective(DKind) &&
3602           !Stack->isLoopControlVariable(VD).first) {
3603         if (!Stack->checkMappableExprComponentListsForDecl(
3604                 VD, /*CurrentRegionOnly=*/true,
3605                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3606                            StackComponents,
3607                        OpenMPClauseKind) {
3608                   if (SemaRef.LangOpts.OpenMP >= 50)
3609                     return !StackComponents.empty();
3610                   // Variable is used if it has been marked as an array, array
3611                   // section, array shaping or the variable iself.
3612                   return StackComponents.size() == 1 ||
3613                          std::all_of(
3614                              std::next(StackComponents.rbegin()),
3615                              StackComponents.rend(),
3616                              [](const OMPClauseMappableExprCommon::
3617                                     MappableComponent &MC) {
3618                                return MC.getAssociatedDeclaration() ==
3619                                           nullptr &&
3620                                       (isa<OMPArraySectionExpr>(
3621                                            MC.getAssociatedExpression()) ||
3622                                        isa<OMPArrayShapingExpr>(
3623                                            MC.getAssociatedExpression()) ||
3624                                        isa<ArraySubscriptExpr>(
3625                                            MC.getAssociatedExpression()));
3626                              });
3627                 })) {
3628           bool IsFirstprivate = false;
3629           // By default lambdas are captured as firstprivates.
3630           if (const auto *RD =
3631                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3632             IsFirstprivate = RD->isLambda();
3633           IsFirstprivate =
3634               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3635           if (IsFirstprivate) {
3636             ImplicitFirstprivate.emplace_back(E);
3637           } else {
3638             OpenMPDefaultmapClauseModifier M =
3639                 Stack->getDefaultmapModifier(ClauseKind);
3640             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3641                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3642             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3643           }
3644           return;
3645         }
3646       }
3647 
3648       // OpenMP [2.9.3.6, Restrictions, p.2]
3649       //  A list item that appears in a reduction clause of the innermost
3650       //  enclosing worksharing or parallel construct may not be accessed in an
3651       //  explicit task.
3652       DVar = Stack->hasInnermostDSA(
3653           VD,
3654           [](OpenMPClauseKind C, bool AppliedToPointee) {
3655             return C == OMPC_reduction && !AppliedToPointee;
3656           },
3657           [](OpenMPDirectiveKind K) {
3658             return isOpenMPParallelDirective(K) ||
3659                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3660           },
3661           /*FromParent=*/true);
3662       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3663         ErrorFound = true;
3664         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3665         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3666         return;
3667       }
3668 
3669       // Define implicit data-sharing attributes for task.
3670       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3671       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3672            (Stack->getDefaultDSA() == DSA_firstprivate &&
3673             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3674           !Stack->isLoopControlVariable(VD).first) {
3675         ImplicitFirstprivate.push_back(E);
3676         return;
3677       }
3678 
3679       // Store implicitly used globals with declare target link for parent
3680       // target.
3681       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3682           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3683         Stack->addToParentTargetRegionLinkGlobals(E);
3684         return;
3685       }
3686     }
3687   }
3688   void VisitMemberExpr(MemberExpr *E) {
3689     if (E->isTypeDependent() || E->isValueDependent() ||
3690         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3691       return;
3692     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3693     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3694     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3695       if (!FD)
3696         return;
3697       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3698       // Check if the variable has explicit DSA set and stop analysis if it
3699       // so.
3700       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3701         return;
3702 
3703       if (isOpenMPTargetExecutionDirective(DKind) &&
3704           !Stack->isLoopControlVariable(FD).first &&
3705           !Stack->checkMappableExprComponentListsForDecl(
3706               FD, /*CurrentRegionOnly=*/true,
3707               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3708                      StackComponents,
3709                  OpenMPClauseKind) {
3710                 return isa<CXXThisExpr>(
3711                     cast<MemberExpr>(
3712                         StackComponents.back().getAssociatedExpression())
3713                         ->getBase()
3714                         ->IgnoreParens());
3715               })) {
3716         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3717         //  A bit-field cannot appear in a map clause.
3718         //
3719         if (FD->isBitField())
3720           return;
3721 
3722         // Check to see if the member expression is referencing a class that
3723         // has already been explicitly mapped
3724         if (Stack->isClassPreviouslyMapped(TE->getType()))
3725           return;
3726 
3727         OpenMPDefaultmapClauseModifier Modifier =
3728             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3729         OpenMPDefaultmapClauseKind ClauseKind =
3730             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3731         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3732             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3733         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3734         return;
3735       }
3736 
3737       SourceLocation ELoc = E->getExprLoc();
3738       // OpenMP [2.9.3.6, Restrictions, p.2]
3739       //  A list item that appears in a reduction clause of the innermost
3740       //  enclosing worksharing or parallel construct may not be accessed in
3741       //  an  explicit task.
3742       DVar = Stack->hasInnermostDSA(
3743           FD,
3744           [](OpenMPClauseKind C, bool AppliedToPointee) {
3745             return C == OMPC_reduction && !AppliedToPointee;
3746           },
3747           [](OpenMPDirectiveKind K) {
3748             return isOpenMPParallelDirective(K) ||
3749                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3750           },
3751           /*FromParent=*/true);
3752       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3753         ErrorFound = true;
3754         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3755         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3756         return;
3757       }
3758 
3759       // Define implicit data-sharing attributes for task.
3760       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3761       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3762           !Stack->isLoopControlVariable(FD).first) {
3763         // Check if there is a captured expression for the current field in the
3764         // region. Do not mark it as firstprivate unless there is no captured
3765         // expression.
3766         // TODO: try to make it firstprivate.
3767         if (DVar.CKind != OMPC_unknown)
3768           ImplicitFirstprivate.push_back(E);
3769       }
3770       return;
3771     }
3772     if (isOpenMPTargetExecutionDirective(DKind)) {
3773       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3774       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3775                                         Stack->getCurrentDirective(),
3776                                         /*NoDiagnose=*/true))
3777         return;
3778       const auto *VD = cast<ValueDecl>(
3779           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3780       if (!Stack->checkMappableExprComponentListsForDecl(
3781               VD, /*CurrentRegionOnly=*/true,
3782               [&CurComponents](
3783                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3784                       StackComponents,
3785                   OpenMPClauseKind) {
3786                 auto CCI = CurComponents.rbegin();
3787                 auto CCE = CurComponents.rend();
3788                 for (const auto &SC : llvm::reverse(StackComponents)) {
3789                   // Do both expressions have the same kind?
3790                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3791                       SC.getAssociatedExpression()->getStmtClass())
3792                     if (!((isa<OMPArraySectionExpr>(
3793                                SC.getAssociatedExpression()) ||
3794                            isa<OMPArrayShapingExpr>(
3795                                SC.getAssociatedExpression())) &&
3796                           isa<ArraySubscriptExpr>(
3797                               CCI->getAssociatedExpression())))
3798                       return false;
3799 
3800                   const Decl *CCD = CCI->getAssociatedDeclaration();
3801                   const Decl *SCD = SC.getAssociatedDeclaration();
3802                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3803                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3804                   if (SCD != CCD)
3805                     return false;
3806                   std::advance(CCI, 1);
3807                   if (CCI == CCE)
3808                     break;
3809                 }
3810                 return true;
3811               })) {
3812         Visit(E->getBase());
3813       }
3814     } else if (!TryCaptureCXXThisMembers) {
3815       Visit(E->getBase());
3816     }
3817   }
3818   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3819     for (OMPClause *C : S->clauses()) {
3820       // Skip analysis of arguments of private clauses for task|target
3821       // directives.
3822       if (isa_and_nonnull<OMPPrivateClause>(C))
3823         continue;
3824       // Skip analysis of arguments of implicitly defined firstprivate clause
3825       // for task|target directives.
3826       // Skip analysis of arguments of implicitly defined map clause for target
3827       // directives.
3828       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3829                  C->isImplicit() &&
3830                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3831         for (Stmt *CC : C->children()) {
3832           if (CC)
3833             Visit(CC);
3834         }
3835       }
3836     }
3837     // Check implicitly captured variables.
3838     VisitSubCaptures(S);
3839   }
3840 
3841   void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
3842     // Loop transformation directives do not introduce data sharing
3843     VisitStmt(S);
3844   }
3845 
3846   void VisitCallExpr(CallExpr *S) {
3847     for (Stmt *C : S->arguments()) {
3848       if (C) {
3849         // Check implicitly captured variables in the task-based directives to
3850         // check if they must be firstprivatized.
3851         Visit(C);
3852       }
3853     }
3854     if (Expr *Callee = S->getCallee())
3855       if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts()))
3856         Visit(CE->getBase());
3857   }
3858   void VisitStmt(Stmt *S) {
3859     for (Stmt *C : S->children()) {
3860       if (C) {
3861         // Check implicitly captured variables in the task-based directives to
3862         // check if they must be firstprivatized.
3863         Visit(C);
3864       }
3865     }
3866   }
3867 
3868   void visitSubCaptures(CapturedStmt *S) {
3869     for (const CapturedStmt::Capture &Cap : S->captures()) {
3870       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3871         continue;
3872       VarDecl *VD = Cap.getCapturedVar();
3873       // Do not try to map the variable if it or its sub-component was mapped
3874       // already.
3875       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3876           Stack->checkMappableExprComponentListsForDecl(
3877               VD, /*CurrentRegionOnly=*/true,
3878               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3879                  OpenMPClauseKind) { return true; }))
3880         continue;
3881       DeclRefExpr *DRE = buildDeclRefExpr(
3882           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3883           Cap.getLocation(), /*RefersToCapture=*/true);
3884       Visit(DRE);
3885     }
3886   }
3887   bool isErrorFound() const { return ErrorFound; }
3888   ArrayRef<Expr *> getImplicitFirstprivate() const {
3889     return ImplicitFirstprivate;
3890   }
3891   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3892                                   OpenMPMapClauseKind MK) const {
3893     return ImplicitMap[DK][MK];
3894   }
3895   ArrayRef<OpenMPMapModifierKind>
3896   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3897     return ImplicitMapModifier[Kind];
3898   }
3899   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3900     return VarsWithInheritedDSA;
3901   }
3902 
3903   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3904       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3905     // Process declare target link variables for the target directives.
3906     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3907       for (DeclRefExpr *E : Stack->getLinkGlobals())
3908         Visit(E);
3909     }
3910   }
3911 };
3912 } // namespace
3913 
3914 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
3915                                                OpenMPDirectiveKind DKind,
3916                                                bool ScopeEntry) {
3917   SmallVector<llvm::omp::TraitProperty, 8> Traits;
3918   if (isOpenMPTargetExecutionDirective(DKind))
3919     Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
3920   if (isOpenMPTeamsDirective(DKind))
3921     Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
3922   if (isOpenMPParallelDirective(DKind))
3923     Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
3924   if (isOpenMPWorksharingDirective(DKind))
3925     Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
3926   if (isOpenMPSimdDirective(DKind))
3927     Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
3928   Stack->handleConstructTrait(Traits, ScopeEntry);
3929 }
3930 
3931 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3932   switch (DKind) {
3933   case OMPD_parallel:
3934   case OMPD_parallel_for:
3935   case OMPD_parallel_for_simd:
3936   case OMPD_parallel_sections:
3937   case OMPD_parallel_master:
3938   case OMPD_parallel_loop:
3939   case OMPD_teams:
3940   case OMPD_teams_distribute:
3941   case OMPD_teams_distribute_simd: {
3942     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3943     QualType KmpInt32PtrTy =
3944         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3945     Sema::CapturedParamNameType Params[] = {
3946         std::make_pair(".global_tid.", KmpInt32PtrTy),
3947         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3948         std::make_pair(StringRef(), QualType()) // __context with shared vars
3949     };
3950     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3951                              Params);
3952     break;
3953   }
3954   case OMPD_target_teams:
3955   case OMPD_target_parallel:
3956   case OMPD_target_parallel_for:
3957   case OMPD_target_parallel_for_simd:
3958   case OMPD_target_teams_loop:
3959   case OMPD_target_parallel_loop:
3960   case OMPD_target_teams_distribute:
3961   case OMPD_target_teams_distribute_simd: {
3962     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3963     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3964     QualType KmpInt32PtrTy =
3965         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3966     QualType Args[] = {VoidPtrTy};
3967     FunctionProtoType::ExtProtoInfo EPI;
3968     EPI.Variadic = true;
3969     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3970     Sema::CapturedParamNameType Params[] = {
3971         std::make_pair(".global_tid.", KmpInt32Ty),
3972         std::make_pair(".part_id.", KmpInt32PtrTy),
3973         std::make_pair(".privates.", VoidPtrTy),
3974         std::make_pair(
3975             ".copy_fn.",
3976             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3977         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3978         std::make_pair(StringRef(), QualType()) // __context with shared vars
3979     };
3980     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3981                              Params, /*OpenMPCaptureLevel=*/0);
3982     // Mark this captured region as inlined, because we don't use outlined
3983     // function directly.
3984     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3985         AlwaysInlineAttr::CreateImplicit(
3986             Context, {}, AttributeCommonInfo::AS_Keyword,
3987             AlwaysInlineAttr::Keyword_forceinline));
3988     Sema::CapturedParamNameType ParamsTarget[] = {
3989         std::make_pair(StringRef(), QualType()) // __context with shared vars
3990     };
3991     // Start a captured region for 'target' with no implicit parameters.
3992     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3993                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3994     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3995         std::make_pair(".global_tid.", KmpInt32PtrTy),
3996         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3997         std::make_pair(StringRef(), QualType()) // __context with shared vars
3998     };
3999     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4000     // the same implicit parameters.
4001     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4002                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
4003     break;
4004   }
4005   case OMPD_target:
4006   case OMPD_target_simd: {
4007     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4008     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4009     QualType KmpInt32PtrTy =
4010         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4011     QualType Args[] = {VoidPtrTy};
4012     FunctionProtoType::ExtProtoInfo EPI;
4013     EPI.Variadic = true;
4014     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4015     Sema::CapturedParamNameType Params[] = {
4016         std::make_pair(".global_tid.", KmpInt32Ty),
4017         std::make_pair(".part_id.", KmpInt32PtrTy),
4018         std::make_pair(".privates.", VoidPtrTy),
4019         std::make_pair(
4020             ".copy_fn.",
4021             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4022         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4023         std::make_pair(StringRef(), QualType()) // __context with shared vars
4024     };
4025     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4026                              Params, /*OpenMPCaptureLevel=*/0);
4027     // Mark this captured region as inlined, because we don't use outlined
4028     // function directly.
4029     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4030         AlwaysInlineAttr::CreateImplicit(
4031             Context, {}, AttributeCommonInfo::AS_Keyword,
4032             AlwaysInlineAttr::Keyword_forceinline));
4033     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4034                              std::make_pair(StringRef(), QualType()),
4035                              /*OpenMPCaptureLevel=*/1);
4036     break;
4037   }
4038   case OMPD_atomic:
4039   case OMPD_critical:
4040   case OMPD_section:
4041   case OMPD_master:
4042   case OMPD_masked:
4043   case OMPD_tile:
4044   case OMPD_unroll:
4045     break;
4046   case OMPD_loop:
4047     // TODO: 'loop' may require additional parameters depending on the binding.
4048     // Treat similar to OMPD_simd/OMPD_for for now.
4049   case OMPD_simd:
4050   case OMPD_for:
4051   case OMPD_for_simd:
4052   case OMPD_sections:
4053   case OMPD_single:
4054   case OMPD_taskgroup:
4055   case OMPD_distribute:
4056   case OMPD_distribute_simd:
4057   case OMPD_ordered:
4058   case OMPD_target_data:
4059   case OMPD_dispatch: {
4060     Sema::CapturedParamNameType Params[] = {
4061         std::make_pair(StringRef(), QualType()) // __context with shared vars
4062     };
4063     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4064                              Params);
4065     break;
4066   }
4067   case OMPD_task: {
4068     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4069     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4070     QualType KmpInt32PtrTy =
4071         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4072     QualType Args[] = {VoidPtrTy};
4073     FunctionProtoType::ExtProtoInfo EPI;
4074     EPI.Variadic = true;
4075     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4076     Sema::CapturedParamNameType Params[] = {
4077         std::make_pair(".global_tid.", KmpInt32Ty),
4078         std::make_pair(".part_id.", KmpInt32PtrTy),
4079         std::make_pair(".privates.", VoidPtrTy),
4080         std::make_pair(
4081             ".copy_fn.",
4082             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4083         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4084         std::make_pair(StringRef(), QualType()) // __context with shared vars
4085     };
4086     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4087                              Params);
4088     // Mark this captured region as inlined, because we don't use outlined
4089     // function directly.
4090     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4091         AlwaysInlineAttr::CreateImplicit(
4092             Context, {}, AttributeCommonInfo::AS_Keyword,
4093             AlwaysInlineAttr::Keyword_forceinline));
4094     break;
4095   }
4096   case OMPD_taskloop:
4097   case OMPD_taskloop_simd:
4098   case OMPD_master_taskloop:
4099   case OMPD_master_taskloop_simd: {
4100     QualType KmpInt32Ty =
4101         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4102             .withConst();
4103     QualType KmpUInt64Ty =
4104         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4105             .withConst();
4106     QualType KmpInt64Ty =
4107         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4108             .withConst();
4109     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4110     QualType KmpInt32PtrTy =
4111         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4112     QualType Args[] = {VoidPtrTy};
4113     FunctionProtoType::ExtProtoInfo EPI;
4114     EPI.Variadic = true;
4115     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4116     Sema::CapturedParamNameType Params[] = {
4117         std::make_pair(".global_tid.", KmpInt32Ty),
4118         std::make_pair(".part_id.", KmpInt32PtrTy),
4119         std::make_pair(".privates.", VoidPtrTy),
4120         std::make_pair(
4121             ".copy_fn.",
4122             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4123         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4124         std::make_pair(".lb.", KmpUInt64Ty),
4125         std::make_pair(".ub.", KmpUInt64Ty),
4126         std::make_pair(".st.", KmpInt64Ty),
4127         std::make_pair(".liter.", KmpInt32Ty),
4128         std::make_pair(".reductions.", VoidPtrTy),
4129         std::make_pair(StringRef(), QualType()) // __context with shared vars
4130     };
4131     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4132                              Params);
4133     // Mark this captured region as inlined, because we don't use outlined
4134     // function directly.
4135     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4136         AlwaysInlineAttr::CreateImplicit(
4137             Context, {}, AttributeCommonInfo::AS_Keyword,
4138             AlwaysInlineAttr::Keyword_forceinline));
4139     break;
4140   }
4141   case OMPD_parallel_master_taskloop:
4142   case OMPD_parallel_master_taskloop_simd: {
4143     QualType KmpInt32Ty =
4144         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4145             .withConst();
4146     QualType KmpUInt64Ty =
4147         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4148             .withConst();
4149     QualType KmpInt64Ty =
4150         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4151             .withConst();
4152     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4153     QualType KmpInt32PtrTy =
4154         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4155     Sema::CapturedParamNameType ParamsParallel[] = {
4156         std::make_pair(".global_tid.", KmpInt32PtrTy),
4157         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4158         std::make_pair(StringRef(), QualType()) // __context with shared vars
4159     };
4160     // Start a captured region for 'parallel'.
4161     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4162                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4163     QualType Args[] = {VoidPtrTy};
4164     FunctionProtoType::ExtProtoInfo EPI;
4165     EPI.Variadic = true;
4166     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4167     Sema::CapturedParamNameType Params[] = {
4168         std::make_pair(".global_tid.", KmpInt32Ty),
4169         std::make_pair(".part_id.", KmpInt32PtrTy),
4170         std::make_pair(".privates.", VoidPtrTy),
4171         std::make_pair(
4172             ".copy_fn.",
4173             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4174         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4175         std::make_pair(".lb.", KmpUInt64Ty),
4176         std::make_pair(".ub.", KmpUInt64Ty),
4177         std::make_pair(".st.", KmpInt64Ty),
4178         std::make_pair(".liter.", KmpInt32Ty),
4179         std::make_pair(".reductions.", VoidPtrTy),
4180         std::make_pair(StringRef(), QualType()) // __context with shared vars
4181     };
4182     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4183                              Params, /*OpenMPCaptureLevel=*/1);
4184     // Mark this captured region as inlined, because we don't use outlined
4185     // function directly.
4186     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4187         AlwaysInlineAttr::CreateImplicit(
4188             Context, {}, AttributeCommonInfo::AS_Keyword,
4189             AlwaysInlineAttr::Keyword_forceinline));
4190     break;
4191   }
4192   case OMPD_distribute_parallel_for_simd:
4193   case OMPD_distribute_parallel_for: {
4194     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4195     QualType KmpInt32PtrTy =
4196         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4197     Sema::CapturedParamNameType Params[] = {
4198         std::make_pair(".global_tid.", KmpInt32PtrTy),
4199         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4200         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4201         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4202         std::make_pair(StringRef(), QualType()) // __context with shared vars
4203     };
4204     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4205                              Params);
4206     break;
4207   }
4208   case OMPD_target_teams_distribute_parallel_for:
4209   case OMPD_target_teams_distribute_parallel_for_simd: {
4210     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4211     QualType KmpInt32PtrTy =
4212         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4213     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4214 
4215     QualType Args[] = {VoidPtrTy};
4216     FunctionProtoType::ExtProtoInfo EPI;
4217     EPI.Variadic = true;
4218     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4219     Sema::CapturedParamNameType Params[] = {
4220         std::make_pair(".global_tid.", KmpInt32Ty),
4221         std::make_pair(".part_id.", KmpInt32PtrTy),
4222         std::make_pair(".privates.", VoidPtrTy),
4223         std::make_pair(
4224             ".copy_fn.",
4225             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4226         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4227         std::make_pair(StringRef(), QualType()) // __context with shared vars
4228     };
4229     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4230                              Params, /*OpenMPCaptureLevel=*/0);
4231     // Mark this captured region as inlined, because we don't use outlined
4232     // function directly.
4233     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4234         AlwaysInlineAttr::CreateImplicit(
4235             Context, {}, AttributeCommonInfo::AS_Keyword,
4236             AlwaysInlineAttr::Keyword_forceinline));
4237     Sema::CapturedParamNameType ParamsTarget[] = {
4238         std::make_pair(StringRef(), QualType()) // __context with shared vars
4239     };
4240     // Start a captured region for 'target' with no implicit parameters.
4241     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4242                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4243 
4244     Sema::CapturedParamNameType ParamsTeams[] = {
4245         std::make_pair(".global_tid.", KmpInt32PtrTy),
4246         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4247         std::make_pair(StringRef(), QualType()) // __context with shared vars
4248     };
4249     // Start a captured region for 'target' with no implicit parameters.
4250     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4251                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4252 
4253     Sema::CapturedParamNameType ParamsParallel[] = {
4254         std::make_pair(".global_tid.", KmpInt32PtrTy),
4255         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4256         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4257         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4258         std::make_pair(StringRef(), QualType()) // __context with shared vars
4259     };
4260     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4261     // the same implicit parameters.
4262     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4263                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4264     break;
4265   }
4266 
4267   case OMPD_teams_loop: {
4268     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4269     QualType KmpInt32PtrTy =
4270         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4271 
4272     Sema::CapturedParamNameType ParamsTeams[] = {
4273         std::make_pair(".global_tid.", KmpInt32PtrTy),
4274         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4275         std::make_pair(StringRef(), QualType()) // __context with shared vars
4276     };
4277     // Start a captured region for 'teams'.
4278     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4279                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4280     break;
4281   }
4282 
4283   case OMPD_teams_distribute_parallel_for:
4284   case OMPD_teams_distribute_parallel_for_simd: {
4285     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4286     QualType KmpInt32PtrTy =
4287         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4288 
4289     Sema::CapturedParamNameType ParamsTeams[] = {
4290         std::make_pair(".global_tid.", KmpInt32PtrTy),
4291         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4292         std::make_pair(StringRef(), QualType()) // __context with shared vars
4293     };
4294     // Start a captured region for 'target' with no implicit parameters.
4295     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4296                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4297 
4298     Sema::CapturedParamNameType ParamsParallel[] = {
4299         std::make_pair(".global_tid.", KmpInt32PtrTy),
4300         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4301         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4302         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4303         std::make_pair(StringRef(), QualType()) // __context with shared vars
4304     };
4305     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4306     // the same implicit parameters.
4307     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4308                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4309     break;
4310   }
4311   case OMPD_target_update:
4312   case OMPD_target_enter_data:
4313   case OMPD_target_exit_data: {
4314     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4315     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4316     QualType KmpInt32PtrTy =
4317         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4318     QualType Args[] = {VoidPtrTy};
4319     FunctionProtoType::ExtProtoInfo EPI;
4320     EPI.Variadic = true;
4321     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4322     Sema::CapturedParamNameType Params[] = {
4323         std::make_pair(".global_tid.", KmpInt32Ty),
4324         std::make_pair(".part_id.", KmpInt32PtrTy),
4325         std::make_pair(".privates.", VoidPtrTy),
4326         std::make_pair(
4327             ".copy_fn.",
4328             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4329         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4330         std::make_pair(StringRef(), QualType()) // __context with shared vars
4331     };
4332     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4333                              Params);
4334     // Mark this captured region as inlined, because we don't use outlined
4335     // function directly.
4336     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4337         AlwaysInlineAttr::CreateImplicit(
4338             Context, {}, AttributeCommonInfo::AS_Keyword,
4339             AlwaysInlineAttr::Keyword_forceinline));
4340     break;
4341   }
4342   case OMPD_threadprivate:
4343   case OMPD_allocate:
4344   case OMPD_taskyield:
4345   case OMPD_barrier:
4346   case OMPD_taskwait:
4347   case OMPD_cancellation_point:
4348   case OMPD_cancel:
4349   case OMPD_flush:
4350   case OMPD_depobj:
4351   case OMPD_scan:
4352   case OMPD_declare_reduction:
4353   case OMPD_declare_mapper:
4354   case OMPD_declare_simd:
4355   case OMPD_declare_target:
4356   case OMPD_end_declare_target:
4357   case OMPD_requires:
4358   case OMPD_declare_variant:
4359   case OMPD_begin_declare_variant:
4360   case OMPD_end_declare_variant:
4361   case OMPD_metadirective:
4362     llvm_unreachable("OpenMP Directive is not allowed");
4363   case OMPD_unknown:
4364   default:
4365     llvm_unreachable("Unknown OpenMP directive");
4366   }
4367   DSAStack->setContext(CurContext);
4368   handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
4369 }
4370 
4371 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4372   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4373 }
4374 
4375 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4376   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4377   getOpenMPCaptureRegions(CaptureRegions, DKind);
4378   return CaptureRegions.size();
4379 }
4380 
4381 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4382                                              Expr *CaptureExpr, bool WithInit,
4383                                              bool AsExpression) {
4384   assert(CaptureExpr);
4385   ASTContext &C = S.getASTContext();
4386   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4387   QualType Ty = Init->getType();
4388   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4389     if (S.getLangOpts().CPlusPlus) {
4390       Ty = C.getLValueReferenceType(Ty);
4391     } else {
4392       Ty = C.getPointerType(Ty);
4393       ExprResult Res =
4394           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4395       if (!Res.isUsable())
4396         return nullptr;
4397       Init = Res.get();
4398     }
4399     WithInit = true;
4400   }
4401   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4402                                           CaptureExpr->getBeginLoc());
4403   if (!WithInit)
4404     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4405   S.CurContext->addHiddenDecl(CED);
4406   Sema::TentativeAnalysisScope Trap(S);
4407   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4408   return CED;
4409 }
4410 
4411 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4412                                  bool WithInit) {
4413   OMPCapturedExprDecl *CD;
4414   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4415     CD = cast<OMPCapturedExprDecl>(VD);
4416   else
4417     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4418                           /*AsExpression=*/false);
4419   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4420                           CaptureExpr->getExprLoc());
4421 }
4422 
4423 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4424   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4425   if (!Ref) {
4426     OMPCapturedExprDecl *CD = buildCaptureDecl(
4427         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4428         /*WithInit=*/true, /*AsExpression=*/true);
4429     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4430                            CaptureExpr->getExprLoc());
4431   }
4432   ExprResult Res = Ref;
4433   if (!S.getLangOpts().CPlusPlus &&
4434       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4435       Ref->getType()->isPointerType()) {
4436     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4437     if (!Res.isUsable())
4438       return ExprError();
4439   }
4440   return S.DefaultLvalueConversion(Res.get());
4441 }
4442 
4443 namespace {
4444 // OpenMP directives parsed in this section are represented as a
4445 // CapturedStatement with an associated statement.  If a syntax error
4446 // is detected during the parsing of the associated statement, the
4447 // compiler must abort processing and close the CapturedStatement.
4448 //
4449 // Combined directives such as 'target parallel' have more than one
4450 // nested CapturedStatements.  This RAII ensures that we unwind out
4451 // of all the nested CapturedStatements when an error is found.
4452 class CaptureRegionUnwinderRAII {
4453 private:
4454   Sema &S;
4455   bool &ErrorFound;
4456   OpenMPDirectiveKind DKind = OMPD_unknown;
4457 
4458 public:
4459   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4460                             OpenMPDirectiveKind DKind)
4461       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4462   ~CaptureRegionUnwinderRAII() {
4463     if (ErrorFound) {
4464       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4465       while (--ThisCaptureLevel >= 0)
4466         S.ActOnCapturedRegionError();
4467     }
4468   }
4469 };
4470 } // namespace
4471 
4472 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4473   // Capture variables captured by reference in lambdas for target-based
4474   // directives.
4475   if (!CurContext->isDependentContext() &&
4476       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4477        isOpenMPTargetDataManagementDirective(
4478            DSAStack->getCurrentDirective()))) {
4479     QualType Type = V->getType();
4480     if (const auto *RD = Type.getCanonicalType()
4481                              .getNonReferenceType()
4482                              ->getAsCXXRecordDecl()) {
4483       bool SavedForceCaptureByReferenceInTargetExecutable =
4484           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4485       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4486           /*V=*/true);
4487       if (RD->isLambda()) {
4488         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4489         FieldDecl *ThisCapture;
4490         RD->getCaptureFields(Captures, ThisCapture);
4491         for (const LambdaCapture &LC : RD->captures()) {
4492           if (LC.getCaptureKind() == LCK_ByRef) {
4493             VarDecl *VD = LC.getCapturedVar();
4494             DeclContext *VDC = VD->getDeclContext();
4495             if (!VDC->Encloses(CurContext))
4496               continue;
4497             MarkVariableReferenced(LC.getLocation(), VD);
4498           } else if (LC.getCaptureKind() == LCK_This) {
4499             QualType ThisTy = getCurrentThisType();
4500             if (!ThisTy.isNull() &&
4501                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4502               CheckCXXThisCapture(LC.getLocation());
4503           }
4504         }
4505       }
4506       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4507           SavedForceCaptureByReferenceInTargetExecutable);
4508     }
4509   }
4510 }
4511 
4512 static bool checkOrderedOrderSpecified(Sema &S,
4513                                        const ArrayRef<OMPClause *> Clauses) {
4514   const OMPOrderedClause *Ordered = nullptr;
4515   const OMPOrderClause *Order = nullptr;
4516 
4517   for (const OMPClause *Clause : Clauses) {
4518     if (Clause->getClauseKind() == OMPC_ordered)
4519       Ordered = cast<OMPOrderedClause>(Clause);
4520     else if (Clause->getClauseKind() == OMPC_order) {
4521       Order = cast<OMPOrderClause>(Clause);
4522       if (Order->getKind() != OMPC_ORDER_concurrent)
4523         Order = nullptr;
4524     }
4525     if (Ordered && Order)
4526       break;
4527   }
4528 
4529   if (Ordered && Order) {
4530     S.Diag(Order->getKindKwLoc(),
4531            diag::err_omp_simple_clause_incompatible_with_ordered)
4532         << getOpenMPClauseName(OMPC_order)
4533         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4534         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4535     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4536         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4537     return true;
4538   }
4539   return false;
4540 }
4541 
4542 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4543                                       ArrayRef<OMPClause *> Clauses) {
4544   handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
4545                                      /* ScopeEntry */ false);
4546   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4547       DSAStack->getCurrentDirective() == OMPD_critical ||
4548       DSAStack->getCurrentDirective() == OMPD_section ||
4549       DSAStack->getCurrentDirective() == OMPD_master ||
4550       DSAStack->getCurrentDirective() == OMPD_masked)
4551     return S;
4552 
4553   bool ErrorFound = false;
4554   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4555       *this, ErrorFound, DSAStack->getCurrentDirective());
4556   if (!S.isUsable()) {
4557     ErrorFound = true;
4558     return StmtError();
4559   }
4560 
4561   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4562   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4563   OMPOrderedClause *OC = nullptr;
4564   OMPScheduleClause *SC = nullptr;
4565   SmallVector<const OMPLinearClause *, 4> LCs;
4566   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4567   // This is required for proper codegen.
4568   for (OMPClause *Clause : Clauses) {
4569     if (!LangOpts.OpenMPSimd &&
4570         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4571         Clause->getClauseKind() == OMPC_in_reduction) {
4572       // Capture taskgroup task_reduction descriptors inside the tasking regions
4573       // with the corresponding in_reduction items.
4574       auto *IRC = cast<OMPInReductionClause>(Clause);
4575       for (Expr *E : IRC->taskgroup_descriptors())
4576         if (E)
4577           MarkDeclarationsReferencedInExpr(E);
4578     }
4579     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4580         Clause->getClauseKind() == OMPC_copyprivate ||
4581         (getLangOpts().OpenMPUseTLS &&
4582          getASTContext().getTargetInfo().isTLSSupported() &&
4583          Clause->getClauseKind() == OMPC_copyin)) {
4584       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4585       // Mark all variables in private list clauses as used in inner region.
4586       for (Stmt *VarRef : Clause->children()) {
4587         if (auto *E = cast_or_null<Expr>(VarRef)) {
4588           MarkDeclarationsReferencedInExpr(E);
4589         }
4590       }
4591       DSAStack->setForceVarCapturing(/*V=*/false);
4592     } else if (isOpenMPLoopTransformationDirective(
4593                    DSAStack->getCurrentDirective())) {
4594       assert(CaptureRegions.empty() &&
4595              "No captured regions in loop transformation directives.");
4596     } else if (CaptureRegions.size() > 1 ||
4597                CaptureRegions.back() != OMPD_unknown) {
4598       if (auto *C = OMPClauseWithPreInit::get(Clause))
4599         PICs.push_back(C);
4600       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4601         if (Expr *E = C->getPostUpdateExpr())
4602           MarkDeclarationsReferencedInExpr(E);
4603       }
4604     }
4605     if (Clause->getClauseKind() == OMPC_schedule)
4606       SC = cast<OMPScheduleClause>(Clause);
4607     else if (Clause->getClauseKind() == OMPC_ordered)
4608       OC = cast<OMPOrderedClause>(Clause);
4609     else if (Clause->getClauseKind() == OMPC_linear)
4610       LCs.push_back(cast<OMPLinearClause>(Clause));
4611   }
4612   // Capture allocator expressions if used.
4613   for (Expr *E : DSAStack->getInnerAllocators())
4614     MarkDeclarationsReferencedInExpr(E);
4615   // OpenMP, 2.7.1 Loop Construct, Restrictions
4616   // The nonmonotonic modifier cannot be specified if an ordered clause is
4617   // specified.
4618   if (SC &&
4619       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4620        SC->getSecondScheduleModifier() ==
4621            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4622       OC) {
4623     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4624              ? SC->getFirstScheduleModifierLoc()
4625              : SC->getSecondScheduleModifierLoc(),
4626          diag::err_omp_simple_clause_incompatible_with_ordered)
4627         << getOpenMPClauseName(OMPC_schedule)
4628         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4629                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4630         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4631     ErrorFound = true;
4632   }
4633   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4634   // If an order(concurrent) clause is present, an ordered clause may not appear
4635   // on the same directive.
4636   if (checkOrderedOrderSpecified(*this, Clauses))
4637     ErrorFound = true;
4638   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4639     for (const OMPLinearClause *C : LCs) {
4640       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4641           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4642     }
4643     ErrorFound = true;
4644   }
4645   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4646       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4647       OC->getNumForLoops()) {
4648     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4649         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4650     ErrorFound = true;
4651   }
4652   if (ErrorFound) {
4653     return StmtError();
4654   }
4655   StmtResult SR = S;
4656   unsigned CompletedRegions = 0;
4657   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4658     // Mark all variables in private list clauses as used in inner region.
4659     // Required for proper codegen of combined directives.
4660     // TODO: add processing for other clauses.
4661     if (ThisCaptureRegion != OMPD_unknown) {
4662       for (const clang::OMPClauseWithPreInit *C : PICs) {
4663         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4664         // Find the particular capture region for the clause if the
4665         // directive is a combined one with multiple capture regions.
4666         // If the directive is not a combined one, the capture region
4667         // associated with the clause is OMPD_unknown and is generated
4668         // only once.
4669         if (CaptureRegion == ThisCaptureRegion ||
4670             CaptureRegion == OMPD_unknown) {
4671           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4672             for (Decl *D : DS->decls())
4673               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4674           }
4675         }
4676       }
4677     }
4678     if (ThisCaptureRegion == OMPD_target) {
4679       // Capture allocator traits in the target region. They are used implicitly
4680       // and, thus, are not captured by default.
4681       for (OMPClause *C : Clauses) {
4682         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4683           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4684                ++I) {
4685             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4686             if (Expr *E = D.AllocatorTraits)
4687               MarkDeclarationsReferencedInExpr(E);
4688           }
4689           continue;
4690         }
4691       }
4692     }
4693     if (ThisCaptureRegion == OMPD_parallel) {
4694       // Capture temp arrays for inscan reductions and locals in aligned
4695       // clauses.
4696       for (OMPClause *C : Clauses) {
4697         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4698           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4699             continue;
4700           for (Expr *E : RC->copy_array_temps())
4701             MarkDeclarationsReferencedInExpr(E);
4702         }
4703         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4704           for (Expr *E : AC->varlists())
4705             MarkDeclarationsReferencedInExpr(E);
4706         }
4707       }
4708     }
4709     if (++CompletedRegions == CaptureRegions.size())
4710       DSAStack->setBodyComplete();
4711     SR = ActOnCapturedRegionEnd(SR.get());
4712   }
4713   return SR;
4714 }
4715 
4716 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4717                               OpenMPDirectiveKind CancelRegion,
4718                               SourceLocation StartLoc) {
4719   // CancelRegion is only needed for cancel and cancellation_point.
4720   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4721     return false;
4722 
4723   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4724       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4725     return false;
4726 
4727   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4728       << getOpenMPDirectiveName(CancelRegion);
4729   return true;
4730 }
4731 
4732 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4733                                   OpenMPDirectiveKind CurrentRegion,
4734                                   const DeclarationNameInfo &CurrentName,
4735                                   OpenMPDirectiveKind CancelRegion,
4736                                   OpenMPBindClauseKind BindKind,
4737                                   SourceLocation StartLoc) {
4738   if (Stack->getCurScope()) {
4739     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4740     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4741     bool NestingProhibited = false;
4742     bool CloseNesting = true;
4743     bool OrphanSeen = false;
4744     enum {
4745       NoRecommend,
4746       ShouldBeInParallelRegion,
4747       ShouldBeInOrderedRegion,
4748       ShouldBeInTargetRegion,
4749       ShouldBeInTeamsRegion,
4750       ShouldBeInLoopSimdRegion,
4751     } Recommend = NoRecommend;
4752     if (isOpenMPSimdDirective(ParentRegion) &&
4753         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4754          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4755           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4756           CurrentRegion != OMPD_scan))) {
4757       // OpenMP [2.16, Nesting of Regions]
4758       // OpenMP constructs may not be nested inside a simd region.
4759       // OpenMP [2.8.1,simd Construct, Restrictions]
4760       // An ordered construct with the simd clause is the only OpenMP
4761       // construct that can appear in the simd region.
4762       // Allowing a SIMD construct nested in another SIMD construct is an
4763       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4764       // message.
4765       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4766       // The only OpenMP constructs that can be encountered during execution of
4767       // a simd region are the atomic construct, the loop construct, the simd
4768       // construct and the ordered construct with the simd clause.
4769       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4770                                  ? diag::err_omp_prohibited_region_simd
4771                                  : diag::warn_omp_nesting_simd)
4772           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4773       return CurrentRegion != OMPD_simd;
4774     }
4775     if (ParentRegion == OMPD_atomic) {
4776       // OpenMP [2.16, Nesting of Regions]
4777       // OpenMP constructs may not be nested inside an atomic region.
4778       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4779       return true;
4780     }
4781     if (CurrentRegion == OMPD_section) {
4782       // OpenMP [2.7.2, sections Construct, Restrictions]
4783       // Orphaned section directives are prohibited. That is, the section
4784       // directives must appear within the sections construct and must not be
4785       // encountered elsewhere in the sections region.
4786       if (ParentRegion != OMPD_sections &&
4787           ParentRegion != OMPD_parallel_sections) {
4788         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4789             << (ParentRegion != OMPD_unknown)
4790             << getOpenMPDirectiveName(ParentRegion);
4791         return true;
4792       }
4793       return false;
4794     }
4795     // Allow some constructs (except teams and cancellation constructs) to be
4796     // orphaned (they could be used in functions, called from OpenMP regions
4797     // with the required preconditions).
4798     if (ParentRegion == OMPD_unknown &&
4799         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4800         CurrentRegion != OMPD_cancellation_point &&
4801         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4802       return false;
4803     if (CurrentRegion == OMPD_cancellation_point ||
4804         CurrentRegion == OMPD_cancel) {
4805       // OpenMP [2.16, Nesting of Regions]
4806       // A cancellation point construct for which construct-type-clause is
4807       // taskgroup must be nested inside a task construct. A cancellation
4808       // point construct for which construct-type-clause is not taskgroup must
4809       // be closely nested inside an OpenMP construct that matches the type
4810       // specified in construct-type-clause.
4811       // A cancel construct for which construct-type-clause is taskgroup must be
4812       // nested inside a task construct. A cancel construct for which
4813       // construct-type-clause is not taskgroup must be closely nested inside an
4814       // OpenMP construct that matches the type specified in
4815       // construct-type-clause.
4816       NestingProhibited =
4817           !((CancelRegion == OMPD_parallel &&
4818              (ParentRegion == OMPD_parallel ||
4819               ParentRegion == OMPD_target_parallel)) ||
4820             (CancelRegion == OMPD_for &&
4821              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4822               ParentRegion == OMPD_target_parallel_for ||
4823               ParentRegion == OMPD_distribute_parallel_for ||
4824               ParentRegion == OMPD_teams_distribute_parallel_for ||
4825               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4826             (CancelRegion == OMPD_taskgroup &&
4827              (ParentRegion == OMPD_task ||
4828               (SemaRef.getLangOpts().OpenMP >= 50 &&
4829                (ParentRegion == OMPD_taskloop ||
4830                 ParentRegion == OMPD_master_taskloop ||
4831                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4832             (CancelRegion == OMPD_sections &&
4833              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4834               ParentRegion == OMPD_parallel_sections)));
4835       OrphanSeen = ParentRegion == OMPD_unknown;
4836     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4837       // OpenMP 5.1 [2.22, Nesting of Regions]
4838       // A masked region may not be closely nested inside a worksharing, loop,
4839       // atomic, task, or taskloop region.
4840       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4841                           isOpenMPGenericLoopDirective(ParentRegion) ||
4842                           isOpenMPTaskingDirective(ParentRegion);
4843     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4844       // OpenMP [2.16, Nesting of Regions]
4845       // A critical region may not be nested (closely or otherwise) inside a
4846       // critical region with the same name. Note that this restriction is not
4847       // sufficient to prevent deadlock.
4848       SourceLocation PreviousCriticalLoc;
4849       bool DeadLock = Stack->hasDirective(
4850           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4851                                               const DeclarationNameInfo &DNI,
4852                                               SourceLocation Loc) {
4853             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4854               PreviousCriticalLoc = Loc;
4855               return true;
4856             }
4857             return false;
4858           },
4859           false /* skip top directive */);
4860       if (DeadLock) {
4861         SemaRef.Diag(StartLoc,
4862                      diag::err_omp_prohibited_region_critical_same_name)
4863             << CurrentName.getName();
4864         if (PreviousCriticalLoc.isValid())
4865           SemaRef.Diag(PreviousCriticalLoc,
4866                        diag::note_omp_previous_critical_region);
4867         return true;
4868       }
4869     } else if (CurrentRegion == OMPD_barrier) {
4870       // OpenMP 5.1 [2.22, Nesting of Regions]
4871       // A barrier region may not be closely nested inside a worksharing, loop,
4872       // task, taskloop, critical, ordered, atomic, or masked region.
4873       NestingProhibited =
4874           isOpenMPWorksharingDirective(ParentRegion) ||
4875           isOpenMPGenericLoopDirective(ParentRegion) ||
4876           isOpenMPTaskingDirective(ParentRegion) ||
4877           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4878           ParentRegion == OMPD_parallel_master ||
4879           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4880     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4881                !isOpenMPParallelDirective(CurrentRegion) &&
4882                !isOpenMPTeamsDirective(CurrentRegion)) {
4883       // OpenMP 5.1 [2.22, Nesting of Regions]
4884       // A loop region that binds to a parallel region or a worksharing region
4885       // may not be closely nested inside a worksharing, loop, task, taskloop,
4886       // critical, ordered, atomic, or masked region.
4887       NestingProhibited =
4888           isOpenMPWorksharingDirective(ParentRegion) ||
4889           isOpenMPGenericLoopDirective(ParentRegion) ||
4890           isOpenMPTaskingDirective(ParentRegion) ||
4891           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4892           ParentRegion == OMPD_parallel_master ||
4893           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4894       Recommend = ShouldBeInParallelRegion;
4895     } else if (CurrentRegion == OMPD_ordered) {
4896       // OpenMP [2.16, Nesting of Regions]
4897       // An ordered region may not be closely nested inside a critical,
4898       // atomic, or explicit task region.
4899       // An ordered region must be closely nested inside a loop region (or
4900       // parallel loop region) with an ordered clause.
4901       // OpenMP [2.8.1,simd Construct, Restrictions]
4902       // An ordered construct with the simd clause is the only OpenMP construct
4903       // that can appear in the simd region.
4904       NestingProhibited = ParentRegion == OMPD_critical ||
4905                           isOpenMPTaskingDirective(ParentRegion) ||
4906                           !(isOpenMPSimdDirective(ParentRegion) ||
4907                             Stack->isParentOrderedRegion());
4908       Recommend = ShouldBeInOrderedRegion;
4909     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4910       // OpenMP [2.16, Nesting of Regions]
4911       // If specified, a teams construct must be contained within a target
4912       // construct.
4913       NestingProhibited =
4914           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4915           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4916            ParentRegion != OMPD_target);
4917       OrphanSeen = ParentRegion == OMPD_unknown;
4918       Recommend = ShouldBeInTargetRegion;
4919     } else if (CurrentRegion == OMPD_scan) {
4920       // OpenMP [2.16, Nesting of Regions]
4921       // If specified, a teams construct must be contained within a target
4922       // construct.
4923       NestingProhibited =
4924           SemaRef.LangOpts.OpenMP < 50 ||
4925           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4926            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4927            ParentRegion != OMPD_parallel_for_simd);
4928       OrphanSeen = ParentRegion == OMPD_unknown;
4929       Recommend = ShouldBeInLoopSimdRegion;
4930     }
4931     if (!NestingProhibited &&
4932         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4933         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4934         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4935       // OpenMP [5.1, 2.22, Nesting of Regions]
4936       // distribute, distribute simd, distribute parallel worksharing-loop,
4937       // distribute parallel worksharing-loop SIMD, loop, parallel regions,
4938       // including any parallel regions arising from combined constructs,
4939       // omp_get_num_teams() regions, and omp_get_team_num() regions are the
4940       // only OpenMP regions that may be strictly nested inside the teams
4941       // region.
4942       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4943                           !isOpenMPDistributeDirective(CurrentRegion) &&
4944                           CurrentRegion != OMPD_loop;
4945       Recommend = ShouldBeInParallelRegion;
4946     }
4947     if (!NestingProhibited && CurrentRegion == OMPD_loop) {
4948       // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
4949       // If the bind clause is present on the loop construct and binding is
4950       // teams then the corresponding loop region must be strictly nested inside
4951       // a teams region.
4952       NestingProhibited = BindKind == OMPC_BIND_teams &&
4953                           ParentRegion != OMPD_teams &&
4954                           ParentRegion != OMPD_target_teams;
4955       Recommend = ShouldBeInTeamsRegion;
4956     }
4957     if (!NestingProhibited &&
4958         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4959       // OpenMP 4.5 [2.17 Nesting of Regions]
4960       // The region associated with the distribute construct must be strictly
4961       // nested inside a teams region
4962       NestingProhibited =
4963           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4964       Recommend = ShouldBeInTeamsRegion;
4965     }
4966     if (!NestingProhibited &&
4967         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4968          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4969       // OpenMP 4.5 [2.17 Nesting of Regions]
4970       // If a target, target update, target data, target enter data, or
4971       // target exit data construct is encountered during execution of a
4972       // target region, the behavior is unspecified.
4973       NestingProhibited = Stack->hasDirective(
4974           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4975                              SourceLocation) {
4976             if (isOpenMPTargetExecutionDirective(K)) {
4977               OffendingRegion = K;
4978               return true;
4979             }
4980             return false;
4981           },
4982           false /* don't skip top directive */);
4983       CloseNesting = false;
4984     }
4985     if (NestingProhibited) {
4986       if (OrphanSeen) {
4987         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4988             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4989       } else {
4990         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4991             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4992             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4993       }
4994       return true;
4995     }
4996   }
4997   return false;
4998 }
4999 
5000 struct Kind2Unsigned {
5001   using argument_type = OpenMPDirectiveKind;
5002   unsigned operator()(argument_type DK) { return unsigned(DK); }
5003 };
5004 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
5005                            ArrayRef<OMPClause *> Clauses,
5006                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
5007   bool ErrorFound = false;
5008   unsigned NamedModifiersNumber = 0;
5009   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
5010   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
5011   SmallVector<SourceLocation, 4> NameModifierLoc;
5012   for (const OMPClause *C : Clauses) {
5013     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
5014       // At most one if clause without a directive-name-modifier can appear on
5015       // the directive.
5016       OpenMPDirectiveKind CurNM = IC->getNameModifier();
5017       if (FoundNameModifiers[CurNM]) {
5018         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
5019             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
5020             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
5021         ErrorFound = true;
5022       } else if (CurNM != OMPD_unknown) {
5023         NameModifierLoc.push_back(IC->getNameModifierLoc());
5024         ++NamedModifiersNumber;
5025       }
5026       FoundNameModifiers[CurNM] = IC;
5027       if (CurNM == OMPD_unknown)
5028         continue;
5029       // Check if the specified name modifier is allowed for the current
5030       // directive.
5031       // At most one if clause with the particular directive-name-modifier can
5032       // appear on the directive.
5033       if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
5034         S.Diag(IC->getNameModifierLoc(),
5035                diag::err_omp_wrong_if_directive_name_modifier)
5036             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
5037         ErrorFound = true;
5038       }
5039     }
5040   }
5041   // If any if clause on the directive includes a directive-name-modifier then
5042   // all if clauses on the directive must include a directive-name-modifier.
5043   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5044     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5045       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5046              diag::err_omp_no_more_if_clause);
5047     } else {
5048       std::string Values;
5049       std::string Sep(", ");
5050       unsigned AllowedCnt = 0;
5051       unsigned TotalAllowedNum =
5052           AllowedNameModifiers.size() - NamedModifiersNumber;
5053       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5054            ++Cnt) {
5055         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5056         if (!FoundNameModifiers[NM]) {
5057           Values += "'";
5058           Values += getOpenMPDirectiveName(NM);
5059           Values += "'";
5060           if (AllowedCnt + 2 == TotalAllowedNum)
5061             Values += " or ";
5062           else if (AllowedCnt + 1 != TotalAllowedNum)
5063             Values += Sep;
5064           ++AllowedCnt;
5065         }
5066       }
5067       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5068              diag::err_omp_unnamed_if_clause)
5069           << (TotalAllowedNum > 1) << Values;
5070     }
5071     for (SourceLocation Loc : NameModifierLoc) {
5072       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5073     }
5074     ErrorFound = true;
5075   }
5076   return ErrorFound;
5077 }
5078 
5079 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
5080                                                    SourceLocation &ELoc,
5081                                                    SourceRange &ERange,
5082                                                    bool AllowArraySection) {
5083   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5084       RefExpr->containsUnexpandedParameterPack())
5085     return std::make_pair(nullptr, true);
5086 
5087   // OpenMP [3.1, C/C++]
5088   //  A list item is a variable name.
5089   // OpenMP  [2.9.3.3, Restrictions, p.1]
5090   //  A variable that is part of another variable (as an array or
5091   //  structure element) cannot appear in a private clause.
5092   RefExpr = RefExpr->IgnoreParens();
5093   enum {
5094     NoArrayExpr = -1,
5095     ArraySubscript = 0,
5096     OMPArraySection = 1
5097   } IsArrayExpr = NoArrayExpr;
5098   if (AllowArraySection) {
5099     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5100       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5101       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5102         Base = TempASE->getBase()->IgnoreParenImpCasts();
5103       RefExpr = Base;
5104       IsArrayExpr = ArraySubscript;
5105     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5106       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5107       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5108         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5109       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5110         Base = TempASE->getBase()->IgnoreParenImpCasts();
5111       RefExpr = Base;
5112       IsArrayExpr = OMPArraySection;
5113     }
5114   }
5115   ELoc = RefExpr->getExprLoc();
5116   ERange = RefExpr->getSourceRange();
5117   RefExpr = RefExpr->IgnoreParenImpCasts();
5118   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5119   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5120   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5121       (S.getCurrentThisType().isNull() || !ME ||
5122        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5123        !isa<FieldDecl>(ME->getMemberDecl()))) {
5124     if (IsArrayExpr != NoArrayExpr) {
5125       S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5126           << IsArrayExpr << ERange;
5127     } else {
5128       S.Diag(ELoc,
5129              AllowArraySection
5130                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5131                  : diag::err_omp_expected_var_name_member_expr)
5132           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5133     }
5134     return std::make_pair(nullptr, false);
5135   }
5136   return std::make_pair(
5137       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5138 }
5139 
5140 namespace {
5141 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5142 /// target regions.
5143 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5144   DSAStackTy *S = nullptr;
5145 
5146 public:
5147   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5148     return S->isUsesAllocatorsDecl(E->getDecl())
5149                .getValueOr(
5150                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5151            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5152   }
5153   bool VisitStmt(const Stmt *S) {
5154     for (const Stmt *Child : S->children()) {
5155       if (Child && Visit(Child))
5156         return true;
5157     }
5158     return false;
5159   }
5160   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5161 };
5162 } // namespace
5163 
5164 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5165                                  ArrayRef<OMPClause *> Clauses) {
5166   assert(!S.CurContext->isDependentContext() &&
5167          "Expected non-dependent context.");
5168   auto AllocateRange =
5169       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5170   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5171   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5172     return isOpenMPPrivate(C->getClauseKind());
5173   });
5174   for (OMPClause *Cl : PrivateRange) {
5175     MutableArrayRef<Expr *>::iterator I, It, Et;
5176     if (Cl->getClauseKind() == OMPC_private) {
5177       auto *PC = cast<OMPPrivateClause>(Cl);
5178       I = PC->private_copies().begin();
5179       It = PC->varlist_begin();
5180       Et = PC->varlist_end();
5181     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5182       auto *PC = cast<OMPFirstprivateClause>(Cl);
5183       I = PC->private_copies().begin();
5184       It = PC->varlist_begin();
5185       Et = PC->varlist_end();
5186     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5187       auto *PC = cast<OMPLastprivateClause>(Cl);
5188       I = PC->private_copies().begin();
5189       It = PC->varlist_begin();
5190       Et = PC->varlist_end();
5191     } else if (Cl->getClauseKind() == OMPC_linear) {
5192       auto *PC = cast<OMPLinearClause>(Cl);
5193       I = PC->privates().begin();
5194       It = PC->varlist_begin();
5195       Et = PC->varlist_end();
5196     } else if (Cl->getClauseKind() == OMPC_reduction) {
5197       auto *PC = cast<OMPReductionClause>(Cl);
5198       I = PC->privates().begin();
5199       It = PC->varlist_begin();
5200       Et = PC->varlist_end();
5201     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5202       auto *PC = cast<OMPTaskReductionClause>(Cl);
5203       I = PC->privates().begin();
5204       It = PC->varlist_begin();
5205       Et = PC->varlist_end();
5206     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5207       auto *PC = cast<OMPInReductionClause>(Cl);
5208       I = PC->privates().begin();
5209       It = PC->varlist_begin();
5210       Et = PC->varlist_end();
5211     } else {
5212       llvm_unreachable("Expected private clause.");
5213     }
5214     for (Expr *E : llvm::make_range(It, Et)) {
5215       if (!*I) {
5216         ++I;
5217         continue;
5218       }
5219       SourceLocation ELoc;
5220       SourceRange ERange;
5221       Expr *SimpleRefExpr = E;
5222       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5223                                 /*AllowArraySection=*/true);
5224       DeclToCopy.try_emplace(Res.first,
5225                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5226       ++I;
5227     }
5228   }
5229   for (OMPClause *C : AllocateRange) {
5230     auto *AC = cast<OMPAllocateClause>(C);
5231     if (S.getLangOpts().OpenMP >= 50 &&
5232         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5233         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5234         AC->getAllocator()) {
5235       Expr *Allocator = AC->getAllocator();
5236       // OpenMP, 2.12.5 target Construct
5237       // Memory allocators that do not appear in a uses_allocators clause cannot
5238       // appear as an allocator in an allocate clause or be used in the target
5239       // region unless a requires directive with the dynamic_allocators clause
5240       // is present in the same compilation unit.
5241       AllocatorChecker Checker(Stack);
5242       if (Checker.Visit(Allocator))
5243         S.Diag(Allocator->getExprLoc(),
5244                diag::err_omp_allocator_not_in_uses_allocators)
5245             << Allocator->getSourceRange();
5246     }
5247     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5248         getAllocatorKind(S, Stack, AC->getAllocator());
5249     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5250     // For task, taskloop or target directives, allocation requests to memory
5251     // allocators with the trait access set to thread result in unspecified
5252     // behavior.
5253     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5254         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5255          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5256       S.Diag(AC->getAllocator()->getExprLoc(),
5257              diag::warn_omp_allocate_thread_on_task_target_directive)
5258           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5259     }
5260     for (Expr *E : AC->varlists()) {
5261       SourceLocation ELoc;
5262       SourceRange ERange;
5263       Expr *SimpleRefExpr = E;
5264       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5265       ValueDecl *VD = Res.first;
5266       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5267       if (!isOpenMPPrivate(Data.CKind)) {
5268         S.Diag(E->getExprLoc(),
5269                diag::err_omp_expected_private_copy_for_allocate);
5270         continue;
5271       }
5272       VarDecl *PrivateVD = DeclToCopy[VD];
5273       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5274                                             AllocatorKind, AC->getAllocator()))
5275         continue;
5276       // Placeholder until allocate clause supports align modifier.
5277       Expr *Alignment = nullptr;
5278       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5279                                 Alignment, E->getSourceRange());
5280     }
5281   }
5282 }
5283 
5284 namespace {
5285 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5286 ///
5287 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5288 /// context. DeclRefExpr used inside the new context are changed to refer to the
5289 /// captured variable instead.
5290 class CaptureVars : public TreeTransform<CaptureVars> {
5291   using BaseTransform = TreeTransform<CaptureVars>;
5292 
5293 public:
5294   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5295 
5296   bool AlwaysRebuild() { return true; }
5297 };
5298 } // namespace
5299 
5300 static VarDecl *precomputeExpr(Sema &Actions,
5301                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5302                                StringRef Name) {
5303   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5304   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5305                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5306   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5307       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5308   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5309   BodyStmts.push_back(NewDeclStmt);
5310   return NewVar;
5311 }
5312 
5313 /// Create a closure that computes the number of iterations of a loop.
5314 ///
5315 /// \param Actions   The Sema object.
5316 /// \param LogicalTy Type for the logical iteration number.
5317 /// \param Rel       Comparison operator of the loop condition.
5318 /// \param StartExpr Value of the loop counter at the first iteration.
5319 /// \param StopExpr  Expression the loop counter is compared against in the loop
5320 /// condition. \param StepExpr      Amount of increment after each iteration.
5321 ///
5322 /// \return Closure (CapturedStmt) of the distance calculation.
5323 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5324                                        BinaryOperator::Opcode Rel,
5325                                        Expr *StartExpr, Expr *StopExpr,
5326                                        Expr *StepExpr) {
5327   ASTContext &Ctx = Actions.getASTContext();
5328   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5329 
5330   // Captured regions currently don't support return values, we use an
5331   // out-parameter instead. All inputs are implicit captures.
5332   // TODO: Instead of capturing each DeclRefExpr occurring in
5333   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5334   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5335   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5336                                           {StringRef(), QualType()}};
5337   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5338 
5339   Stmt *Body;
5340   {
5341     Sema::CompoundScopeRAII CompoundScope(Actions);
5342     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5343 
5344     // Get the LValue expression for the result.
5345     ImplicitParamDecl *DistParam = CS->getParam(0);
5346     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5347         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5348 
5349     SmallVector<Stmt *, 4> BodyStmts;
5350 
5351     // Capture all referenced variable references.
5352     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5353     // CapturedStmt, we could compute them before and capture the result, to be
5354     // used jointly with the LoopVar function.
5355     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5356     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5357     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5358     auto BuildVarRef = [&](VarDecl *VD) {
5359       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5360     };
5361 
5362     IntegerLiteral *Zero = IntegerLiteral::Create(
5363         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5364     IntegerLiteral *One = IntegerLiteral::Create(
5365         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5366     Expr *Dist;
5367     if (Rel == BO_NE) {
5368       // When using a != comparison, the increment can be +1 or -1. This can be
5369       // dynamic at runtime, so we need to check for the direction.
5370       Expr *IsNegStep = AssertSuccess(
5371           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5372 
5373       // Positive increment.
5374       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5375           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5376       ForwardRange = AssertSuccess(
5377           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5378       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5379           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5380 
5381       // Negative increment.
5382       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5383           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5384       BackwardRange = AssertSuccess(
5385           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5386       Expr *NegIncAmount = AssertSuccess(
5387           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5388       Expr *BackwardDist = AssertSuccess(
5389           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5390 
5391       // Use the appropriate case.
5392       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5393           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5394     } else {
5395       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5396              "Expected one of these relational operators");
5397 
5398       // We can derive the direction from any other comparison operator. It is
5399       // non well-formed OpenMP if Step increments/decrements in the other
5400       // directions. Whether at least the first iteration passes the loop
5401       // condition.
5402       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5403           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5404 
5405       // Compute the range between first and last counter value.
5406       Expr *Range;
5407       if (Rel == BO_GE || Rel == BO_GT)
5408         Range = AssertSuccess(Actions.BuildBinOp(
5409             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5410       else
5411         Range = AssertSuccess(Actions.BuildBinOp(
5412             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5413 
5414       // Ensure unsigned range space.
5415       Range =
5416           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5417 
5418       if (Rel == BO_LE || Rel == BO_GE) {
5419         // Add one to the range if the relational operator is inclusive.
5420         Range =
5421             AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One));
5422       }
5423 
5424       // Divide by the absolute step amount. If the range is not a multiple of
5425       // the step size, rounding-up the effective upper bound ensures that the
5426       // last iteration is included.
5427       // Note that the rounding-up may cause an overflow in a temporry that
5428       // could be avoided, but would have occurred in a C-style for-loop as well.
5429       Expr *Divisor = BuildVarRef(NewStep);
5430       if (Rel == BO_GE || Rel == BO_GT)
5431         Divisor =
5432             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5433       Expr *DivisorMinusOne =
5434           AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One));
5435       Expr *RangeRoundUp = AssertSuccess(
5436           Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne));
5437       Dist = AssertSuccess(
5438           Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor));
5439 
5440       // If there is not at least one iteration, the range contains garbage. Fix
5441       // to zero in this case.
5442       Dist = AssertSuccess(
5443           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5444     }
5445 
5446     // Assign the result to the out-parameter.
5447     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5448         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5449     BodyStmts.push_back(ResultAssign);
5450 
5451     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5452   }
5453 
5454   return cast<CapturedStmt>(
5455       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5456 }
5457 
5458 /// Create a closure that computes the loop variable from the logical iteration
5459 /// number.
5460 ///
5461 /// \param Actions   The Sema object.
5462 /// \param LoopVarTy Type for the loop variable used for result value.
5463 /// \param LogicalTy Type for the logical iteration number.
5464 /// \param StartExpr Value of the loop counter at the first iteration.
5465 /// \param Step      Amount of increment after each iteration.
5466 /// \param Deref     Whether the loop variable is a dereference of the loop
5467 /// counter variable.
5468 ///
5469 /// \return Closure (CapturedStmt) of the loop value calculation.
5470 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5471                                       QualType LogicalTy,
5472                                       DeclRefExpr *StartExpr, Expr *Step,
5473                                       bool Deref) {
5474   ASTContext &Ctx = Actions.getASTContext();
5475 
5476   // Pass the result as an out-parameter. Passing as return value would require
5477   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5478   // invoke a copy constructor.
5479   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5480   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5481                                           {"Logical", LogicalTy},
5482                                           {StringRef(), QualType()}};
5483   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5484 
5485   // Capture the initial iterator which represents the LoopVar value at the
5486   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5487   // it in every iteration, capture it by value before it is modified.
5488   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5489   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5490                                             Sema::TryCapture_ExplicitByVal, {});
5491   (void)Invalid;
5492   assert(!Invalid && "Expecting capture-by-value to work.");
5493 
5494   Expr *Body;
5495   {
5496     Sema::CompoundScopeRAII CompoundScope(Actions);
5497     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5498 
5499     ImplicitParamDecl *TargetParam = CS->getParam(0);
5500     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5501         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5502     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5503     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5504         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5505 
5506     // Capture the Start expression.
5507     CaptureVars Recap(Actions);
5508     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5509     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5510 
5511     Expr *Skip = AssertSuccess(
5512         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5513     // TODO: Explicitly cast to the iterator's difference_type instead of
5514     // relying on implicit conversion.
5515     Expr *Advanced =
5516         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5517 
5518     if (Deref) {
5519       // For range-based for-loops convert the loop counter value to a concrete
5520       // loop variable value by dereferencing the iterator.
5521       Advanced =
5522           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5523     }
5524 
5525     // Assign the result to the output parameter.
5526     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5527                                             BO_Assign, TargetRef, Advanced));
5528   }
5529   return cast<CapturedStmt>(
5530       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5531 }
5532 
5533 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5534   ASTContext &Ctx = getASTContext();
5535 
5536   // Extract the common elements of ForStmt and CXXForRangeStmt:
5537   // Loop variable, repeat condition, increment
5538   Expr *Cond, *Inc;
5539   VarDecl *LIVDecl, *LUVDecl;
5540   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5541     Stmt *Init = For->getInit();
5542     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5543       // For statement declares loop variable.
5544       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5545     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5546       // For statement reuses variable.
5547       assert(LCAssign->getOpcode() == BO_Assign &&
5548              "init part must be a loop variable assignment");
5549       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5550       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5551     } else
5552       llvm_unreachable("Cannot determine loop variable");
5553     LUVDecl = LIVDecl;
5554 
5555     Cond = For->getCond();
5556     Inc = For->getInc();
5557   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5558     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5559     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5560     LUVDecl = RangeFor->getLoopVariable();
5561 
5562     Cond = RangeFor->getCond();
5563     Inc = RangeFor->getInc();
5564   } else
5565     llvm_unreachable("unhandled kind of loop");
5566 
5567   QualType CounterTy = LIVDecl->getType();
5568   QualType LVTy = LUVDecl->getType();
5569 
5570   // Analyze the loop condition.
5571   Expr *LHS, *RHS;
5572   BinaryOperator::Opcode CondRel;
5573   Cond = Cond->IgnoreImplicit();
5574   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5575     LHS = CondBinExpr->getLHS();
5576     RHS = CondBinExpr->getRHS();
5577     CondRel = CondBinExpr->getOpcode();
5578   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5579     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5580     LHS = CondCXXOp->getArg(0);
5581     RHS = CondCXXOp->getArg(1);
5582     switch (CondCXXOp->getOperator()) {
5583     case OO_ExclaimEqual:
5584       CondRel = BO_NE;
5585       break;
5586     case OO_Less:
5587       CondRel = BO_LT;
5588       break;
5589     case OO_LessEqual:
5590       CondRel = BO_LE;
5591       break;
5592     case OO_Greater:
5593       CondRel = BO_GT;
5594       break;
5595     case OO_GreaterEqual:
5596       CondRel = BO_GE;
5597       break;
5598     default:
5599       llvm_unreachable("unexpected iterator operator");
5600     }
5601   } else
5602     llvm_unreachable("unexpected loop condition");
5603 
5604   // Normalize such that the loop counter is on the LHS.
5605   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5606       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5607     std::swap(LHS, RHS);
5608     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5609   }
5610   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5611 
5612   // Decide the bit width for the logical iteration counter. By default use the
5613   // unsigned ptrdiff_t integer size (for iterators and pointers).
5614   // TODO: For iterators, use iterator::difference_type,
5615   // std::iterator_traits<>::difference_type or decltype(it - end).
5616   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5617   if (CounterTy->isIntegerType()) {
5618     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5619     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5620   }
5621 
5622   // Analyze the loop increment.
5623   Expr *Step;
5624   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5625     int Direction;
5626     switch (IncUn->getOpcode()) {
5627     case UO_PreInc:
5628     case UO_PostInc:
5629       Direction = 1;
5630       break;
5631     case UO_PreDec:
5632     case UO_PostDec:
5633       Direction = -1;
5634       break;
5635     default:
5636       llvm_unreachable("unhandled unary increment operator");
5637     }
5638     Step = IntegerLiteral::Create(
5639         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5640   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5641     if (IncBin->getOpcode() == BO_AddAssign) {
5642       Step = IncBin->getRHS();
5643     } else if (IncBin->getOpcode() == BO_SubAssign) {
5644       Step =
5645           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5646     } else
5647       llvm_unreachable("unhandled binary increment operator");
5648   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5649     switch (CondCXXOp->getOperator()) {
5650     case OO_PlusPlus:
5651       Step = IntegerLiteral::Create(
5652           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5653       break;
5654     case OO_MinusMinus:
5655       Step = IntegerLiteral::Create(
5656           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5657       break;
5658     case OO_PlusEqual:
5659       Step = CondCXXOp->getArg(1);
5660       break;
5661     case OO_MinusEqual:
5662       Step = AssertSuccess(
5663           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5664       break;
5665     default:
5666       llvm_unreachable("unhandled overloaded increment operator");
5667     }
5668   } else
5669     llvm_unreachable("unknown increment expression");
5670 
5671   CapturedStmt *DistanceFunc =
5672       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5673   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5674       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5675   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5676                                         {}, nullptr, nullptr, {}, nullptr);
5677   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5678                                   LoopVarFunc, LVRef);
5679 }
5680 
5681 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
5682   // Handle a literal loop.
5683   if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
5684     return ActOnOpenMPCanonicalLoop(AStmt);
5685 
5686   // If not a literal loop, it must be the result of a loop transformation.
5687   OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
5688   assert(
5689       isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
5690       "Loop transformation directive expected");
5691   return LoopTransform;
5692 }
5693 
5694 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5695                                             CXXScopeSpec &MapperIdScopeSpec,
5696                                             const DeclarationNameInfo &MapperId,
5697                                             QualType Type,
5698                                             Expr *UnresolvedMapper);
5699 
5700 /// Perform DFS through the structure/class data members trying to find
5701 /// member(s) with user-defined 'default' mapper and generate implicit map
5702 /// clauses for such members with the found 'default' mapper.
5703 static void
5704 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5705                                       SmallVectorImpl<OMPClause *> &Clauses) {
5706   // Check for the deault mapper for data members.
5707   if (S.getLangOpts().OpenMP < 50)
5708     return;
5709   SmallVector<OMPClause *, 4> ImplicitMaps;
5710   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5711     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5712     if (!C)
5713       continue;
5714     SmallVector<Expr *, 4> SubExprs;
5715     auto *MI = C->mapperlist_begin();
5716     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5717          ++I, ++MI) {
5718       // Expression is mapped using mapper - skip it.
5719       if (*MI)
5720         continue;
5721       Expr *E = *I;
5722       // Expression is dependent - skip it, build the mapper when it gets
5723       // instantiated.
5724       if (E->isTypeDependent() || E->isValueDependent() ||
5725           E->containsUnexpandedParameterPack())
5726         continue;
5727       // Array section - need to check for the mapping of the array section
5728       // element.
5729       QualType CanonType = E->getType().getCanonicalType();
5730       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5731         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5732         QualType BaseType =
5733             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5734         QualType ElemType;
5735         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5736           ElemType = ATy->getElementType();
5737         else
5738           ElemType = BaseType->getPointeeType();
5739         CanonType = ElemType;
5740       }
5741 
5742       // DFS over data members in structures/classes.
5743       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5744           1, {CanonType, nullptr});
5745       llvm::DenseMap<const Type *, Expr *> Visited;
5746       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5747           1, {nullptr, 1});
5748       while (!Types.empty()) {
5749         QualType BaseType;
5750         FieldDecl *CurFD;
5751         std::tie(BaseType, CurFD) = Types.pop_back_val();
5752         while (ParentChain.back().second == 0)
5753           ParentChain.pop_back();
5754         --ParentChain.back().second;
5755         if (BaseType.isNull())
5756           continue;
5757         // Only structs/classes are allowed to have mappers.
5758         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5759         if (!RD)
5760           continue;
5761         auto It = Visited.find(BaseType.getTypePtr());
5762         if (It == Visited.end()) {
5763           // Try to find the associated user-defined mapper.
5764           CXXScopeSpec MapperIdScopeSpec;
5765           DeclarationNameInfo DefaultMapperId;
5766           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5767               &S.Context.Idents.get("default")));
5768           DefaultMapperId.setLoc(E->getExprLoc());
5769           ExprResult ER = buildUserDefinedMapperRef(
5770               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5771               BaseType, /*UnresolvedMapper=*/nullptr);
5772           if (ER.isInvalid())
5773             continue;
5774           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5775         }
5776         // Found default mapper.
5777         if (It->second) {
5778           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5779                                                      VK_LValue, OK_Ordinary, E);
5780           OE->setIsUnique(/*V=*/true);
5781           Expr *BaseExpr = OE;
5782           for (const auto &P : ParentChain) {
5783             if (P.first) {
5784               BaseExpr = S.BuildMemberExpr(
5785                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5786                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5787                   DeclAccessPair::make(P.first, P.first->getAccess()),
5788                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5789                   P.first->getType(), VK_LValue, OK_Ordinary);
5790               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5791             }
5792           }
5793           if (CurFD)
5794             BaseExpr = S.BuildMemberExpr(
5795                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5796                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5797                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5798                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5799                 CurFD->getType(), VK_LValue, OK_Ordinary);
5800           SubExprs.push_back(BaseExpr);
5801           continue;
5802         }
5803         // Check for the "default" mapper for data members.
5804         bool FirstIter = true;
5805         for (FieldDecl *FD : RD->fields()) {
5806           if (!FD)
5807             continue;
5808           QualType FieldTy = FD->getType();
5809           if (FieldTy.isNull() ||
5810               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5811             continue;
5812           if (FirstIter) {
5813             FirstIter = false;
5814             ParentChain.emplace_back(CurFD, 1);
5815           } else {
5816             ++ParentChain.back().second;
5817           }
5818           Types.emplace_back(FieldTy, FD);
5819         }
5820       }
5821     }
5822     if (SubExprs.empty())
5823       continue;
5824     CXXScopeSpec MapperIdScopeSpec;
5825     DeclarationNameInfo MapperId;
5826     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5827             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5828             MapperIdScopeSpec, MapperId, C->getMapType(),
5829             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5830             SubExprs, OMPVarListLocTy()))
5831       Clauses.push_back(NewClause);
5832   }
5833 }
5834 
5835 StmtResult Sema::ActOnOpenMPExecutableDirective(
5836     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5837     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5838     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5839   StmtResult Res = StmtError();
5840   OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
5841   if (const OMPBindClause *BC =
5842           OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
5843     BindKind = BC->getBindKind();
5844   // First check CancelRegion which is then used in checkNestingOfRegions.
5845   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5846       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5847                             BindKind, StartLoc))
5848     return StmtError();
5849 
5850   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5851   VarsWithInheritedDSAType VarsWithInheritedDSA;
5852   bool ErrorFound = false;
5853   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5854   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5855       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5856       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5857     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5858 
5859     // Check default data sharing attributes for referenced variables.
5860     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5861     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5862     Stmt *S = AStmt;
5863     while (--ThisCaptureLevel >= 0)
5864       S = cast<CapturedStmt>(S)->getCapturedStmt();
5865     DSAChecker.Visit(S);
5866     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5867         !isOpenMPTaskingDirective(Kind)) {
5868       // Visit subcaptures to generate implicit clauses for captured vars.
5869       auto *CS = cast<CapturedStmt>(AStmt);
5870       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5871       getOpenMPCaptureRegions(CaptureRegions, Kind);
5872       // Ignore outer tasking regions for target directives.
5873       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5874         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5875       DSAChecker.visitSubCaptures(CS);
5876     }
5877     if (DSAChecker.isErrorFound())
5878       return StmtError();
5879     // Generate list of implicitly defined firstprivate variables.
5880     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5881 
5882     SmallVector<Expr *, 4> ImplicitFirstprivates(
5883         DSAChecker.getImplicitFirstprivate().begin(),
5884         DSAChecker.getImplicitFirstprivate().end());
5885     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5886     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5887     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5888         ImplicitMapModifiers[DefaultmapKindNum];
5889     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5890         ImplicitMapModifiersLoc[DefaultmapKindNum];
5891     // Get the original location of present modifier from Defaultmap clause.
5892     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5893     for (OMPClause *C : Clauses) {
5894       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5895         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5896           PresentModifierLocs[DMC->getDefaultmapKind()] =
5897               DMC->getDefaultmapModifierLoc();
5898     }
5899     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5900       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5901       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5902         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5903             Kind, static_cast<OpenMPMapClauseKind>(I));
5904         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5905       }
5906       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5907           DSAChecker.getImplicitMapModifier(Kind);
5908       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5909                                       ImplicitModifier.end());
5910       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5911                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5912     }
5913     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5914     for (OMPClause *C : Clauses) {
5915       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5916         for (Expr *E : IRC->taskgroup_descriptors())
5917           if (E)
5918             ImplicitFirstprivates.emplace_back(E);
5919       }
5920       // OpenMP 5.0, 2.10.1 task Construct
5921       // [detach clause]... The event-handle will be considered as if it was
5922       // specified on a firstprivate clause.
5923       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5924         ImplicitFirstprivates.push_back(DC->getEventHandler());
5925     }
5926     if (!ImplicitFirstprivates.empty()) {
5927       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5928               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5929               SourceLocation())) {
5930         ClausesWithImplicit.push_back(Implicit);
5931         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5932                      ImplicitFirstprivates.size();
5933       } else {
5934         ErrorFound = true;
5935       }
5936     }
5937     // OpenMP 5.0 [2.19.7]
5938     // If a list item appears in a reduction, lastprivate or linear
5939     // clause on a combined target construct then it is treated as
5940     // if it also appears in a map clause with a map-type of tofrom
5941     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5942         isOpenMPTargetExecutionDirective(Kind)) {
5943       SmallVector<Expr *, 4> ImplicitExprs;
5944       for (OMPClause *C : Clauses) {
5945         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5946           for (Expr *E : RC->varlists())
5947             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5948               ImplicitExprs.emplace_back(E);
5949       }
5950       if (!ImplicitExprs.empty()) {
5951         ArrayRef<Expr *> Exprs = ImplicitExprs;
5952         CXXScopeSpec MapperIdScopeSpec;
5953         DeclarationNameInfo MapperId;
5954         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5955                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
5956                 MapperId, OMPC_MAP_tofrom,
5957                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5958                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
5959           ClausesWithImplicit.emplace_back(Implicit);
5960       }
5961     }
5962     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5963       int ClauseKindCnt = -1;
5964       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5965         ++ClauseKindCnt;
5966         if (ImplicitMap.empty())
5967           continue;
5968         CXXScopeSpec MapperIdScopeSpec;
5969         DeclarationNameInfo MapperId;
5970         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5971         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5972                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5973                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5974                 SourceLocation(), SourceLocation(), ImplicitMap,
5975                 OMPVarListLocTy())) {
5976           ClausesWithImplicit.emplace_back(Implicit);
5977           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5978                         ImplicitMap.size();
5979         } else {
5980           ErrorFound = true;
5981         }
5982       }
5983     }
5984     // Build expressions for implicit maps of data members with 'default'
5985     // mappers.
5986     if (LangOpts.OpenMP >= 50)
5987       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5988                                             ClausesWithImplicit);
5989   }
5990 
5991   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5992   switch (Kind) {
5993   case OMPD_parallel:
5994     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5995                                        EndLoc);
5996     AllowedNameModifiers.push_back(OMPD_parallel);
5997     break;
5998   case OMPD_simd:
5999     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
6000                                    VarsWithInheritedDSA);
6001     if (LangOpts.OpenMP >= 50)
6002       AllowedNameModifiers.push_back(OMPD_simd);
6003     break;
6004   case OMPD_tile:
6005     Res =
6006         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6007     break;
6008   case OMPD_unroll:
6009     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
6010                                      EndLoc);
6011     break;
6012   case OMPD_for:
6013     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
6014                                   VarsWithInheritedDSA);
6015     break;
6016   case OMPD_for_simd:
6017     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6018                                       EndLoc, VarsWithInheritedDSA);
6019     if (LangOpts.OpenMP >= 50)
6020       AllowedNameModifiers.push_back(OMPD_simd);
6021     break;
6022   case OMPD_sections:
6023     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
6024                                        EndLoc);
6025     break;
6026   case OMPD_section:
6027     assert(ClausesWithImplicit.empty() &&
6028            "No clauses are allowed for 'omp section' directive");
6029     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
6030     break;
6031   case OMPD_single:
6032     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
6033                                      EndLoc);
6034     break;
6035   case OMPD_master:
6036     assert(ClausesWithImplicit.empty() &&
6037            "No clauses are allowed for 'omp master' directive");
6038     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
6039     break;
6040   case OMPD_masked:
6041     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
6042                                      EndLoc);
6043     break;
6044   case OMPD_critical:
6045     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
6046                                        StartLoc, EndLoc);
6047     break;
6048   case OMPD_parallel_for:
6049     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
6050                                           EndLoc, VarsWithInheritedDSA);
6051     AllowedNameModifiers.push_back(OMPD_parallel);
6052     break;
6053   case OMPD_parallel_for_simd:
6054     Res = ActOnOpenMPParallelForSimdDirective(
6055         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6056     AllowedNameModifiers.push_back(OMPD_parallel);
6057     if (LangOpts.OpenMP >= 50)
6058       AllowedNameModifiers.push_back(OMPD_simd);
6059     break;
6060   case OMPD_parallel_master:
6061     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
6062                                              StartLoc, EndLoc);
6063     AllowedNameModifiers.push_back(OMPD_parallel);
6064     break;
6065   case OMPD_parallel_sections:
6066     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
6067                                                StartLoc, EndLoc);
6068     AllowedNameModifiers.push_back(OMPD_parallel);
6069     break;
6070   case OMPD_task:
6071     Res =
6072         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6073     AllowedNameModifiers.push_back(OMPD_task);
6074     break;
6075   case OMPD_taskyield:
6076     assert(ClausesWithImplicit.empty() &&
6077            "No clauses are allowed for 'omp taskyield' directive");
6078     assert(AStmt == nullptr &&
6079            "No associated statement allowed for 'omp taskyield' directive");
6080     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
6081     break;
6082   case OMPD_barrier:
6083     assert(ClausesWithImplicit.empty() &&
6084            "No clauses are allowed for 'omp barrier' directive");
6085     assert(AStmt == nullptr &&
6086            "No associated statement allowed for 'omp barrier' directive");
6087     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
6088     break;
6089   case OMPD_taskwait:
6090     assert(AStmt == nullptr &&
6091            "No associated statement allowed for 'omp taskwait' directive");
6092     Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
6093     break;
6094   case OMPD_taskgroup:
6095     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
6096                                         EndLoc);
6097     break;
6098   case OMPD_flush:
6099     assert(AStmt == nullptr &&
6100            "No associated statement allowed for 'omp flush' directive");
6101     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
6102     break;
6103   case OMPD_depobj:
6104     assert(AStmt == nullptr &&
6105            "No associated statement allowed for 'omp depobj' directive");
6106     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
6107     break;
6108   case OMPD_scan:
6109     assert(AStmt == nullptr &&
6110            "No associated statement allowed for 'omp scan' directive");
6111     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
6112     break;
6113   case OMPD_ordered:
6114     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
6115                                       EndLoc);
6116     break;
6117   case OMPD_atomic:
6118     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
6119                                      EndLoc);
6120     break;
6121   case OMPD_teams:
6122     Res =
6123         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6124     break;
6125   case OMPD_target:
6126     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6127                                      EndLoc);
6128     AllowedNameModifiers.push_back(OMPD_target);
6129     break;
6130   case OMPD_target_parallel:
6131     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6132                                              StartLoc, EndLoc);
6133     AllowedNameModifiers.push_back(OMPD_target);
6134     AllowedNameModifiers.push_back(OMPD_parallel);
6135     break;
6136   case OMPD_target_parallel_for:
6137     Res = ActOnOpenMPTargetParallelForDirective(
6138         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6139     AllowedNameModifiers.push_back(OMPD_target);
6140     AllowedNameModifiers.push_back(OMPD_parallel);
6141     break;
6142   case OMPD_cancellation_point:
6143     assert(ClausesWithImplicit.empty() &&
6144            "No clauses are allowed for 'omp cancellation point' directive");
6145     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6146                                "cancellation point' directive");
6147     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6148     break;
6149   case OMPD_cancel:
6150     assert(AStmt == nullptr &&
6151            "No associated statement allowed for 'omp cancel' directive");
6152     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6153                                      CancelRegion);
6154     AllowedNameModifiers.push_back(OMPD_cancel);
6155     break;
6156   case OMPD_target_data:
6157     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6158                                          EndLoc);
6159     AllowedNameModifiers.push_back(OMPD_target_data);
6160     break;
6161   case OMPD_target_enter_data:
6162     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6163                                               EndLoc, AStmt);
6164     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6165     break;
6166   case OMPD_target_exit_data:
6167     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6168                                              EndLoc, AStmt);
6169     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6170     break;
6171   case OMPD_taskloop:
6172     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6173                                        EndLoc, VarsWithInheritedDSA);
6174     AllowedNameModifiers.push_back(OMPD_taskloop);
6175     break;
6176   case OMPD_taskloop_simd:
6177     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6178                                            EndLoc, VarsWithInheritedDSA);
6179     AllowedNameModifiers.push_back(OMPD_taskloop);
6180     if (LangOpts.OpenMP >= 50)
6181       AllowedNameModifiers.push_back(OMPD_simd);
6182     break;
6183   case OMPD_master_taskloop:
6184     Res = ActOnOpenMPMasterTaskLoopDirective(
6185         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6186     AllowedNameModifiers.push_back(OMPD_taskloop);
6187     break;
6188   case OMPD_master_taskloop_simd:
6189     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6190         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6191     AllowedNameModifiers.push_back(OMPD_taskloop);
6192     if (LangOpts.OpenMP >= 50)
6193       AllowedNameModifiers.push_back(OMPD_simd);
6194     break;
6195   case OMPD_parallel_master_taskloop:
6196     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6197         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6198     AllowedNameModifiers.push_back(OMPD_taskloop);
6199     AllowedNameModifiers.push_back(OMPD_parallel);
6200     break;
6201   case OMPD_parallel_master_taskloop_simd:
6202     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6203         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6204     AllowedNameModifiers.push_back(OMPD_taskloop);
6205     AllowedNameModifiers.push_back(OMPD_parallel);
6206     if (LangOpts.OpenMP >= 50)
6207       AllowedNameModifiers.push_back(OMPD_simd);
6208     break;
6209   case OMPD_distribute:
6210     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6211                                          EndLoc, VarsWithInheritedDSA);
6212     break;
6213   case OMPD_target_update:
6214     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6215                                            EndLoc, AStmt);
6216     AllowedNameModifiers.push_back(OMPD_target_update);
6217     break;
6218   case OMPD_distribute_parallel_for:
6219     Res = ActOnOpenMPDistributeParallelForDirective(
6220         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6221     AllowedNameModifiers.push_back(OMPD_parallel);
6222     break;
6223   case OMPD_distribute_parallel_for_simd:
6224     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6225         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6226     AllowedNameModifiers.push_back(OMPD_parallel);
6227     if (LangOpts.OpenMP >= 50)
6228       AllowedNameModifiers.push_back(OMPD_simd);
6229     break;
6230   case OMPD_distribute_simd:
6231     Res = ActOnOpenMPDistributeSimdDirective(
6232         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6233     if (LangOpts.OpenMP >= 50)
6234       AllowedNameModifiers.push_back(OMPD_simd);
6235     break;
6236   case OMPD_target_parallel_for_simd:
6237     Res = ActOnOpenMPTargetParallelForSimdDirective(
6238         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6239     AllowedNameModifiers.push_back(OMPD_target);
6240     AllowedNameModifiers.push_back(OMPD_parallel);
6241     if (LangOpts.OpenMP >= 50)
6242       AllowedNameModifiers.push_back(OMPD_simd);
6243     break;
6244   case OMPD_target_simd:
6245     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6246                                          EndLoc, VarsWithInheritedDSA);
6247     AllowedNameModifiers.push_back(OMPD_target);
6248     if (LangOpts.OpenMP >= 50)
6249       AllowedNameModifiers.push_back(OMPD_simd);
6250     break;
6251   case OMPD_teams_distribute:
6252     Res = ActOnOpenMPTeamsDistributeDirective(
6253         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6254     break;
6255   case OMPD_teams_distribute_simd:
6256     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6257         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6258     if (LangOpts.OpenMP >= 50)
6259       AllowedNameModifiers.push_back(OMPD_simd);
6260     break;
6261   case OMPD_teams_distribute_parallel_for_simd:
6262     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6263         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6264     AllowedNameModifiers.push_back(OMPD_parallel);
6265     if (LangOpts.OpenMP >= 50)
6266       AllowedNameModifiers.push_back(OMPD_simd);
6267     break;
6268   case OMPD_teams_distribute_parallel_for:
6269     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6270         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6271     AllowedNameModifiers.push_back(OMPD_parallel);
6272     break;
6273   case OMPD_target_teams:
6274     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6275                                           EndLoc);
6276     AllowedNameModifiers.push_back(OMPD_target);
6277     break;
6278   case OMPD_target_teams_distribute:
6279     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6280         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6281     AllowedNameModifiers.push_back(OMPD_target);
6282     break;
6283   case OMPD_target_teams_distribute_parallel_for:
6284     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6285         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6286     AllowedNameModifiers.push_back(OMPD_target);
6287     AllowedNameModifiers.push_back(OMPD_parallel);
6288     break;
6289   case OMPD_target_teams_distribute_parallel_for_simd:
6290     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6291         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6292     AllowedNameModifiers.push_back(OMPD_target);
6293     AllowedNameModifiers.push_back(OMPD_parallel);
6294     if (LangOpts.OpenMP >= 50)
6295       AllowedNameModifiers.push_back(OMPD_simd);
6296     break;
6297   case OMPD_target_teams_distribute_simd:
6298     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6299         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6300     AllowedNameModifiers.push_back(OMPD_target);
6301     if (LangOpts.OpenMP >= 50)
6302       AllowedNameModifiers.push_back(OMPD_simd);
6303     break;
6304   case OMPD_interop:
6305     assert(AStmt == nullptr &&
6306            "No associated statement allowed for 'omp interop' directive");
6307     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6308     break;
6309   case OMPD_dispatch:
6310     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6311                                        EndLoc);
6312     break;
6313   case OMPD_loop:
6314     Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6315                                           EndLoc, VarsWithInheritedDSA);
6316     break;
6317   case OMPD_teams_loop:
6318     Res = ActOnOpenMPTeamsGenericLoopDirective(
6319         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6320     break;
6321   case OMPD_target_teams_loop:
6322     Res = ActOnOpenMPTargetTeamsGenericLoopDirective(
6323         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6324     break;
6325   case OMPD_parallel_loop:
6326     Res = ActOnOpenMPParallelGenericLoopDirective(
6327         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6328     break;
6329   case OMPD_target_parallel_loop:
6330     Res = ActOnOpenMPTargetParallelGenericLoopDirective(
6331         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6332     break;
6333   case OMPD_declare_target:
6334   case OMPD_end_declare_target:
6335   case OMPD_threadprivate:
6336   case OMPD_allocate:
6337   case OMPD_declare_reduction:
6338   case OMPD_declare_mapper:
6339   case OMPD_declare_simd:
6340   case OMPD_requires:
6341   case OMPD_declare_variant:
6342   case OMPD_begin_declare_variant:
6343   case OMPD_end_declare_variant:
6344     llvm_unreachable("OpenMP Directive is not allowed");
6345   case OMPD_unknown:
6346   default:
6347     llvm_unreachable("Unknown OpenMP directive");
6348   }
6349 
6350   ErrorFound = Res.isInvalid() || ErrorFound;
6351 
6352   // Check variables in the clauses if default(none) or
6353   // default(firstprivate) was specified.
6354   if (DSAStack->getDefaultDSA() == DSA_none ||
6355       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6356     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6357     for (OMPClause *C : Clauses) {
6358       switch (C->getClauseKind()) {
6359       case OMPC_num_threads:
6360       case OMPC_dist_schedule:
6361         // Do not analyse if no parent teams directive.
6362         if (isOpenMPTeamsDirective(Kind))
6363           break;
6364         continue;
6365       case OMPC_if:
6366         if (isOpenMPTeamsDirective(Kind) &&
6367             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6368           break;
6369         if (isOpenMPParallelDirective(Kind) &&
6370             isOpenMPTaskLoopDirective(Kind) &&
6371             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6372           break;
6373         continue;
6374       case OMPC_schedule:
6375       case OMPC_detach:
6376         break;
6377       case OMPC_grainsize:
6378       case OMPC_num_tasks:
6379       case OMPC_final:
6380       case OMPC_priority:
6381       case OMPC_novariants:
6382       case OMPC_nocontext:
6383         // Do not analyze if no parent parallel directive.
6384         if (isOpenMPParallelDirective(Kind))
6385           break;
6386         continue;
6387       case OMPC_ordered:
6388       case OMPC_device:
6389       case OMPC_num_teams:
6390       case OMPC_thread_limit:
6391       case OMPC_hint:
6392       case OMPC_collapse:
6393       case OMPC_safelen:
6394       case OMPC_simdlen:
6395       case OMPC_sizes:
6396       case OMPC_default:
6397       case OMPC_proc_bind:
6398       case OMPC_private:
6399       case OMPC_firstprivate:
6400       case OMPC_lastprivate:
6401       case OMPC_shared:
6402       case OMPC_reduction:
6403       case OMPC_task_reduction:
6404       case OMPC_in_reduction:
6405       case OMPC_linear:
6406       case OMPC_aligned:
6407       case OMPC_copyin:
6408       case OMPC_copyprivate:
6409       case OMPC_nowait:
6410       case OMPC_untied:
6411       case OMPC_mergeable:
6412       case OMPC_allocate:
6413       case OMPC_read:
6414       case OMPC_write:
6415       case OMPC_update:
6416       case OMPC_capture:
6417       case OMPC_compare:
6418       case OMPC_seq_cst:
6419       case OMPC_acq_rel:
6420       case OMPC_acquire:
6421       case OMPC_release:
6422       case OMPC_relaxed:
6423       case OMPC_depend:
6424       case OMPC_threads:
6425       case OMPC_simd:
6426       case OMPC_map:
6427       case OMPC_nogroup:
6428       case OMPC_defaultmap:
6429       case OMPC_to:
6430       case OMPC_from:
6431       case OMPC_use_device_ptr:
6432       case OMPC_use_device_addr:
6433       case OMPC_is_device_ptr:
6434       case OMPC_nontemporal:
6435       case OMPC_order:
6436       case OMPC_destroy:
6437       case OMPC_inclusive:
6438       case OMPC_exclusive:
6439       case OMPC_uses_allocators:
6440       case OMPC_affinity:
6441       case OMPC_bind:
6442         continue;
6443       case OMPC_allocator:
6444       case OMPC_flush:
6445       case OMPC_depobj:
6446       case OMPC_threadprivate:
6447       case OMPC_uniform:
6448       case OMPC_unknown:
6449       case OMPC_unified_address:
6450       case OMPC_unified_shared_memory:
6451       case OMPC_reverse_offload:
6452       case OMPC_dynamic_allocators:
6453       case OMPC_atomic_default_mem_order:
6454       case OMPC_device_type:
6455       case OMPC_match:
6456       case OMPC_when:
6457       default:
6458         llvm_unreachable("Unexpected clause");
6459       }
6460       for (Stmt *CC : C->children()) {
6461         if (CC)
6462           DSAChecker.Visit(CC);
6463       }
6464     }
6465     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6466       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6467   }
6468   for (const auto &P : VarsWithInheritedDSA) {
6469     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6470       continue;
6471     ErrorFound = true;
6472     if (DSAStack->getDefaultDSA() == DSA_none ||
6473         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6474       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6475           << P.first << P.second->getSourceRange();
6476       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6477     } else if (getLangOpts().OpenMP >= 50) {
6478       Diag(P.second->getExprLoc(),
6479            diag::err_omp_defaultmap_no_attr_for_variable)
6480           << P.first << P.second->getSourceRange();
6481       Diag(DSAStack->getDefaultDSALocation(),
6482            diag::note_omp_defaultmap_attr_none);
6483     }
6484   }
6485 
6486   if (!AllowedNameModifiers.empty())
6487     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6488                  ErrorFound;
6489 
6490   if (ErrorFound)
6491     return StmtError();
6492 
6493   if (!CurContext->isDependentContext() &&
6494       isOpenMPTargetExecutionDirective(Kind) &&
6495       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6496         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6497         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6498         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6499     // Register target to DSA Stack.
6500     DSAStack->addTargetDirLocation(StartLoc);
6501   }
6502 
6503   return Res;
6504 }
6505 
6506 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6507     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6508     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6509     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6510     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6511   assert(Aligneds.size() == Alignments.size());
6512   assert(Linears.size() == LinModifiers.size());
6513   assert(Linears.size() == Steps.size());
6514   if (!DG || DG.get().isNull())
6515     return DeclGroupPtrTy();
6516 
6517   const int SimdId = 0;
6518   if (!DG.get().isSingleDecl()) {
6519     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6520         << SimdId;
6521     return DG;
6522   }
6523   Decl *ADecl = DG.get().getSingleDecl();
6524   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6525     ADecl = FTD->getTemplatedDecl();
6526 
6527   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6528   if (!FD) {
6529     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6530     return DeclGroupPtrTy();
6531   }
6532 
6533   // OpenMP [2.8.2, declare simd construct, Description]
6534   // The parameter of the simdlen clause must be a constant positive integer
6535   // expression.
6536   ExprResult SL;
6537   if (Simdlen)
6538     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6539   // OpenMP [2.8.2, declare simd construct, Description]
6540   // The special this pointer can be used as if was one of the arguments to the
6541   // function in any of the linear, aligned, or uniform clauses.
6542   // The uniform clause declares one or more arguments to have an invariant
6543   // value for all concurrent invocations of the function in the execution of a
6544   // single SIMD loop.
6545   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6546   const Expr *UniformedLinearThis = nullptr;
6547   for (const Expr *E : Uniforms) {
6548     E = E->IgnoreParenImpCasts();
6549     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6550       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6551         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6552             FD->getParamDecl(PVD->getFunctionScopeIndex())
6553                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6554           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6555           continue;
6556         }
6557     if (isa<CXXThisExpr>(E)) {
6558       UniformedLinearThis = E;
6559       continue;
6560     }
6561     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6562         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6563   }
6564   // OpenMP [2.8.2, declare simd construct, Description]
6565   // The aligned clause declares that the object to which each list item points
6566   // is aligned to the number of bytes expressed in the optional parameter of
6567   // the aligned clause.
6568   // The special this pointer can be used as if was one of the arguments to the
6569   // function in any of the linear, aligned, or uniform clauses.
6570   // The type of list items appearing in the aligned clause must be array,
6571   // pointer, reference to array, or reference to pointer.
6572   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6573   const Expr *AlignedThis = nullptr;
6574   for (const Expr *E : Aligneds) {
6575     E = E->IgnoreParenImpCasts();
6576     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6577       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6578         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6579         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6580             FD->getParamDecl(PVD->getFunctionScopeIndex())
6581                     ->getCanonicalDecl() == CanonPVD) {
6582           // OpenMP  [2.8.1, simd construct, Restrictions]
6583           // A list-item cannot appear in more than one aligned clause.
6584           if (AlignedArgs.count(CanonPVD) > 0) {
6585             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6586                 << 1 << getOpenMPClauseName(OMPC_aligned)
6587                 << E->getSourceRange();
6588             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6589                  diag::note_omp_explicit_dsa)
6590                 << getOpenMPClauseName(OMPC_aligned);
6591             continue;
6592           }
6593           AlignedArgs[CanonPVD] = E;
6594           QualType QTy = PVD->getType()
6595                              .getNonReferenceType()
6596                              .getUnqualifiedType()
6597                              .getCanonicalType();
6598           const Type *Ty = QTy.getTypePtrOrNull();
6599           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6600             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6601                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6602             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6603           }
6604           continue;
6605         }
6606       }
6607     if (isa<CXXThisExpr>(E)) {
6608       if (AlignedThis) {
6609         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6610             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6611         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6612             << getOpenMPClauseName(OMPC_aligned);
6613       }
6614       AlignedThis = E;
6615       continue;
6616     }
6617     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6618         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6619   }
6620   // The optional parameter of the aligned clause, alignment, must be a constant
6621   // positive integer expression. If no optional parameter is specified,
6622   // implementation-defined default alignments for SIMD instructions on the
6623   // target platforms are assumed.
6624   SmallVector<const Expr *, 4> NewAligns;
6625   for (Expr *E : Alignments) {
6626     ExprResult Align;
6627     if (E)
6628       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6629     NewAligns.push_back(Align.get());
6630   }
6631   // OpenMP [2.8.2, declare simd construct, Description]
6632   // The linear clause declares one or more list items to be private to a SIMD
6633   // lane and to have a linear relationship with respect to the iteration space
6634   // of a loop.
6635   // The special this pointer can be used as if was one of the arguments to the
6636   // function in any of the linear, aligned, or uniform clauses.
6637   // When a linear-step expression is specified in a linear clause it must be
6638   // either a constant integer expression or an integer-typed parameter that is
6639   // specified in a uniform clause on the directive.
6640   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6641   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6642   auto MI = LinModifiers.begin();
6643   for (const Expr *E : Linears) {
6644     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6645     ++MI;
6646     E = E->IgnoreParenImpCasts();
6647     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6648       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6649         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6650         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6651             FD->getParamDecl(PVD->getFunctionScopeIndex())
6652                     ->getCanonicalDecl() == CanonPVD) {
6653           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6654           // A list-item cannot appear in more than one linear clause.
6655           if (LinearArgs.count(CanonPVD) > 0) {
6656             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6657                 << getOpenMPClauseName(OMPC_linear)
6658                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6659             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6660                  diag::note_omp_explicit_dsa)
6661                 << getOpenMPClauseName(OMPC_linear);
6662             continue;
6663           }
6664           // Each argument can appear in at most one uniform or linear clause.
6665           if (UniformedArgs.count(CanonPVD) > 0) {
6666             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6667                 << getOpenMPClauseName(OMPC_linear)
6668                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6669             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6670                  diag::note_omp_explicit_dsa)
6671                 << getOpenMPClauseName(OMPC_uniform);
6672             continue;
6673           }
6674           LinearArgs[CanonPVD] = E;
6675           if (E->isValueDependent() || E->isTypeDependent() ||
6676               E->isInstantiationDependent() ||
6677               E->containsUnexpandedParameterPack())
6678             continue;
6679           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6680                                       PVD->getOriginalType(),
6681                                       /*IsDeclareSimd=*/true);
6682           continue;
6683         }
6684       }
6685     if (isa<CXXThisExpr>(E)) {
6686       if (UniformedLinearThis) {
6687         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6688             << getOpenMPClauseName(OMPC_linear)
6689             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6690             << E->getSourceRange();
6691         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6692             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6693                                                    : OMPC_linear);
6694         continue;
6695       }
6696       UniformedLinearThis = E;
6697       if (E->isValueDependent() || E->isTypeDependent() ||
6698           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6699         continue;
6700       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6701                                   E->getType(), /*IsDeclareSimd=*/true);
6702       continue;
6703     }
6704     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6705         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6706   }
6707   Expr *Step = nullptr;
6708   Expr *NewStep = nullptr;
6709   SmallVector<Expr *, 4> NewSteps;
6710   for (Expr *E : Steps) {
6711     // Skip the same step expression, it was checked already.
6712     if (Step == E || !E) {
6713       NewSteps.push_back(E ? NewStep : nullptr);
6714       continue;
6715     }
6716     Step = E;
6717     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6718       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6719         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6720         if (UniformedArgs.count(CanonPVD) == 0) {
6721           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6722               << Step->getSourceRange();
6723         } else if (E->isValueDependent() || E->isTypeDependent() ||
6724                    E->isInstantiationDependent() ||
6725                    E->containsUnexpandedParameterPack() ||
6726                    CanonPVD->getType()->hasIntegerRepresentation()) {
6727           NewSteps.push_back(Step);
6728         } else {
6729           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6730               << Step->getSourceRange();
6731         }
6732         continue;
6733       }
6734     NewStep = Step;
6735     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6736         !Step->isInstantiationDependent() &&
6737         !Step->containsUnexpandedParameterPack()) {
6738       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6739                     .get();
6740       if (NewStep)
6741         NewStep =
6742             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6743     }
6744     NewSteps.push_back(NewStep);
6745   }
6746   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6747       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6748       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6749       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6750       const_cast<Expr **>(Linears.data()), Linears.size(),
6751       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6752       NewSteps.data(), NewSteps.size(), SR);
6753   ADecl->addAttr(NewAttr);
6754   return DG;
6755 }
6756 
6757 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6758                          QualType NewType) {
6759   assert(NewType->isFunctionProtoType() &&
6760          "Expected function type with prototype.");
6761   assert(FD->getType()->isFunctionNoProtoType() &&
6762          "Expected function with type with no prototype.");
6763   assert(FDWithProto->getType()->isFunctionProtoType() &&
6764          "Expected function with prototype.");
6765   // Synthesize parameters with the same types.
6766   FD->setType(NewType);
6767   SmallVector<ParmVarDecl *, 16> Params;
6768   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6769     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6770                                       SourceLocation(), nullptr, P->getType(),
6771                                       /*TInfo=*/nullptr, SC_None, nullptr);
6772     Param->setScopeInfo(0, Params.size());
6773     Param->setImplicit();
6774     Params.push_back(Param);
6775   }
6776 
6777   FD->setParams(Params);
6778 }
6779 
6780 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6781   if (D->isInvalidDecl())
6782     return;
6783   FunctionDecl *FD = nullptr;
6784   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6785     FD = UTemplDecl->getTemplatedDecl();
6786   else
6787     FD = cast<FunctionDecl>(D);
6788   assert(FD && "Expected a function declaration!");
6789 
6790   // If we are instantiating templates we do *not* apply scoped assumptions but
6791   // only global ones. We apply scoped assumption to the template definition
6792   // though.
6793   if (!inTemplateInstantiation()) {
6794     for (AssumptionAttr *AA : OMPAssumeScoped)
6795       FD->addAttr(AA);
6796   }
6797   for (AssumptionAttr *AA : OMPAssumeGlobal)
6798     FD->addAttr(AA);
6799 }
6800 
6801 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6802     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6803 
6804 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6805     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6806     SmallVectorImpl<FunctionDecl *> &Bases) {
6807   if (!D.getIdentifier())
6808     return;
6809 
6810   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6811 
6812   // Template specialization is an extension, check if we do it.
6813   bool IsTemplated = !TemplateParamLists.empty();
6814   if (IsTemplated &
6815       !DVScope.TI->isExtensionActive(
6816           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6817     return;
6818 
6819   IdentifierInfo *BaseII = D.getIdentifier();
6820   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6821                       LookupOrdinaryName);
6822   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6823 
6824   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6825   QualType FType = TInfo->getType();
6826 
6827   bool IsConstexpr =
6828       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6829   bool IsConsteval =
6830       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6831 
6832   for (auto *Candidate : Lookup) {
6833     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6834     FunctionDecl *UDecl = nullptr;
6835     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
6836       auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
6837       if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
6838         UDecl = FTD->getTemplatedDecl();
6839     } else if (!IsTemplated)
6840       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6841     if (!UDecl)
6842       continue;
6843 
6844     // Don't specialize constexpr/consteval functions with
6845     // non-constexpr/consteval functions.
6846     if (UDecl->isConstexpr() && !IsConstexpr)
6847       continue;
6848     if (UDecl->isConsteval() && !IsConsteval)
6849       continue;
6850 
6851     QualType UDeclTy = UDecl->getType();
6852     if (!UDeclTy->isDependentType()) {
6853       QualType NewType = Context.mergeFunctionTypes(
6854           FType, UDeclTy, /* OfBlockPointer */ false,
6855           /* Unqualified */ false, /* AllowCXX */ true);
6856       if (NewType.isNull())
6857         continue;
6858     }
6859 
6860     // Found a base!
6861     Bases.push_back(UDecl);
6862   }
6863 
6864   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6865       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6866   // If no base was found we create a declaration that we use as base.
6867   if (Bases.empty() && UseImplicitBase) {
6868     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6869     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6870     BaseD->setImplicit(true);
6871     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6872       Bases.push_back(BaseTemplD->getTemplatedDecl());
6873     else
6874       Bases.push_back(cast<FunctionDecl>(BaseD));
6875   }
6876 
6877   std::string MangledName;
6878   MangledName += D.getIdentifier()->getName();
6879   MangledName += getOpenMPVariantManglingSeparatorStr();
6880   MangledName += DVScope.NameSuffix;
6881   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6882 
6883   VariantII.setMangledOpenMPVariantName(true);
6884   D.SetIdentifier(&VariantII, D.getBeginLoc());
6885 }
6886 
6887 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6888     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6889   // Do not mark function as is used to prevent its emission if this is the
6890   // only place where it is used.
6891   EnterExpressionEvaluationContext Unevaluated(
6892       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6893 
6894   FunctionDecl *FD = nullptr;
6895   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6896     FD = UTemplDecl->getTemplatedDecl();
6897   else
6898     FD = cast<FunctionDecl>(D);
6899   auto *VariantFuncRef = DeclRefExpr::Create(
6900       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6901       /* RefersToEnclosingVariableOrCapture */ false,
6902       /* NameLoc */ FD->getLocation(), FD->getType(),
6903       ExprValueKind::VK_PRValue);
6904 
6905   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6906   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6907       Context, VariantFuncRef, DVScope.TI,
6908       /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
6909       /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
6910       /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
6911   for (FunctionDecl *BaseFD : Bases)
6912     BaseFD->addAttr(OMPDeclareVariantA);
6913 }
6914 
6915 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6916                                  SourceLocation LParenLoc,
6917                                  MultiExprArg ArgExprs,
6918                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6919   // The common case is a regular call we do not want to specialize at all. Try
6920   // to make that case fast by bailing early.
6921   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6922   if (!CE)
6923     return Call;
6924 
6925   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6926   if (!CalleeFnDecl)
6927     return Call;
6928 
6929   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6930     return Call;
6931 
6932   ASTContext &Context = getASTContext();
6933   std::function<void(StringRef)> DiagUnknownTrait = [this,
6934                                                      CE](StringRef ISATrait) {
6935     // TODO Track the selector locations in a way that is accessible here to
6936     // improve the diagnostic location.
6937     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6938         << ISATrait;
6939   };
6940   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6941                           getCurFunctionDecl(), DSAStack->getConstructTraits());
6942 
6943   QualType CalleeFnType = CalleeFnDecl->getType();
6944 
6945   SmallVector<Expr *, 4> Exprs;
6946   SmallVector<VariantMatchInfo, 4> VMIs;
6947   while (CalleeFnDecl) {
6948     for (OMPDeclareVariantAttr *A :
6949          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6950       Expr *VariantRef = A->getVariantFuncRef();
6951 
6952       VariantMatchInfo VMI;
6953       OMPTraitInfo &TI = A->getTraitInfo();
6954       TI.getAsVariantMatchInfo(Context, VMI);
6955       if (!isVariantApplicableInContext(VMI, OMPCtx,
6956                                         /* DeviceSetOnly */ false))
6957         continue;
6958 
6959       VMIs.push_back(VMI);
6960       Exprs.push_back(VariantRef);
6961     }
6962 
6963     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6964   }
6965 
6966   ExprResult NewCall;
6967   do {
6968     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6969     if (BestIdx < 0)
6970       return Call;
6971     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6972     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6973 
6974     {
6975       // Try to build a (member) call expression for the current best applicable
6976       // variant expression. We allow this to fail in which case we continue
6977       // with the next best variant expression. The fail case is part of the
6978       // implementation defined behavior in the OpenMP standard when it talks
6979       // about what differences in the function prototypes: "Any differences
6980       // that the specific OpenMP context requires in the prototype of the
6981       // variant from the base function prototype are implementation defined."
6982       // This wording is there to allow the specialized variant to have a
6983       // different type than the base function. This is intended and OK but if
6984       // we cannot create a call the difference is not in the "implementation
6985       // defined range" we allow.
6986       Sema::TentativeAnalysisScope Trap(*this);
6987 
6988       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6989         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6990         BestExpr = MemberExpr::CreateImplicit(
6991             Context, MemberCall->getImplicitObjectArgument(),
6992             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6993             MemberCall->getValueKind(), MemberCall->getObjectKind());
6994       }
6995       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6996                               ExecConfig);
6997       if (NewCall.isUsable()) {
6998         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6999           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
7000           QualType NewType = Context.mergeFunctionTypes(
7001               CalleeFnType, NewCalleeFnDecl->getType(),
7002               /* OfBlockPointer */ false,
7003               /* Unqualified */ false, /* AllowCXX */ true);
7004           if (!NewType.isNull())
7005             break;
7006           // Don't use the call if the function type was not compatible.
7007           NewCall = nullptr;
7008         }
7009       }
7010     }
7011 
7012     VMIs.erase(VMIs.begin() + BestIdx);
7013     Exprs.erase(Exprs.begin() + BestIdx);
7014   } while (!VMIs.empty());
7015 
7016   if (!NewCall.isUsable())
7017     return Call;
7018   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
7019 }
7020 
7021 Optional<std::pair<FunctionDecl *, Expr *>>
7022 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
7023                                         Expr *VariantRef, OMPTraitInfo &TI,
7024                                         unsigned NumAppendArgs,
7025                                         SourceRange SR) {
7026   if (!DG || DG.get().isNull())
7027     return None;
7028 
7029   const int VariantId = 1;
7030   // Must be applied only to single decl.
7031   if (!DG.get().isSingleDecl()) {
7032     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
7033         << VariantId << SR;
7034     return None;
7035   }
7036   Decl *ADecl = DG.get().getSingleDecl();
7037   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
7038     ADecl = FTD->getTemplatedDecl();
7039 
7040   // Decl must be a function.
7041   auto *FD = dyn_cast<FunctionDecl>(ADecl);
7042   if (!FD) {
7043     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
7044         << VariantId << SR;
7045     return None;
7046   }
7047 
7048   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
7049     // The 'target' attribute needs to be separately checked because it does
7050     // not always signify a multiversion function declaration.
7051     return FD->isMultiVersion() || FD->hasAttr<TargetAttr>();
7052   };
7053   // OpenMP is not compatible with multiversion function attributes.
7054   if (HasMultiVersionAttributes(FD)) {
7055     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
7056         << SR;
7057     return None;
7058   }
7059 
7060   // Allow #pragma omp declare variant only if the function is not used.
7061   if (FD->isUsed(false))
7062     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
7063         << FD->getLocation();
7064 
7065   // Check if the function was emitted already.
7066   const FunctionDecl *Definition;
7067   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
7068       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
7069     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
7070         << FD->getLocation();
7071 
7072   // The VariantRef must point to function.
7073   if (!VariantRef) {
7074     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
7075     return None;
7076   }
7077 
7078   auto ShouldDelayChecks = [](Expr *&E, bool) {
7079     return E && (E->isTypeDependent() || E->isValueDependent() ||
7080                  E->containsUnexpandedParameterPack() ||
7081                  E->isInstantiationDependent());
7082   };
7083   // Do not check templates, wait until instantiation.
7084   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
7085       TI.anyScoreOrCondition(ShouldDelayChecks))
7086     return std::make_pair(FD, VariantRef);
7087 
7088   // Deal with non-constant score and user condition expressions.
7089   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
7090                                                      bool IsScore) -> bool {
7091     if (!E || E->isIntegerConstantExpr(Context))
7092       return false;
7093 
7094     if (IsScore) {
7095       // We warn on non-constant scores and pretend they were not present.
7096       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
7097           << E;
7098       E = nullptr;
7099     } else {
7100       // We could replace a non-constant user condition with "false" but we
7101       // will soon need to handle these anyway for the dynamic version of
7102       // OpenMP context selectors.
7103       Diag(E->getExprLoc(),
7104            diag::err_omp_declare_variant_user_condition_not_constant)
7105           << E;
7106     }
7107     return true;
7108   };
7109   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
7110     return None;
7111 
7112   QualType AdjustedFnType = FD->getType();
7113   if (NumAppendArgs) {
7114     const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
7115     if (!PTy) {
7116       Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
7117           << SR;
7118       return None;
7119     }
7120     // Adjust the function type to account for an extra omp_interop_t for each
7121     // specified in the append_args clause.
7122     const TypeDecl *TD = nullptr;
7123     LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
7124                         SR.getBegin(), Sema::LookupOrdinaryName);
7125     if (LookupName(Result, getCurScope())) {
7126       NamedDecl *ND = Result.getFoundDecl();
7127       TD = dyn_cast_or_null<TypeDecl>(ND);
7128     }
7129     if (!TD) {
7130       Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
7131       return None;
7132     }
7133     QualType InteropType = Context.getTypeDeclType(TD);
7134     if (PTy->isVariadic()) {
7135       Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
7136       return None;
7137     }
7138     llvm::SmallVector<QualType, 8> Params;
7139     Params.append(PTy->param_type_begin(), PTy->param_type_end());
7140     Params.insert(Params.end(), NumAppendArgs, InteropType);
7141     AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
7142                                              PTy->getExtProtoInfo());
7143   }
7144 
7145   // Convert VariantRef expression to the type of the original function to
7146   // resolve possible conflicts.
7147   ExprResult VariantRefCast = VariantRef;
7148   if (LangOpts.CPlusPlus) {
7149     QualType FnPtrType;
7150     auto *Method = dyn_cast<CXXMethodDecl>(FD);
7151     if (Method && !Method->isStatic()) {
7152       const Type *ClassType =
7153           Context.getTypeDeclType(Method->getParent()).getTypePtr();
7154       FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
7155       ExprResult ER;
7156       {
7157         // Build adrr_of unary op to correctly handle type checks for member
7158         // functions.
7159         Sema::TentativeAnalysisScope Trap(*this);
7160         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
7161                                   VariantRef);
7162       }
7163       if (!ER.isUsable()) {
7164         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7165             << VariantId << VariantRef->getSourceRange();
7166         return None;
7167       }
7168       VariantRef = ER.get();
7169     } else {
7170       FnPtrType = Context.getPointerType(AdjustedFnType);
7171     }
7172     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
7173     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
7174       ImplicitConversionSequence ICS = TryImplicitConversion(
7175           VariantRef, FnPtrType.getUnqualifiedType(),
7176           /*SuppressUserConversions=*/false, AllowedExplicit::None,
7177           /*InOverloadResolution=*/false,
7178           /*CStyle=*/false,
7179           /*AllowObjCWritebackConversion=*/false);
7180       if (ICS.isFailure()) {
7181         Diag(VariantRef->getExprLoc(),
7182              diag::err_omp_declare_variant_incompat_types)
7183             << VariantRef->getType()
7184             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7185             << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
7186         return None;
7187       }
7188       VariantRefCast = PerformImplicitConversion(
7189           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7190       if (!VariantRefCast.isUsable())
7191         return None;
7192     }
7193     // Drop previously built artificial addr_of unary op for member functions.
7194     if (Method && !Method->isStatic()) {
7195       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7196       if (auto *UO = dyn_cast<UnaryOperator>(
7197               PossibleAddrOfVariantRef->IgnoreImplicit()))
7198         VariantRefCast = UO->getSubExpr();
7199     }
7200   }
7201 
7202   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7203   if (!ER.isUsable() ||
7204       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7205     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7206         << VariantId << VariantRef->getSourceRange();
7207     return None;
7208   }
7209 
7210   // The VariantRef must point to function.
7211   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7212   if (!DRE) {
7213     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7214         << VariantId << VariantRef->getSourceRange();
7215     return None;
7216   }
7217   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7218   if (!NewFD) {
7219     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7220         << VariantId << VariantRef->getSourceRange();
7221     return None;
7222   }
7223 
7224   if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) {
7225     Diag(VariantRef->getExprLoc(),
7226          diag::err_omp_declare_variant_same_base_function)
7227         << VariantRef->getSourceRange();
7228     return None;
7229   }
7230 
7231   // Check if function types are compatible in C.
7232   if (!LangOpts.CPlusPlus) {
7233     QualType NewType =
7234         Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
7235     if (NewType.isNull()) {
7236       Diag(VariantRef->getExprLoc(),
7237            diag::err_omp_declare_variant_incompat_types)
7238           << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
7239           << VariantRef->getSourceRange();
7240       return None;
7241     }
7242     if (NewType->isFunctionProtoType()) {
7243       if (FD->getType()->isFunctionNoProtoType())
7244         setPrototype(*this, FD, NewFD, NewType);
7245       else if (NewFD->getType()->isFunctionNoProtoType())
7246         setPrototype(*this, NewFD, FD, NewType);
7247     }
7248   }
7249 
7250   // Check if variant function is not marked with declare variant directive.
7251   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7252     Diag(VariantRef->getExprLoc(),
7253          diag::warn_omp_declare_variant_marked_as_declare_variant)
7254         << VariantRef->getSourceRange();
7255     SourceRange SR =
7256         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7257     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7258     return None;
7259   }
7260 
7261   enum DoesntSupport {
7262     VirtFuncs = 1,
7263     Constructors = 3,
7264     Destructors = 4,
7265     DeletedFuncs = 5,
7266     DefaultedFuncs = 6,
7267     ConstexprFuncs = 7,
7268     ConstevalFuncs = 8,
7269   };
7270   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7271     if (CXXFD->isVirtual()) {
7272       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7273           << VirtFuncs;
7274       return None;
7275     }
7276 
7277     if (isa<CXXConstructorDecl>(FD)) {
7278       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7279           << Constructors;
7280       return None;
7281     }
7282 
7283     if (isa<CXXDestructorDecl>(FD)) {
7284       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7285           << Destructors;
7286       return None;
7287     }
7288   }
7289 
7290   if (FD->isDeleted()) {
7291     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7292         << DeletedFuncs;
7293     return None;
7294   }
7295 
7296   if (FD->isDefaulted()) {
7297     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7298         << DefaultedFuncs;
7299     return None;
7300   }
7301 
7302   if (FD->isConstexpr()) {
7303     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7304         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7305     return None;
7306   }
7307 
7308   // Check general compatibility.
7309   if (areMultiversionVariantFunctionsCompatible(
7310           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7311           PartialDiagnosticAt(SourceLocation(),
7312                               PartialDiagnostic::NullDiagnostic()),
7313           PartialDiagnosticAt(
7314               VariantRef->getExprLoc(),
7315               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7316           PartialDiagnosticAt(VariantRef->getExprLoc(),
7317                               PDiag(diag::err_omp_declare_variant_diff)
7318                                   << FD->getLocation()),
7319           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7320           /*CLinkageMayDiffer=*/true))
7321     return None;
7322   return std::make_pair(FD, cast<Expr>(DRE));
7323 }
7324 
7325 void Sema::ActOnOpenMPDeclareVariantDirective(
7326     FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
7327     ArrayRef<Expr *> AdjustArgsNothing,
7328     ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
7329     ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
7330     SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
7331     SourceRange SR) {
7332 
7333   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7334   // An adjust_args clause or append_args clause can only be specified if the
7335   // dispatch selector of the construct selector set appears in the match
7336   // clause.
7337 
7338   SmallVector<Expr *, 8> AllAdjustArgs;
7339   llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
7340   llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
7341 
7342   if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
7343     VariantMatchInfo VMI;
7344     TI.getAsVariantMatchInfo(Context, VMI);
7345     if (!llvm::is_contained(
7346             VMI.ConstructTraits,
7347             llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
7348       if (!AllAdjustArgs.empty())
7349         Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7350             << getOpenMPClauseName(OMPC_adjust_args);
7351       if (!AppendArgs.empty())
7352         Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7353             << getOpenMPClauseName(OMPC_append_args);
7354       return;
7355     }
7356   }
7357 
7358   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7359   // Each argument can only appear in a single adjust_args clause for each
7360   // declare variant directive.
7361   llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
7362 
7363   for (Expr *E : AllAdjustArgs) {
7364     E = E->IgnoreParenImpCasts();
7365     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
7366       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7367         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7368         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7369             FD->getParamDecl(PVD->getFunctionScopeIndex())
7370                     ->getCanonicalDecl() == CanonPVD) {
7371           // It's a parameter of the function, check duplicates.
7372           if (!AdjustVars.insert(CanonPVD).second) {
7373             Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
7374                 << PVD;
7375             return;
7376           }
7377           continue;
7378         }
7379       }
7380     }
7381     // Anything that is not a function parameter is an error.
7382     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
7383     return;
7384   }
7385 
7386   auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
7387       Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
7388       AdjustArgsNothing.size(),
7389       const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
7390       AdjustArgsNeedDevicePtr.size(),
7391       const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
7392       AppendArgs.size(), SR);
7393   FD->addAttr(NewAttr);
7394 }
7395 
7396 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7397                                               Stmt *AStmt,
7398                                               SourceLocation StartLoc,
7399                                               SourceLocation EndLoc) {
7400   if (!AStmt)
7401     return StmtError();
7402 
7403   auto *CS = cast<CapturedStmt>(AStmt);
7404   // 1.2.2 OpenMP Language Terminology
7405   // Structured block - An executable statement with a single entry at the
7406   // top and a single exit at the bottom.
7407   // The point of exit cannot be a branch out of the structured block.
7408   // longjmp() and throw() must not violate the entry/exit criteria.
7409   CS->getCapturedDecl()->setNothrow();
7410 
7411   setFunctionHasBranchProtectedScope();
7412 
7413   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7414                                       DSAStack->getTaskgroupReductionRef(),
7415                                       DSAStack->isCancelRegion());
7416 }
7417 
7418 namespace {
7419 /// Iteration space of a single for loop.
7420 struct LoopIterationSpace final {
7421   /// True if the condition operator is the strict compare operator (<, > or
7422   /// !=).
7423   bool IsStrictCompare = false;
7424   /// Condition of the loop.
7425   Expr *PreCond = nullptr;
7426   /// This expression calculates the number of iterations in the loop.
7427   /// It is always possible to calculate it before starting the loop.
7428   Expr *NumIterations = nullptr;
7429   /// The loop counter variable.
7430   Expr *CounterVar = nullptr;
7431   /// Private loop counter variable.
7432   Expr *PrivateCounterVar = nullptr;
7433   /// This is initializer for the initial value of #CounterVar.
7434   Expr *CounterInit = nullptr;
7435   /// This is step for the #CounterVar used to generate its update:
7436   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7437   Expr *CounterStep = nullptr;
7438   /// Should step be subtracted?
7439   bool Subtract = false;
7440   /// Source range of the loop init.
7441   SourceRange InitSrcRange;
7442   /// Source range of the loop condition.
7443   SourceRange CondSrcRange;
7444   /// Source range of the loop increment.
7445   SourceRange IncSrcRange;
7446   /// Minimum value that can have the loop control variable. Used to support
7447   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7448   /// since only such variables can be used in non-loop invariant expressions.
7449   Expr *MinValue = nullptr;
7450   /// Maximum value that can have the loop control variable. Used to support
7451   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7452   /// since only such variables can be used in non-loop invariant expressions.
7453   Expr *MaxValue = nullptr;
7454   /// true, if the lower bound depends on the outer loop control var.
7455   bool IsNonRectangularLB = false;
7456   /// true, if the upper bound depends on the outer loop control var.
7457   bool IsNonRectangularUB = false;
7458   /// Index of the loop this loop depends on and forms non-rectangular loop
7459   /// nest.
7460   unsigned LoopDependentIdx = 0;
7461   /// Final condition for the non-rectangular loop nest support. It is used to
7462   /// check that the number of iterations for this particular counter must be
7463   /// finished.
7464   Expr *FinalCondition = nullptr;
7465 };
7466 
7467 /// Helper class for checking canonical form of the OpenMP loops and
7468 /// extracting iteration space of each loop in the loop nest, that will be used
7469 /// for IR generation.
7470 class OpenMPIterationSpaceChecker {
7471   /// Reference to Sema.
7472   Sema &SemaRef;
7473   /// Does the loop associated directive support non-rectangular loops?
7474   bool SupportsNonRectangular;
7475   /// Data-sharing stack.
7476   DSAStackTy &Stack;
7477   /// A location for diagnostics (when there is no some better location).
7478   SourceLocation DefaultLoc;
7479   /// A location for diagnostics (when increment is not compatible).
7480   SourceLocation ConditionLoc;
7481   /// A source location for referring to loop init later.
7482   SourceRange InitSrcRange;
7483   /// A source location for referring to condition later.
7484   SourceRange ConditionSrcRange;
7485   /// A source location for referring to increment later.
7486   SourceRange IncrementSrcRange;
7487   /// Loop variable.
7488   ValueDecl *LCDecl = nullptr;
7489   /// Reference to loop variable.
7490   Expr *LCRef = nullptr;
7491   /// Lower bound (initializer for the var).
7492   Expr *LB = nullptr;
7493   /// Upper bound.
7494   Expr *UB = nullptr;
7495   /// Loop step (increment).
7496   Expr *Step = nullptr;
7497   /// This flag is true when condition is one of:
7498   ///   Var <  UB
7499   ///   Var <= UB
7500   ///   UB  >  Var
7501   ///   UB  >= Var
7502   /// This will have no value when the condition is !=
7503   llvm::Optional<bool> TestIsLessOp;
7504   /// This flag is true when condition is strict ( < or > ).
7505   bool TestIsStrictOp = false;
7506   /// This flag is true when step is subtracted on each iteration.
7507   bool SubtractStep = false;
7508   /// The outer loop counter this loop depends on (if any).
7509   const ValueDecl *DepDecl = nullptr;
7510   /// Contains number of loop (starts from 1) on which loop counter init
7511   /// expression of this loop depends on.
7512   Optional<unsigned> InitDependOnLC;
7513   /// Contains number of loop (starts from 1) on which loop counter condition
7514   /// expression of this loop depends on.
7515   Optional<unsigned> CondDependOnLC;
7516   /// Checks if the provide statement depends on the loop counter.
7517   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7518   /// Original condition required for checking of the exit condition for
7519   /// non-rectangular loop.
7520   Expr *Condition = nullptr;
7521 
7522 public:
7523   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7524                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7525       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7526         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7527   /// Check init-expr for canonical loop form and save loop counter
7528   /// variable - #Var and its initialization value - #LB.
7529   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7530   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7531   /// for less/greater and for strict/non-strict comparison.
7532   bool checkAndSetCond(Expr *S);
7533   /// Check incr-expr for canonical loop form and return true if it
7534   /// does not conform, otherwise save loop step (#Step).
7535   bool checkAndSetInc(Expr *S);
7536   /// Return the loop counter variable.
7537   ValueDecl *getLoopDecl() const { return LCDecl; }
7538   /// Return the reference expression to loop counter variable.
7539   Expr *getLoopDeclRefExpr() const { return LCRef; }
7540   /// Source range of the loop init.
7541   SourceRange getInitSrcRange() const { return InitSrcRange; }
7542   /// Source range of the loop condition.
7543   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7544   /// Source range of the loop increment.
7545   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7546   /// True if the step should be subtracted.
7547   bool shouldSubtractStep() const { return SubtractStep; }
7548   /// True, if the compare operator is strict (<, > or !=).
7549   bool isStrictTestOp() const { return TestIsStrictOp; }
7550   /// Build the expression to calculate the number of iterations.
7551   Expr *buildNumIterations(
7552       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7553       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7554   /// Build the precondition expression for the loops.
7555   Expr *
7556   buildPreCond(Scope *S, Expr *Cond,
7557                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7558   /// Build reference expression to the counter be used for codegen.
7559   DeclRefExpr *
7560   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7561                   DSAStackTy &DSA) const;
7562   /// Build reference expression to the private counter be used for
7563   /// codegen.
7564   Expr *buildPrivateCounterVar() const;
7565   /// Build initialization of the counter be used for codegen.
7566   Expr *buildCounterInit() const;
7567   /// Build step of the counter be used for codegen.
7568   Expr *buildCounterStep() const;
7569   /// Build loop data with counter value for depend clauses in ordered
7570   /// directives.
7571   Expr *
7572   buildOrderedLoopData(Scope *S, Expr *Counter,
7573                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7574                        SourceLocation Loc, Expr *Inc = nullptr,
7575                        OverloadedOperatorKind OOK = OO_Amp);
7576   /// Builds the minimum value for the loop counter.
7577   std::pair<Expr *, Expr *> buildMinMaxValues(
7578       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7579   /// Builds final condition for the non-rectangular loops.
7580   Expr *buildFinalCondition(Scope *S) const;
7581   /// Return true if any expression is dependent.
7582   bool dependent() const;
7583   /// Returns true if the initializer forms non-rectangular loop.
7584   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7585   /// Returns true if the condition forms non-rectangular loop.
7586   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7587   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7588   unsigned getLoopDependentIdx() const {
7589     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7590   }
7591 
7592 private:
7593   /// Check the right-hand side of an assignment in the increment
7594   /// expression.
7595   bool checkAndSetIncRHS(Expr *RHS);
7596   /// Helper to set loop counter variable and its initializer.
7597   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7598                       bool EmitDiags);
7599   /// Helper to set upper bound.
7600   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7601              SourceRange SR, SourceLocation SL);
7602   /// Helper to set loop increment.
7603   bool setStep(Expr *NewStep, bool Subtract);
7604 };
7605 
7606 bool OpenMPIterationSpaceChecker::dependent() const {
7607   if (!LCDecl) {
7608     assert(!LB && !UB && !Step);
7609     return false;
7610   }
7611   return LCDecl->getType()->isDependentType() ||
7612          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7613          (Step && Step->isValueDependent());
7614 }
7615 
7616 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7617                                                  Expr *NewLCRefExpr,
7618                                                  Expr *NewLB, bool EmitDiags) {
7619   // State consistency checking to ensure correct usage.
7620   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7621          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7622   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7623     return true;
7624   LCDecl = getCanonicalDecl(NewLCDecl);
7625   LCRef = NewLCRefExpr;
7626   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7627     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7628       if ((Ctor->isCopyOrMoveConstructor() ||
7629            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7630           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7631         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7632   LB = NewLB;
7633   if (EmitDiags)
7634     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7635   return false;
7636 }
7637 
7638 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7639                                         llvm::Optional<bool> LessOp,
7640                                         bool StrictOp, SourceRange SR,
7641                                         SourceLocation SL) {
7642   // State consistency checking to ensure correct usage.
7643   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7644          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7645   if (!NewUB || NewUB->containsErrors())
7646     return true;
7647   UB = NewUB;
7648   if (LessOp)
7649     TestIsLessOp = LessOp;
7650   TestIsStrictOp = StrictOp;
7651   ConditionSrcRange = SR;
7652   ConditionLoc = SL;
7653   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7654   return false;
7655 }
7656 
7657 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7658   // State consistency checking to ensure correct usage.
7659   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7660   if (!NewStep || NewStep->containsErrors())
7661     return true;
7662   if (!NewStep->isValueDependent()) {
7663     // Check that the step is integer expression.
7664     SourceLocation StepLoc = NewStep->getBeginLoc();
7665     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7666         StepLoc, getExprAsWritten(NewStep));
7667     if (Val.isInvalid())
7668       return true;
7669     NewStep = Val.get();
7670 
7671     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7672     //  If test-expr is of form var relational-op b and relational-op is < or
7673     //  <= then incr-expr must cause var to increase on each iteration of the
7674     //  loop. If test-expr is of form var relational-op b and relational-op is
7675     //  > or >= then incr-expr must cause var to decrease on each iteration of
7676     //  the loop.
7677     //  If test-expr is of form b relational-op var and relational-op is < or
7678     //  <= then incr-expr must cause var to decrease on each iteration of the
7679     //  loop. If test-expr is of form b relational-op var and relational-op is
7680     //  > or >= then incr-expr must cause var to increase on each iteration of
7681     //  the loop.
7682     Optional<llvm::APSInt> Result =
7683         NewStep->getIntegerConstantExpr(SemaRef.Context);
7684     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7685     bool IsConstNeg =
7686         Result && Result->isSigned() && (Subtract != Result->isNegative());
7687     bool IsConstPos =
7688         Result && Result->isSigned() && (Subtract == Result->isNegative());
7689     bool IsConstZero = Result && !Result->getBoolValue();
7690 
7691     // != with increment is treated as <; != with decrement is treated as >
7692     if (!TestIsLessOp.hasValue())
7693       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7694     if (UB &&
7695         (IsConstZero || (TestIsLessOp.getValue()
7696                              ? (IsConstNeg || (IsUnsigned && Subtract))
7697                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
7698       SemaRef.Diag(NewStep->getExprLoc(),
7699                    diag::err_omp_loop_incr_not_compatible)
7700           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7701       SemaRef.Diag(ConditionLoc,
7702                    diag::note_omp_loop_cond_requres_compatible_incr)
7703           << TestIsLessOp.getValue() << ConditionSrcRange;
7704       return true;
7705     }
7706     if (TestIsLessOp.getValue() == Subtract) {
7707       NewStep =
7708           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7709               .get();
7710       Subtract = !Subtract;
7711     }
7712   }
7713 
7714   Step = NewStep;
7715   SubtractStep = Subtract;
7716   return false;
7717 }
7718 
7719 namespace {
7720 /// Checker for the non-rectangular loops. Checks if the initializer or
7721 /// condition expression references loop counter variable.
7722 class LoopCounterRefChecker final
7723     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7724   Sema &SemaRef;
7725   DSAStackTy &Stack;
7726   const ValueDecl *CurLCDecl = nullptr;
7727   const ValueDecl *DepDecl = nullptr;
7728   const ValueDecl *PrevDepDecl = nullptr;
7729   bool IsInitializer = true;
7730   bool SupportsNonRectangular;
7731   unsigned BaseLoopId = 0;
7732   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7733     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7734       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7735           << (IsInitializer ? 0 : 1);
7736       return false;
7737     }
7738     const auto &&Data = Stack.isLoopControlVariable(VD);
7739     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7740     // The type of the loop iterator on which we depend may not have a random
7741     // access iterator type.
7742     if (Data.first && VD->getType()->isRecordType()) {
7743       SmallString<128> Name;
7744       llvm::raw_svector_ostream OS(Name);
7745       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7746                                /*Qualified=*/true);
7747       SemaRef.Diag(E->getExprLoc(),
7748                    diag::err_omp_wrong_dependency_iterator_type)
7749           << OS.str();
7750       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7751       return false;
7752     }
7753     if (Data.first && !SupportsNonRectangular) {
7754       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7755       return false;
7756     }
7757     if (Data.first &&
7758         (DepDecl || (PrevDepDecl &&
7759                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7760       if (!DepDecl && PrevDepDecl)
7761         DepDecl = PrevDepDecl;
7762       SmallString<128> Name;
7763       llvm::raw_svector_ostream OS(Name);
7764       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7765                                     /*Qualified=*/true);
7766       SemaRef.Diag(E->getExprLoc(),
7767                    diag::err_omp_invariant_or_linear_dependency)
7768           << OS.str();
7769       return false;
7770     }
7771     if (Data.first) {
7772       DepDecl = VD;
7773       BaseLoopId = Data.first;
7774     }
7775     return Data.first;
7776   }
7777 
7778 public:
7779   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7780     const ValueDecl *VD = E->getDecl();
7781     if (isa<VarDecl>(VD))
7782       return checkDecl(E, VD);
7783     return false;
7784   }
7785   bool VisitMemberExpr(const MemberExpr *E) {
7786     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7787       const ValueDecl *VD = E->getMemberDecl();
7788       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7789         return checkDecl(E, VD);
7790     }
7791     return false;
7792   }
7793   bool VisitStmt(const Stmt *S) {
7794     bool Res = false;
7795     for (const Stmt *Child : S->children())
7796       Res = (Child && Visit(Child)) || Res;
7797     return Res;
7798   }
7799   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7800                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7801                                  const ValueDecl *PrevDepDecl = nullptr,
7802                                  bool SupportsNonRectangular = true)
7803       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7804         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7805         SupportsNonRectangular(SupportsNonRectangular) {}
7806   unsigned getBaseLoopId() const {
7807     assert(CurLCDecl && "Expected loop dependency.");
7808     return BaseLoopId;
7809   }
7810   const ValueDecl *getDepDecl() const {
7811     assert(CurLCDecl && "Expected loop dependency.");
7812     return DepDecl;
7813   }
7814 };
7815 } // namespace
7816 
7817 Optional<unsigned>
7818 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7819                                                      bool IsInitializer) {
7820   // Check for the non-rectangular loops.
7821   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7822                                         DepDecl, SupportsNonRectangular);
7823   if (LoopStmtChecker.Visit(S)) {
7824     DepDecl = LoopStmtChecker.getDepDecl();
7825     return LoopStmtChecker.getBaseLoopId();
7826   }
7827   return llvm::None;
7828 }
7829 
7830 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7831   // Check init-expr for canonical loop form and save loop counter
7832   // variable - #Var and its initialization value - #LB.
7833   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7834   //   var = lb
7835   //   integer-type var = lb
7836   //   random-access-iterator-type var = lb
7837   //   pointer-type var = lb
7838   //
7839   if (!S) {
7840     if (EmitDiags) {
7841       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7842     }
7843     return true;
7844   }
7845   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7846     if (!ExprTemp->cleanupsHaveSideEffects())
7847       S = ExprTemp->getSubExpr();
7848 
7849   InitSrcRange = S->getSourceRange();
7850   if (Expr *E = dyn_cast<Expr>(S))
7851     S = E->IgnoreParens();
7852   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7853     if (BO->getOpcode() == BO_Assign) {
7854       Expr *LHS = BO->getLHS()->IgnoreParens();
7855       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7856         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7857           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7858             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7859                                   EmitDiags);
7860         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7861       }
7862       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7863         if (ME->isArrow() &&
7864             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7865           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7866                                 EmitDiags);
7867       }
7868     }
7869   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7870     if (DS->isSingleDecl()) {
7871       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7872         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7873           // Accept non-canonical init form here but emit ext. warning.
7874           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7875             SemaRef.Diag(S->getBeginLoc(),
7876                          diag::ext_omp_loop_not_canonical_init)
7877                 << S->getSourceRange();
7878           return setLCDeclAndLB(
7879               Var,
7880               buildDeclRefExpr(SemaRef, Var,
7881                                Var->getType().getNonReferenceType(),
7882                                DS->getBeginLoc()),
7883               Var->getInit(), EmitDiags);
7884         }
7885       }
7886     }
7887   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7888     if (CE->getOperator() == OO_Equal) {
7889       Expr *LHS = CE->getArg(0);
7890       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7891         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7892           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7893             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7894                                   EmitDiags);
7895         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7896       }
7897       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7898         if (ME->isArrow() &&
7899             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7900           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7901                                 EmitDiags);
7902       }
7903     }
7904   }
7905 
7906   if (dependent() || SemaRef.CurContext->isDependentContext())
7907     return false;
7908   if (EmitDiags) {
7909     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7910         << S->getSourceRange();
7911   }
7912   return true;
7913 }
7914 
7915 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7916 /// variable (which may be the loop variable) if possible.
7917 static const ValueDecl *getInitLCDecl(const Expr *E) {
7918   if (!E)
7919     return nullptr;
7920   E = getExprAsWritten(E);
7921   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7922     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7923       if ((Ctor->isCopyOrMoveConstructor() ||
7924            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7925           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7926         E = CE->getArg(0)->IgnoreParenImpCasts();
7927   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7928     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7929       return getCanonicalDecl(VD);
7930   }
7931   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7932     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7933       return getCanonicalDecl(ME->getMemberDecl());
7934   return nullptr;
7935 }
7936 
7937 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7938   // Check test-expr for canonical form, save upper-bound UB, flags for
7939   // less/greater and for strict/non-strict comparison.
7940   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7941   //   var relational-op b
7942   //   b relational-op var
7943   //
7944   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7945   if (!S) {
7946     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7947         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7948     return true;
7949   }
7950   Condition = S;
7951   S = getExprAsWritten(S);
7952   SourceLocation CondLoc = S->getBeginLoc();
7953   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7954                                BinaryOperatorKind Opcode, const Expr *LHS,
7955                                const Expr *RHS, SourceRange SR,
7956                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7957     if (BinaryOperator::isRelationalOp(Opcode)) {
7958       if (getInitLCDecl(LHS) == LCDecl)
7959         return setUB(const_cast<Expr *>(RHS),
7960                      (Opcode == BO_LT || Opcode == BO_LE),
7961                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7962       if (getInitLCDecl(RHS) == LCDecl)
7963         return setUB(const_cast<Expr *>(LHS),
7964                      (Opcode == BO_GT || Opcode == BO_GE),
7965                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7966     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7967       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7968                    /*LessOp=*/llvm::None,
7969                    /*StrictOp=*/true, SR, OpLoc);
7970     }
7971     return llvm::None;
7972   };
7973   llvm::Optional<bool> Res;
7974   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7975     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7976     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7977                           RBO->getOperatorLoc());
7978   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7979     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7980                           BO->getSourceRange(), BO->getOperatorLoc());
7981   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7982     if (CE->getNumArgs() == 2) {
7983       Res = CheckAndSetCond(
7984           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7985           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7986     }
7987   }
7988   if (Res.hasValue())
7989     return *Res;
7990   if (dependent() || SemaRef.CurContext->isDependentContext())
7991     return false;
7992   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7993       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7994   return true;
7995 }
7996 
7997 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7998   // RHS of canonical loop form increment can be:
7999   //   var + incr
8000   //   incr + var
8001   //   var - incr
8002   //
8003   RHS = RHS->IgnoreParenImpCasts();
8004   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
8005     if (BO->isAdditiveOp()) {
8006       bool IsAdd = BO->getOpcode() == BO_Add;
8007       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8008         return setStep(BO->getRHS(), !IsAdd);
8009       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
8010         return setStep(BO->getLHS(), /*Subtract=*/false);
8011     }
8012   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
8013     bool IsAdd = CE->getOperator() == OO_Plus;
8014     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
8015       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8016         return setStep(CE->getArg(1), !IsAdd);
8017       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
8018         return setStep(CE->getArg(0), /*Subtract=*/false);
8019     }
8020   }
8021   if (dependent() || SemaRef.CurContext->isDependentContext())
8022     return false;
8023   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8024       << RHS->getSourceRange() << LCDecl;
8025   return true;
8026 }
8027 
8028 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
8029   // Check incr-expr for canonical loop form and return true if it
8030   // does not conform.
8031   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
8032   //   ++var
8033   //   var++
8034   //   --var
8035   //   var--
8036   //   var += incr
8037   //   var -= incr
8038   //   var = var + incr
8039   //   var = incr + var
8040   //   var = var - incr
8041   //
8042   if (!S) {
8043     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
8044     return true;
8045   }
8046   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
8047     if (!ExprTemp->cleanupsHaveSideEffects())
8048       S = ExprTemp->getSubExpr();
8049 
8050   IncrementSrcRange = S->getSourceRange();
8051   S = S->IgnoreParens();
8052   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
8053     if (UO->isIncrementDecrementOp() &&
8054         getInitLCDecl(UO->getSubExpr()) == LCDecl)
8055       return setStep(SemaRef
8056                          .ActOnIntegerConstant(UO->getBeginLoc(),
8057                                                (UO->isDecrementOp() ? -1 : 1))
8058                          .get(),
8059                      /*Subtract=*/false);
8060   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
8061     switch (BO->getOpcode()) {
8062     case BO_AddAssign:
8063     case BO_SubAssign:
8064       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8065         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
8066       break;
8067     case BO_Assign:
8068       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8069         return checkAndSetIncRHS(BO->getRHS());
8070       break;
8071     default:
8072       break;
8073     }
8074   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8075     switch (CE->getOperator()) {
8076     case OO_PlusPlus:
8077     case OO_MinusMinus:
8078       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8079         return setStep(SemaRef
8080                            .ActOnIntegerConstant(
8081                                CE->getBeginLoc(),
8082                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
8083                            .get(),
8084                        /*Subtract=*/false);
8085       break;
8086     case OO_PlusEqual:
8087     case OO_MinusEqual:
8088       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8089         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
8090       break;
8091     case OO_Equal:
8092       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8093         return checkAndSetIncRHS(CE->getArg(1));
8094       break;
8095     default:
8096       break;
8097     }
8098   }
8099   if (dependent() || SemaRef.CurContext->isDependentContext())
8100     return false;
8101   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8102       << S->getSourceRange() << LCDecl;
8103   return true;
8104 }
8105 
8106 static ExprResult
8107 tryBuildCapture(Sema &SemaRef, Expr *Capture,
8108                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8109   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
8110     return Capture;
8111   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
8112     return SemaRef.PerformImplicitConversion(
8113         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
8114         /*AllowExplicit=*/true);
8115   auto I = Captures.find(Capture);
8116   if (I != Captures.end())
8117     return buildCapture(SemaRef, Capture, I->second);
8118   DeclRefExpr *Ref = nullptr;
8119   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
8120   Captures[Capture] = Ref;
8121   return Res;
8122 }
8123 
8124 /// Calculate number of iterations, transforming to unsigned, if number of
8125 /// iterations may be larger than the original type.
8126 static Expr *
8127 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
8128                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
8129                   bool TestIsStrictOp, bool RoundToStep,
8130                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8131   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8132   if (!NewStep.isUsable())
8133     return nullptr;
8134   llvm::APSInt LRes, SRes;
8135   bool IsLowerConst = false, IsStepConst = false;
8136   if (Optional<llvm::APSInt> Res =
8137           Lower->getIntegerConstantExpr(SemaRef.Context)) {
8138     LRes = *Res;
8139     IsLowerConst = true;
8140   }
8141   if (Optional<llvm::APSInt> Res =
8142           Step->getIntegerConstantExpr(SemaRef.Context)) {
8143     SRes = *Res;
8144     IsStepConst = true;
8145   }
8146   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
8147                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
8148                           (TestIsStrictOp && LRes.isStrictlyPositive()));
8149   bool NeedToReorganize = false;
8150   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
8151   if (!NoNeedToConvert && IsLowerConst &&
8152       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
8153     NoNeedToConvert = true;
8154     if (RoundToStep) {
8155       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
8156                         ? LRes.getBitWidth()
8157                         : SRes.getBitWidth();
8158       LRes = LRes.extend(BW + 1);
8159       LRes.setIsSigned(true);
8160       SRes = SRes.extend(BW + 1);
8161       SRes.setIsSigned(true);
8162       LRes -= SRes;
8163       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
8164       LRes = LRes.trunc(BW);
8165     }
8166     if (TestIsStrictOp) {
8167       unsigned BW = LRes.getBitWidth();
8168       LRes = LRes.extend(BW + 1);
8169       LRes.setIsSigned(true);
8170       ++LRes;
8171       NoNeedToConvert =
8172           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
8173       // truncate to the original bitwidth.
8174       LRes = LRes.trunc(BW);
8175     }
8176     NeedToReorganize = NoNeedToConvert;
8177   }
8178   llvm::APSInt URes;
8179   bool IsUpperConst = false;
8180   if (Optional<llvm::APSInt> Res =
8181           Upper->getIntegerConstantExpr(SemaRef.Context)) {
8182     URes = *Res;
8183     IsUpperConst = true;
8184   }
8185   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
8186       (!RoundToStep || IsStepConst)) {
8187     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
8188                                                           : URes.getBitWidth();
8189     LRes = LRes.extend(BW + 1);
8190     LRes.setIsSigned(true);
8191     URes = URes.extend(BW + 1);
8192     URes.setIsSigned(true);
8193     URes -= LRes;
8194     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
8195     NeedToReorganize = NoNeedToConvert;
8196   }
8197   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
8198   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
8199   // unsigned.
8200   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
8201       !LCTy->isDependentType() && LCTy->isIntegerType()) {
8202     QualType LowerTy = Lower->getType();
8203     QualType UpperTy = Upper->getType();
8204     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
8205     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
8206     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
8207         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
8208       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
8209           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
8210       Upper =
8211           SemaRef
8212               .PerformImplicitConversion(
8213                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8214                   CastType, Sema::AA_Converting)
8215               .get();
8216       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
8217       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
8218     }
8219   }
8220   if (!Lower || !Upper || NewStep.isInvalid())
8221     return nullptr;
8222 
8223   ExprResult Diff;
8224   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
8225   // 1]).
8226   if (NeedToReorganize) {
8227     Diff = Lower;
8228 
8229     if (RoundToStep) {
8230       // Lower - Step
8231       Diff =
8232           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
8233       if (!Diff.isUsable())
8234         return nullptr;
8235     }
8236 
8237     // Lower - Step [+ 1]
8238     if (TestIsStrictOp)
8239       Diff = SemaRef.BuildBinOp(
8240           S, DefaultLoc, BO_Add, Diff.get(),
8241           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8242     if (!Diff.isUsable())
8243       return nullptr;
8244 
8245     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8246     if (!Diff.isUsable())
8247       return nullptr;
8248 
8249     // Upper - (Lower - Step [+ 1]).
8250     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
8251     if (!Diff.isUsable())
8252       return nullptr;
8253   } else {
8254     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8255 
8256     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8257       // BuildBinOp already emitted error, this one is to point user to upper
8258       // and lower bound, and to tell what is passed to 'operator-'.
8259       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8260           << Upper->getSourceRange() << Lower->getSourceRange();
8261       return nullptr;
8262     }
8263 
8264     if (!Diff.isUsable())
8265       return nullptr;
8266 
8267     // Upper - Lower [- 1]
8268     if (TestIsStrictOp)
8269       Diff = SemaRef.BuildBinOp(
8270           S, DefaultLoc, BO_Sub, Diff.get(),
8271           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8272     if (!Diff.isUsable())
8273       return nullptr;
8274 
8275     if (RoundToStep) {
8276       // Upper - Lower [- 1] + Step
8277       Diff =
8278           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8279       if (!Diff.isUsable())
8280         return nullptr;
8281     }
8282   }
8283 
8284   // Parentheses (for dumping/debugging purposes only).
8285   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8286   if (!Diff.isUsable())
8287     return nullptr;
8288 
8289   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8290   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8291   if (!Diff.isUsable())
8292     return nullptr;
8293 
8294   return Diff.get();
8295 }
8296 
8297 /// Build the expression to calculate the number of iterations.
8298 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8299     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8300     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8301   QualType VarType = LCDecl->getType().getNonReferenceType();
8302   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8303       !SemaRef.getLangOpts().CPlusPlus)
8304     return nullptr;
8305   Expr *LBVal = LB;
8306   Expr *UBVal = UB;
8307   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8308   // max(LB(MinVal), LB(MaxVal))
8309   if (InitDependOnLC) {
8310     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8311     if (!IS.MinValue || !IS.MaxValue)
8312       return nullptr;
8313     // OuterVar = Min
8314     ExprResult MinValue =
8315         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8316     if (!MinValue.isUsable())
8317       return nullptr;
8318 
8319     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8320                                              IS.CounterVar, MinValue.get());
8321     if (!LBMinVal.isUsable())
8322       return nullptr;
8323     // OuterVar = Min, LBVal
8324     LBMinVal =
8325         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8326     if (!LBMinVal.isUsable())
8327       return nullptr;
8328     // (OuterVar = Min, LBVal)
8329     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8330     if (!LBMinVal.isUsable())
8331       return nullptr;
8332 
8333     // OuterVar = Max
8334     ExprResult MaxValue =
8335         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8336     if (!MaxValue.isUsable())
8337       return nullptr;
8338 
8339     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8340                                              IS.CounterVar, MaxValue.get());
8341     if (!LBMaxVal.isUsable())
8342       return nullptr;
8343     // OuterVar = Max, LBVal
8344     LBMaxVal =
8345         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8346     if (!LBMaxVal.isUsable())
8347       return nullptr;
8348     // (OuterVar = Max, LBVal)
8349     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8350     if (!LBMaxVal.isUsable())
8351       return nullptr;
8352 
8353     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8354     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8355     if (!LBMin || !LBMax)
8356       return nullptr;
8357     // LB(MinVal) < LB(MaxVal)
8358     ExprResult MinLessMaxRes =
8359         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8360     if (!MinLessMaxRes.isUsable())
8361       return nullptr;
8362     Expr *MinLessMax =
8363         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8364     if (!MinLessMax)
8365       return nullptr;
8366     if (TestIsLessOp.getValue()) {
8367       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8368       // LB(MaxVal))
8369       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8370                                                     MinLessMax, LBMin, LBMax);
8371       if (!MinLB.isUsable())
8372         return nullptr;
8373       LBVal = MinLB.get();
8374     } else {
8375       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8376       // LB(MaxVal))
8377       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8378                                                     MinLessMax, LBMax, LBMin);
8379       if (!MaxLB.isUsable())
8380         return nullptr;
8381       LBVal = MaxLB.get();
8382     }
8383   }
8384   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8385   // min(UB(MinVal), UB(MaxVal))
8386   if (CondDependOnLC) {
8387     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8388     if (!IS.MinValue || !IS.MaxValue)
8389       return nullptr;
8390     // OuterVar = Min
8391     ExprResult MinValue =
8392         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8393     if (!MinValue.isUsable())
8394       return nullptr;
8395 
8396     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8397                                              IS.CounterVar, MinValue.get());
8398     if (!UBMinVal.isUsable())
8399       return nullptr;
8400     // OuterVar = Min, UBVal
8401     UBMinVal =
8402         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8403     if (!UBMinVal.isUsable())
8404       return nullptr;
8405     // (OuterVar = Min, UBVal)
8406     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8407     if (!UBMinVal.isUsable())
8408       return nullptr;
8409 
8410     // OuterVar = Max
8411     ExprResult MaxValue =
8412         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8413     if (!MaxValue.isUsable())
8414       return nullptr;
8415 
8416     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8417                                              IS.CounterVar, MaxValue.get());
8418     if (!UBMaxVal.isUsable())
8419       return nullptr;
8420     // OuterVar = Max, UBVal
8421     UBMaxVal =
8422         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8423     if (!UBMaxVal.isUsable())
8424       return nullptr;
8425     // (OuterVar = Max, UBVal)
8426     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8427     if (!UBMaxVal.isUsable())
8428       return nullptr;
8429 
8430     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8431     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8432     if (!UBMin || !UBMax)
8433       return nullptr;
8434     // UB(MinVal) > UB(MaxVal)
8435     ExprResult MinGreaterMaxRes =
8436         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8437     if (!MinGreaterMaxRes.isUsable())
8438       return nullptr;
8439     Expr *MinGreaterMax =
8440         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8441     if (!MinGreaterMax)
8442       return nullptr;
8443     if (TestIsLessOp.getValue()) {
8444       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8445       // UB(MaxVal))
8446       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8447           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8448       if (!MaxUB.isUsable())
8449         return nullptr;
8450       UBVal = MaxUB.get();
8451     } else {
8452       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8453       // UB(MaxVal))
8454       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8455           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8456       if (!MinUB.isUsable())
8457         return nullptr;
8458       UBVal = MinUB.get();
8459     }
8460   }
8461   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8462   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8463   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8464   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8465   if (!Upper || !Lower)
8466     return nullptr;
8467 
8468   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8469                                       Step, VarType, TestIsStrictOp,
8470                                       /*RoundToStep=*/true, Captures);
8471   if (!Diff.isUsable())
8472     return nullptr;
8473 
8474   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8475   QualType Type = Diff.get()->getType();
8476   ASTContext &C = SemaRef.Context;
8477   bool UseVarType = VarType->hasIntegerRepresentation() &&
8478                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8479   if (!Type->isIntegerType() || UseVarType) {
8480     unsigned NewSize =
8481         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8482     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8483                                : Type->hasSignedIntegerRepresentation();
8484     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8485     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8486       Diff = SemaRef.PerformImplicitConversion(
8487           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8488       if (!Diff.isUsable())
8489         return nullptr;
8490     }
8491   }
8492   if (LimitedType) {
8493     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8494     if (NewSize != C.getTypeSize(Type)) {
8495       if (NewSize < C.getTypeSize(Type)) {
8496         assert(NewSize == 64 && "incorrect loop var size");
8497         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8498             << InitSrcRange << ConditionSrcRange;
8499       }
8500       QualType NewType = C.getIntTypeForBitwidth(
8501           NewSize, Type->hasSignedIntegerRepresentation() ||
8502                        C.getTypeSize(Type) < NewSize);
8503       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8504         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8505                                                  Sema::AA_Converting, true);
8506         if (!Diff.isUsable())
8507           return nullptr;
8508       }
8509     }
8510   }
8511 
8512   return Diff.get();
8513 }
8514 
8515 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8516     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8517   // Do not build for iterators, they cannot be used in non-rectangular loop
8518   // nests.
8519   if (LCDecl->getType()->isRecordType())
8520     return std::make_pair(nullptr, nullptr);
8521   // If we subtract, the min is in the condition, otherwise the min is in the
8522   // init value.
8523   Expr *MinExpr = nullptr;
8524   Expr *MaxExpr = nullptr;
8525   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8526   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8527   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8528                                            : CondDependOnLC.hasValue();
8529   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8530                                            : InitDependOnLC.hasValue();
8531   Expr *Lower =
8532       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8533   Expr *Upper =
8534       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8535   if (!Upper || !Lower)
8536     return std::make_pair(nullptr, nullptr);
8537 
8538   if (TestIsLessOp.getValue())
8539     MinExpr = Lower;
8540   else
8541     MaxExpr = Upper;
8542 
8543   // Build minimum/maximum value based on number of iterations.
8544   QualType VarType = LCDecl->getType().getNonReferenceType();
8545 
8546   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8547                                       Step, VarType, TestIsStrictOp,
8548                                       /*RoundToStep=*/false, Captures);
8549   if (!Diff.isUsable())
8550     return std::make_pair(nullptr, nullptr);
8551 
8552   // ((Upper - Lower [- 1]) / Step) * Step
8553   // Parentheses (for dumping/debugging purposes only).
8554   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8555   if (!Diff.isUsable())
8556     return std::make_pair(nullptr, nullptr);
8557 
8558   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8559   if (!NewStep.isUsable())
8560     return std::make_pair(nullptr, nullptr);
8561   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8562   if (!Diff.isUsable())
8563     return std::make_pair(nullptr, nullptr);
8564 
8565   // Parentheses (for dumping/debugging purposes only).
8566   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8567   if (!Diff.isUsable())
8568     return std::make_pair(nullptr, nullptr);
8569 
8570   // Convert to the ptrdiff_t, if original type is pointer.
8571   if (VarType->isAnyPointerType() &&
8572       !SemaRef.Context.hasSameType(
8573           Diff.get()->getType(),
8574           SemaRef.Context.getUnsignedPointerDiffType())) {
8575     Diff = SemaRef.PerformImplicitConversion(
8576         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8577         Sema::AA_Converting, /*AllowExplicit=*/true);
8578   }
8579   if (!Diff.isUsable())
8580     return std::make_pair(nullptr, nullptr);
8581 
8582   if (TestIsLessOp.getValue()) {
8583     // MinExpr = Lower;
8584     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8585     Diff = SemaRef.BuildBinOp(
8586         S, DefaultLoc, BO_Add,
8587         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8588         Diff.get());
8589     if (!Diff.isUsable())
8590       return std::make_pair(nullptr, nullptr);
8591   } else {
8592     // MaxExpr = Upper;
8593     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8594     Diff = SemaRef.BuildBinOp(
8595         S, DefaultLoc, BO_Sub,
8596         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8597         Diff.get());
8598     if (!Diff.isUsable())
8599       return std::make_pair(nullptr, nullptr);
8600   }
8601 
8602   // Convert to the original type.
8603   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8604     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8605                                              Sema::AA_Converting,
8606                                              /*AllowExplicit=*/true);
8607   if (!Diff.isUsable())
8608     return std::make_pair(nullptr, nullptr);
8609 
8610   Sema::TentativeAnalysisScope Trap(SemaRef);
8611   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8612   if (!Diff.isUsable())
8613     return std::make_pair(nullptr, nullptr);
8614 
8615   if (TestIsLessOp.getValue())
8616     MaxExpr = Diff.get();
8617   else
8618     MinExpr = Diff.get();
8619 
8620   return std::make_pair(MinExpr, MaxExpr);
8621 }
8622 
8623 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8624   if (InitDependOnLC || CondDependOnLC)
8625     return Condition;
8626   return nullptr;
8627 }
8628 
8629 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8630     Scope *S, Expr *Cond,
8631     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8632   // Do not build a precondition when the condition/initialization is dependent
8633   // to prevent pessimistic early loop exit.
8634   // TODO: this can be improved by calculating min/max values but not sure that
8635   // it will be very effective.
8636   if (CondDependOnLC || InitDependOnLC)
8637     return SemaRef
8638         .PerformImplicitConversion(
8639             SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8640             SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8641             /*AllowExplicit=*/true)
8642         .get();
8643 
8644   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8645   Sema::TentativeAnalysisScope Trap(SemaRef);
8646 
8647   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8648   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8649   if (!NewLB.isUsable() || !NewUB.isUsable())
8650     return nullptr;
8651 
8652   ExprResult CondExpr = SemaRef.BuildBinOp(
8653       S, DefaultLoc,
8654       TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
8655                               : (TestIsStrictOp ? BO_GT : BO_GE),
8656       NewLB.get(), NewUB.get());
8657   if (CondExpr.isUsable()) {
8658     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8659                                                 SemaRef.Context.BoolTy))
8660       CondExpr = SemaRef.PerformImplicitConversion(
8661           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8662           /*AllowExplicit=*/true);
8663   }
8664 
8665   // Otherwise use original loop condition and evaluate it in runtime.
8666   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8667 }
8668 
8669 /// Build reference expression to the counter be used for codegen.
8670 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8671     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8672     DSAStackTy &DSA) const {
8673   auto *VD = dyn_cast<VarDecl>(LCDecl);
8674   if (!VD) {
8675     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8676     DeclRefExpr *Ref = buildDeclRefExpr(
8677         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8678     const DSAStackTy::DSAVarData Data =
8679         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8680     // If the loop control decl is explicitly marked as private, do not mark it
8681     // as captured again.
8682     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8683       Captures.insert(std::make_pair(LCRef, Ref));
8684     return Ref;
8685   }
8686   return cast<DeclRefExpr>(LCRef);
8687 }
8688 
8689 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8690   if (LCDecl && !LCDecl->isInvalidDecl()) {
8691     QualType Type = LCDecl->getType().getNonReferenceType();
8692     VarDecl *PrivateVar = buildVarDecl(
8693         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8694         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8695         isa<VarDecl>(LCDecl)
8696             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8697             : nullptr);
8698     if (PrivateVar->isInvalidDecl())
8699       return nullptr;
8700     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8701   }
8702   return nullptr;
8703 }
8704 
8705 /// Build initialization of the counter to be used for codegen.
8706 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8707 
8708 /// Build step of the counter be used for codegen.
8709 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8710 
8711 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8712     Scope *S, Expr *Counter,
8713     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8714     Expr *Inc, OverloadedOperatorKind OOK) {
8715   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8716   if (!Cnt)
8717     return nullptr;
8718   if (Inc) {
8719     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8720            "Expected only + or - operations for depend clauses.");
8721     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8722     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8723     if (!Cnt)
8724       return nullptr;
8725   }
8726   QualType VarType = LCDecl->getType().getNonReferenceType();
8727   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8728       !SemaRef.getLangOpts().CPlusPlus)
8729     return nullptr;
8730   // Upper - Lower
8731   Expr *Upper = TestIsLessOp.getValue()
8732                     ? Cnt
8733                     : tryBuildCapture(SemaRef, LB, Captures).get();
8734   Expr *Lower = TestIsLessOp.getValue()
8735                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8736                     : Cnt;
8737   if (!Upper || !Lower)
8738     return nullptr;
8739 
8740   ExprResult Diff = calculateNumIters(
8741       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8742       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8743   if (!Diff.isUsable())
8744     return nullptr;
8745 
8746   return Diff.get();
8747 }
8748 } // namespace
8749 
8750 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8751   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8752   assert(Init && "Expected loop in canonical form.");
8753   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8754   if (AssociatedLoops > 0 &&
8755       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8756     DSAStack->loopStart();
8757     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8758                                     *DSAStack, ForLoc);
8759     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8760       if (ValueDecl *D = ISC.getLoopDecl()) {
8761         auto *VD = dyn_cast<VarDecl>(D);
8762         DeclRefExpr *PrivateRef = nullptr;
8763         if (!VD) {
8764           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8765             VD = Private;
8766           } else {
8767             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8768                                       /*WithInit=*/false);
8769             VD = cast<VarDecl>(PrivateRef->getDecl());
8770           }
8771         }
8772         DSAStack->addLoopControlVariable(D, VD);
8773         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8774         if (LD != D->getCanonicalDecl()) {
8775           DSAStack->resetPossibleLoopCounter();
8776           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8777             MarkDeclarationsReferencedInExpr(
8778                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8779                                  Var->getType().getNonLValueExprType(Context),
8780                                  ForLoc, /*RefersToCapture=*/true));
8781         }
8782         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8783         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8784         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8785         // associated for-loop of a simd construct with just one associated
8786         // for-loop may be listed in a linear clause with a constant-linear-step
8787         // that is the increment of the associated for-loop. The loop iteration
8788         // variable(s) in the associated for-loop(s) of a for or parallel for
8789         // construct may be listed in a private or lastprivate clause.
8790         DSAStackTy::DSAVarData DVar =
8791             DSAStack->getTopDSA(D, /*FromParent=*/false);
8792         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8793         // is declared in the loop and it is predetermined as a private.
8794         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8795         OpenMPClauseKind PredeterminedCKind =
8796             isOpenMPSimdDirective(DKind)
8797                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8798                 : OMPC_private;
8799         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8800               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8801               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8802                                          DVar.CKind != OMPC_private))) ||
8803              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8804                DKind == OMPD_master_taskloop ||
8805                DKind == OMPD_parallel_master_taskloop ||
8806                isOpenMPDistributeDirective(DKind)) &&
8807               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8808               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8809             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8810           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8811               << getOpenMPClauseName(DVar.CKind)
8812               << getOpenMPDirectiveName(DKind)
8813               << getOpenMPClauseName(PredeterminedCKind);
8814           if (DVar.RefExpr == nullptr)
8815             DVar.CKind = PredeterminedCKind;
8816           reportOriginalDsa(*this, DSAStack, D, DVar,
8817                             /*IsLoopIterVar=*/true);
8818         } else if (LoopDeclRefExpr) {
8819           // Make the loop iteration variable private (for worksharing
8820           // constructs), linear (for simd directives with the only one
8821           // associated loop) or lastprivate (for simd directives with several
8822           // collapsed or ordered loops).
8823           if (DVar.CKind == OMPC_unknown)
8824             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8825                              PrivateRef);
8826         }
8827       }
8828     }
8829     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8830   }
8831 }
8832 
8833 /// Called on a for stmt to check and extract its iteration space
8834 /// for further processing (such as collapsing).
8835 static bool checkOpenMPIterationSpace(
8836     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8837     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8838     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8839     Expr *OrderedLoopCountExpr,
8840     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8841     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8842     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8843   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8844   // OpenMP [2.9.1, Canonical Loop Form]
8845   //   for (init-expr; test-expr; incr-expr) structured-block
8846   //   for (range-decl: range-expr) structured-block
8847   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8848     S = CanonLoop->getLoopStmt();
8849   auto *For = dyn_cast_or_null<ForStmt>(S);
8850   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8851   // Ranged for is supported only in OpenMP 5.0.
8852   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8853     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8854         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8855         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8856         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8857     if (TotalNestedLoopCount > 1) {
8858       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8859         SemaRef.Diag(DSA.getConstructLoc(),
8860                      diag::note_omp_collapse_ordered_expr)
8861             << 2 << CollapseLoopCountExpr->getSourceRange()
8862             << OrderedLoopCountExpr->getSourceRange();
8863       else if (CollapseLoopCountExpr)
8864         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8865                      diag::note_omp_collapse_ordered_expr)
8866             << 0 << CollapseLoopCountExpr->getSourceRange();
8867       else
8868         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8869                      diag::note_omp_collapse_ordered_expr)
8870             << 1 << OrderedLoopCountExpr->getSourceRange();
8871     }
8872     return true;
8873   }
8874   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8875          "No loop body.");
8876   // Postpone analysis in dependent contexts for ranged for loops.
8877   if (CXXFor && SemaRef.CurContext->isDependentContext())
8878     return false;
8879 
8880   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8881                                   For ? For->getForLoc() : CXXFor->getForLoc());
8882 
8883   // Check init.
8884   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8885   if (ISC.checkAndSetInit(Init))
8886     return true;
8887 
8888   bool HasErrors = false;
8889 
8890   // Check loop variable's type.
8891   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8892     // OpenMP [2.6, Canonical Loop Form]
8893     // Var is one of the following:
8894     //   A variable of signed or unsigned integer type.
8895     //   For C++, a variable of a random access iterator type.
8896     //   For C, a variable of a pointer type.
8897     QualType VarType = LCDecl->getType().getNonReferenceType();
8898     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8899         !VarType->isPointerType() &&
8900         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8901       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8902           << SemaRef.getLangOpts().CPlusPlus;
8903       HasErrors = true;
8904     }
8905 
8906     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8907     // a Construct
8908     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8909     // parallel for construct is (are) private.
8910     // The loop iteration variable in the associated for-loop of a simd
8911     // construct with just one associated for-loop is linear with a
8912     // constant-linear-step that is the increment of the associated for-loop.
8913     // Exclude loop var from the list of variables with implicitly defined data
8914     // sharing attributes.
8915     VarsWithImplicitDSA.erase(LCDecl);
8916 
8917     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8918 
8919     // Check test-expr.
8920     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8921 
8922     // Check incr-expr.
8923     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8924   }
8925 
8926   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8927     return HasErrors;
8928 
8929   // Build the loop's iteration space representation.
8930   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8931       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8932   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8933       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8934                              (isOpenMPWorksharingDirective(DKind) ||
8935                               isOpenMPGenericLoopDirective(DKind) ||
8936                               isOpenMPTaskLoopDirective(DKind) ||
8937                               isOpenMPDistributeDirective(DKind) ||
8938                               isOpenMPLoopTransformationDirective(DKind)),
8939                              Captures);
8940   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8941       ISC.buildCounterVar(Captures, DSA);
8942   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8943       ISC.buildPrivateCounterVar();
8944   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8945   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8946   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8947   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8948       ISC.getConditionSrcRange();
8949   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8950       ISC.getIncrementSrcRange();
8951   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8952   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8953       ISC.isStrictTestOp();
8954   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8955            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8956       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8957   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8958       ISC.buildFinalCondition(DSA.getCurScope());
8959   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8960       ISC.doesInitDependOnLC();
8961   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8962       ISC.doesCondDependOnLC();
8963   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8964       ISC.getLoopDependentIdx();
8965 
8966   HasErrors |=
8967       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8968        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8969        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8970        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8971        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8972        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8973   if (!HasErrors && DSA.isOrderedRegion()) {
8974     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8975       if (CurrentNestedLoopCount <
8976           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8977         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8978             CurrentNestedLoopCount,
8979             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8980         DSA.getOrderedRegionParam().second->setLoopCounter(
8981             CurrentNestedLoopCount,
8982             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8983       }
8984     }
8985     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8986       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8987         // Erroneous case - clause has some problems.
8988         continue;
8989       }
8990       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8991           Pair.second.size() <= CurrentNestedLoopCount) {
8992         // Erroneous case - clause has some problems.
8993         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8994         continue;
8995       }
8996       Expr *CntValue;
8997       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8998         CntValue = ISC.buildOrderedLoopData(
8999             DSA.getCurScope(),
9000             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
9001             Pair.first->getDependencyLoc());
9002       else
9003         CntValue = ISC.buildOrderedLoopData(
9004             DSA.getCurScope(),
9005             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
9006             Pair.first->getDependencyLoc(),
9007             Pair.second[CurrentNestedLoopCount].first,
9008             Pair.second[CurrentNestedLoopCount].second);
9009       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
9010     }
9011   }
9012 
9013   return HasErrors;
9014 }
9015 
9016 /// Build 'VarRef = Start.
9017 static ExprResult
9018 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
9019                  ExprResult Start, bool IsNonRectangularLB,
9020                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9021   // Build 'VarRef = Start.
9022   ExprResult NewStart = IsNonRectangularLB
9023                             ? Start.get()
9024                             : tryBuildCapture(SemaRef, Start.get(), Captures);
9025   if (!NewStart.isUsable())
9026     return ExprError();
9027   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
9028                                    VarRef.get()->getType())) {
9029     NewStart = SemaRef.PerformImplicitConversion(
9030         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
9031         /*AllowExplicit=*/true);
9032     if (!NewStart.isUsable())
9033       return ExprError();
9034   }
9035 
9036   ExprResult Init =
9037       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9038   return Init;
9039 }
9040 
9041 /// Build 'VarRef = Start + Iter * Step'.
9042 static ExprResult buildCounterUpdate(
9043     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
9044     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
9045     bool IsNonRectangularLB,
9046     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
9047   // Add parentheses (for debugging purposes only).
9048   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
9049   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
9050       !Step.isUsable())
9051     return ExprError();
9052 
9053   ExprResult NewStep = Step;
9054   if (Captures)
9055     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
9056   if (NewStep.isInvalid())
9057     return ExprError();
9058   ExprResult Update =
9059       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
9060   if (!Update.isUsable())
9061     return ExprError();
9062 
9063   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
9064   // 'VarRef = Start (+|-) Iter * Step'.
9065   if (!Start.isUsable())
9066     return ExprError();
9067   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
9068   if (!NewStart.isUsable())
9069     return ExprError();
9070   if (Captures && !IsNonRectangularLB)
9071     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
9072   if (NewStart.isInvalid())
9073     return ExprError();
9074 
9075   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
9076   ExprResult SavedUpdate = Update;
9077   ExprResult UpdateVal;
9078   if (VarRef.get()->getType()->isOverloadableType() ||
9079       NewStart.get()->getType()->isOverloadableType() ||
9080       Update.get()->getType()->isOverloadableType()) {
9081     Sema::TentativeAnalysisScope Trap(SemaRef);
9082 
9083     Update =
9084         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9085     if (Update.isUsable()) {
9086       UpdateVal =
9087           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
9088                              VarRef.get(), SavedUpdate.get());
9089       if (UpdateVal.isUsable()) {
9090         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
9091                                             UpdateVal.get());
9092       }
9093     }
9094   }
9095 
9096   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
9097   if (!Update.isUsable() || !UpdateVal.isUsable()) {
9098     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
9099                                 NewStart.get(), SavedUpdate.get());
9100     if (!Update.isUsable())
9101       return ExprError();
9102 
9103     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
9104                                      VarRef.get()->getType())) {
9105       Update = SemaRef.PerformImplicitConversion(
9106           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
9107       if (!Update.isUsable())
9108         return ExprError();
9109     }
9110 
9111     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
9112   }
9113   return Update;
9114 }
9115 
9116 /// Convert integer expression \a E to make it have at least \a Bits
9117 /// bits.
9118 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
9119   if (E == nullptr)
9120     return ExprError();
9121   ASTContext &C = SemaRef.Context;
9122   QualType OldType = E->getType();
9123   unsigned HasBits = C.getTypeSize(OldType);
9124   if (HasBits >= Bits)
9125     return ExprResult(E);
9126   // OK to convert to signed, because new type has more bits than old.
9127   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
9128   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
9129                                            true);
9130 }
9131 
9132 /// Check if the given expression \a E is a constant integer that fits
9133 /// into \a Bits bits.
9134 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
9135   if (E == nullptr)
9136     return false;
9137   if (Optional<llvm::APSInt> Result =
9138           E->getIntegerConstantExpr(SemaRef.Context))
9139     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
9140   return false;
9141 }
9142 
9143 /// Build preinits statement for the given declarations.
9144 static Stmt *buildPreInits(ASTContext &Context,
9145                            MutableArrayRef<Decl *> PreInits) {
9146   if (!PreInits.empty()) {
9147     return new (Context) DeclStmt(
9148         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
9149         SourceLocation(), SourceLocation());
9150   }
9151   return nullptr;
9152 }
9153 
9154 /// Build preinits statement for the given declarations.
9155 static Stmt *
9156 buildPreInits(ASTContext &Context,
9157               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9158   if (!Captures.empty()) {
9159     SmallVector<Decl *, 16> PreInits;
9160     for (const auto &Pair : Captures)
9161       PreInits.push_back(Pair.second->getDecl());
9162     return buildPreInits(Context, PreInits);
9163   }
9164   return nullptr;
9165 }
9166 
9167 /// Build postupdate expression for the given list of postupdates expressions.
9168 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
9169   Expr *PostUpdate = nullptr;
9170   if (!PostUpdates.empty()) {
9171     for (Expr *E : PostUpdates) {
9172       Expr *ConvE = S.BuildCStyleCastExpr(
9173                          E->getExprLoc(),
9174                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
9175                          E->getExprLoc(), E)
9176                         .get();
9177       PostUpdate = PostUpdate
9178                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
9179                                               PostUpdate, ConvE)
9180                              .get()
9181                        : ConvE;
9182     }
9183   }
9184   return PostUpdate;
9185 }
9186 
9187 /// Called on a for stmt to check itself and nested loops (if any).
9188 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
9189 /// number of collapsed loops otherwise.
9190 static unsigned
9191 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
9192                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
9193                 DSAStackTy &DSA,
9194                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
9195                 OMPLoopBasedDirective::HelperExprs &Built) {
9196   unsigned NestedLoopCount = 1;
9197   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
9198                                     !isOpenMPLoopTransformationDirective(DKind);
9199 
9200   if (CollapseLoopCountExpr) {
9201     // Found 'collapse' clause - calculate collapse number.
9202     Expr::EvalResult Result;
9203     if (!CollapseLoopCountExpr->isValueDependent() &&
9204         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
9205       NestedLoopCount = Result.Val.getInt().getLimitedValue();
9206     } else {
9207       Built.clear(/*Size=*/1);
9208       return 1;
9209     }
9210   }
9211   unsigned OrderedLoopCount = 1;
9212   if (OrderedLoopCountExpr) {
9213     // Found 'ordered' clause - calculate collapse number.
9214     Expr::EvalResult EVResult;
9215     if (!OrderedLoopCountExpr->isValueDependent() &&
9216         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
9217                                             SemaRef.getASTContext())) {
9218       llvm::APSInt Result = EVResult.Val.getInt();
9219       if (Result.getLimitedValue() < NestedLoopCount) {
9220         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
9221                      diag::err_omp_wrong_ordered_loop_count)
9222             << OrderedLoopCountExpr->getSourceRange();
9223         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9224                      diag::note_collapse_loop_count)
9225             << CollapseLoopCountExpr->getSourceRange();
9226       }
9227       OrderedLoopCount = Result.getLimitedValue();
9228     } else {
9229       Built.clear(/*Size=*/1);
9230       return 1;
9231     }
9232   }
9233   // This is helper routine for loop directives (e.g., 'for', 'simd',
9234   // 'for simd', etc.).
9235   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9236   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
9237   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
9238   if (!OMPLoopBasedDirective::doForAllLoops(
9239           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
9240           SupportsNonPerfectlyNested, NumLoops,
9241           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
9242            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
9243            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
9244             if (checkOpenMPIterationSpace(
9245                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
9246                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
9247                     VarsWithImplicitDSA, IterSpaces, Captures))
9248               return true;
9249             if (Cnt > 0 && Cnt >= NestedLoopCount &&
9250                 IterSpaces[Cnt].CounterVar) {
9251               // Handle initialization of captured loop iterator variables.
9252               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
9253               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
9254                 Captures[DRE] = DRE;
9255               }
9256             }
9257             return false;
9258           },
9259           [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
9260             Stmt *DependentPreInits = Transform->getPreInits();
9261             if (!DependentPreInits)
9262               return;
9263             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9264               auto *D = cast<VarDecl>(C);
9265               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9266                                                   Transform->getBeginLoc());
9267               Captures[Ref] = Ref;
9268             }
9269           }))
9270     return 0;
9271 
9272   Built.clear(/* size */ NestedLoopCount);
9273 
9274   if (SemaRef.CurContext->isDependentContext())
9275     return NestedLoopCount;
9276 
9277   // An example of what is generated for the following code:
9278   //
9279   //   #pragma omp simd collapse(2) ordered(2)
9280   //   for (i = 0; i < NI; ++i)
9281   //     for (k = 0; k < NK; ++k)
9282   //       for (j = J0; j < NJ; j+=2) {
9283   //         <loop body>
9284   //       }
9285   //
9286   // We generate the code below.
9287   // Note: the loop body may be outlined in CodeGen.
9288   // Note: some counters may be C++ classes, operator- is used to find number of
9289   // iterations and operator+= to calculate counter value.
9290   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9291   // or i64 is currently supported).
9292   //
9293   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9294   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9295   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9296   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9297   //     // similar updates for vars in clauses (e.g. 'linear')
9298   //     <loop body (using local i and j)>
9299   //   }
9300   //   i = NI; // assign final values of counters
9301   //   j = NJ;
9302   //
9303 
9304   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9305   // the iteration counts of the collapsed for loops.
9306   // Precondition tests if there is at least one iteration (all conditions are
9307   // true).
9308   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9309   Expr *N0 = IterSpaces[0].NumIterations;
9310   ExprResult LastIteration32 =
9311       widenIterationCount(/*Bits=*/32,
9312                           SemaRef
9313                               .PerformImplicitConversion(
9314                                   N0->IgnoreImpCasts(), N0->getType(),
9315                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9316                               .get(),
9317                           SemaRef);
9318   ExprResult LastIteration64 = widenIterationCount(
9319       /*Bits=*/64,
9320       SemaRef
9321           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9322                                      Sema::AA_Converting,
9323                                      /*AllowExplicit=*/true)
9324           .get(),
9325       SemaRef);
9326 
9327   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9328     return NestedLoopCount;
9329 
9330   ASTContext &C = SemaRef.Context;
9331   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9332 
9333   Scope *CurScope = DSA.getCurScope();
9334   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9335     if (PreCond.isUsable()) {
9336       PreCond =
9337           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9338                              PreCond.get(), IterSpaces[Cnt].PreCond);
9339     }
9340     Expr *N = IterSpaces[Cnt].NumIterations;
9341     SourceLocation Loc = N->getExprLoc();
9342     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9343     if (LastIteration32.isUsable())
9344       LastIteration32 = SemaRef.BuildBinOp(
9345           CurScope, Loc, BO_Mul, LastIteration32.get(),
9346           SemaRef
9347               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9348                                          Sema::AA_Converting,
9349                                          /*AllowExplicit=*/true)
9350               .get());
9351     if (LastIteration64.isUsable())
9352       LastIteration64 = SemaRef.BuildBinOp(
9353           CurScope, Loc, BO_Mul, LastIteration64.get(),
9354           SemaRef
9355               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9356                                          Sema::AA_Converting,
9357                                          /*AllowExplicit=*/true)
9358               .get());
9359   }
9360 
9361   // Choose either the 32-bit or 64-bit version.
9362   ExprResult LastIteration = LastIteration64;
9363   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9364       (LastIteration32.isUsable() &&
9365        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9366        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9367         fitsInto(
9368             /*Bits=*/32,
9369             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9370             LastIteration64.get(), SemaRef))))
9371     LastIteration = LastIteration32;
9372   QualType VType = LastIteration.get()->getType();
9373   QualType RealVType = VType;
9374   QualType StrideVType = VType;
9375   if (isOpenMPTaskLoopDirective(DKind)) {
9376     VType =
9377         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9378     StrideVType =
9379         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9380   }
9381 
9382   if (!LastIteration.isUsable())
9383     return 0;
9384 
9385   // Save the number of iterations.
9386   ExprResult NumIterations = LastIteration;
9387   {
9388     LastIteration = SemaRef.BuildBinOp(
9389         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9390         LastIteration.get(),
9391         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9392     if (!LastIteration.isUsable())
9393       return 0;
9394   }
9395 
9396   // Calculate the last iteration number beforehand instead of doing this on
9397   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9398   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9399   ExprResult CalcLastIteration;
9400   if (!IsConstant) {
9401     ExprResult SaveRef =
9402         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9403     LastIteration = SaveRef;
9404 
9405     // Prepare SaveRef + 1.
9406     NumIterations = SemaRef.BuildBinOp(
9407         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9408         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9409     if (!NumIterations.isUsable())
9410       return 0;
9411   }
9412 
9413   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9414 
9415   // Build variables passed into runtime, necessary for worksharing directives.
9416   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9417   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9418       isOpenMPDistributeDirective(DKind) ||
9419       isOpenMPGenericLoopDirective(DKind) ||
9420       isOpenMPLoopTransformationDirective(DKind)) {
9421     // Lower bound variable, initialized with zero.
9422     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9423     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9424     SemaRef.AddInitializerToDecl(LBDecl,
9425                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9426                                  /*DirectInit*/ false);
9427 
9428     // Upper bound variable, initialized with last iteration number.
9429     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9430     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9431     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9432                                  /*DirectInit*/ false);
9433 
9434     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9435     // This will be used to implement clause 'lastprivate'.
9436     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9437     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9438     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9439     SemaRef.AddInitializerToDecl(ILDecl,
9440                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9441                                  /*DirectInit*/ false);
9442 
9443     // Stride variable returned by runtime (we initialize it to 1 by default).
9444     VarDecl *STDecl =
9445         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9446     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9447     SemaRef.AddInitializerToDecl(STDecl,
9448                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9449                                  /*DirectInit*/ false);
9450 
9451     // Build expression: UB = min(UB, LastIteration)
9452     // It is necessary for CodeGen of directives with static scheduling.
9453     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9454                                                 UB.get(), LastIteration.get());
9455     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9456         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9457         LastIteration.get(), UB.get());
9458     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9459                              CondOp.get());
9460     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9461 
9462     // If we have a combined directive that combines 'distribute', 'for' or
9463     // 'simd' we need to be able to access the bounds of the schedule of the
9464     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9465     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9466     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9467       // Lower bound variable, initialized with zero.
9468       VarDecl *CombLBDecl =
9469           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9470       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9471       SemaRef.AddInitializerToDecl(
9472           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9473           /*DirectInit*/ false);
9474 
9475       // Upper bound variable, initialized with last iteration number.
9476       VarDecl *CombUBDecl =
9477           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9478       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9479       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9480                                    /*DirectInit*/ false);
9481 
9482       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9483           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9484       ExprResult CombCondOp =
9485           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9486                                      LastIteration.get(), CombUB.get());
9487       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9488                                    CombCondOp.get());
9489       CombEUB =
9490           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9491 
9492       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9493       // We expect to have at least 2 more parameters than the 'parallel'
9494       // directive does - the lower and upper bounds of the previous schedule.
9495       assert(CD->getNumParams() >= 4 &&
9496              "Unexpected number of parameters in loop combined directive");
9497 
9498       // Set the proper type for the bounds given what we learned from the
9499       // enclosed loops.
9500       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9501       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9502 
9503       // Previous lower and upper bounds are obtained from the region
9504       // parameters.
9505       PrevLB =
9506           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9507       PrevUB =
9508           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9509     }
9510   }
9511 
9512   // Build the iteration variable and its initialization before loop.
9513   ExprResult IV;
9514   ExprResult Init, CombInit;
9515   {
9516     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9517     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9518     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9519                  isOpenMPGenericLoopDirective(DKind) ||
9520                  isOpenMPTaskLoopDirective(DKind) ||
9521                  isOpenMPDistributeDirective(DKind) ||
9522                  isOpenMPLoopTransformationDirective(DKind))
9523                     ? LB.get()
9524                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9525     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9526     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9527 
9528     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9529       Expr *CombRHS =
9530           (isOpenMPWorksharingDirective(DKind) ||
9531            isOpenMPGenericLoopDirective(DKind) ||
9532            isOpenMPTaskLoopDirective(DKind) ||
9533            isOpenMPDistributeDirective(DKind))
9534               ? CombLB.get()
9535               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9536       CombInit =
9537           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9538       CombInit =
9539           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9540     }
9541   }
9542 
9543   bool UseStrictCompare =
9544       RealVType->hasUnsignedIntegerRepresentation() &&
9545       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9546         return LIS.IsStrictCompare;
9547       });
9548   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9549   // unsigned IV)) for worksharing loops.
9550   SourceLocation CondLoc = AStmt->getBeginLoc();
9551   Expr *BoundUB = UB.get();
9552   if (UseStrictCompare) {
9553     BoundUB =
9554         SemaRef
9555             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9556                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9557             .get();
9558     BoundUB =
9559         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9560   }
9561   ExprResult Cond =
9562       (isOpenMPWorksharingDirective(DKind) ||
9563        isOpenMPGenericLoopDirective(DKind) ||
9564        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9565        isOpenMPLoopTransformationDirective(DKind))
9566           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9567                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9568                                BoundUB)
9569           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9570                                NumIterations.get());
9571   ExprResult CombDistCond;
9572   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9573     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9574                                       NumIterations.get());
9575   }
9576 
9577   ExprResult CombCond;
9578   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9579     Expr *BoundCombUB = CombUB.get();
9580     if (UseStrictCompare) {
9581       BoundCombUB =
9582           SemaRef
9583               .BuildBinOp(
9584                   CurScope, CondLoc, BO_Add, BoundCombUB,
9585                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9586               .get();
9587       BoundCombUB =
9588           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9589               .get();
9590     }
9591     CombCond =
9592         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9593                            IV.get(), BoundCombUB);
9594   }
9595   // Loop increment (IV = IV + 1)
9596   SourceLocation IncLoc = AStmt->getBeginLoc();
9597   ExprResult Inc =
9598       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9599                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9600   if (!Inc.isUsable())
9601     return 0;
9602   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9603   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9604   if (!Inc.isUsable())
9605     return 0;
9606 
9607   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9608   // Used for directives with static scheduling.
9609   // In combined construct, add combined version that use CombLB and CombUB
9610   // base variables for the update
9611   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9612   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9613       isOpenMPGenericLoopDirective(DKind) ||
9614       isOpenMPDistributeDirective(DKind) ||
9615       isOpenMPLoopTransformationDirective(DKind)) {
9616     // LB + ST
9617     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9618     if (!NextLB.isUsable())
9619       return 0;
9620     // LB = LB + ST
9621     NextLB =
9622         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9623     NextLB =
9624         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9625     if (!NextLB.isUsable())
9626       return 0;
9627     // UB + ST
9628     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9629     if (!NextUB.isUsable())
9630       return 0;
9631     // UB = UB + ST
9632     NextUB =
9633         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9634     NextUB =
9635         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9636     if (!NextUB.isUsable())
9637       return 0;
9638     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9639       CombNextLB =
9640           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9641       if (!NextLB.isUsable())
9642         return 0;
9643       // LB = LB + ST
9644       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9645                                       CombNextLB.get());
9646       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9647                                                /*DiscardedValue*/ false);
9648       if (!CombNextLB.isUsable())
9649         return 0;
9650       // UB + ST
9651       CombNextUB =
9652           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9653       if (!CombNextUB.isUsable())
9654         return 0;
9655       // UB = UB + ST
9656       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9657                                       CombNextUB.get());
9658       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9659                                                /*DiscardedValue*/ false);
9660       if (!CombNextUB.isUsable())
9661         return 0;
9662     }
9663   }
9664 
9665   // Create increment expression for distribute loop when combined in a same
9666   // directive with for as IV = IV + ST; ensure upper bound expression based
9667   // on PrevUB instead of NumIterations - used to implement 'for' when found
9668   // in combination with 'distribute', like in 'distribute parallel for'
9669   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9670   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9671   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9672     DistCond = SemaRef.BuildBinOp(
9673         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9674     assert(DistCond.isUsable() && "distribute cond expr was not built");
9675 
9676     DistInc =
9677         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9678     assert(DistInc.isUsable() && "distribute inc expr was not built");
9679     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9680                                  DistInc.get());
9681     DistInc =
9682         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9683     assert(DistInc.isUsable() && "distribute inc expr was not built");
9684 
9685     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9686     // construct
9687     ExprResult NewPrevUB = PrevUB;
9688     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9689     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9690                                      PrevUB.get()->getType())) {
9691       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9692           DistEUBLoc,
9693           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9694           DistEUBLoc, NewPrevUB.get());
9695       if (!NewPrevUB.isUsable())
9696         return 0;
9697     }
9698     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9699                                                 UB.get(), NewPrevUB.get());
9700     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9701         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9702     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9703                                  CondOp.get());
9704     PrevEUB =
9705         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9706 
9707     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9708     // parallel for is in combination with a distribute directive with
9709     // schedule(static, 1)
9710     Expr *BoundPrevUB = PrevUB.get();
9711     if (UseStrictCompare) {
9712       BoundPrevUB =
9713           SemaRef
9714               .BuildBinOp(
9715                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9716                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9717               .get();
9718       BoundPrevUB =
9719           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9720               .get();
9721     }
9722     ParForInDistCond =
9723         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9724                            IV.get(), BoundPrevUB);
9725   }
9726 
9727   // Build updates and final values of the loop counters.
9728   bool HasErrors = false;
9729   Built.Counters.resize(NestedLoopCount);
9730   Built.Inits.resize(NestedLoopCount);
9731   Built.Updates.resize(NestedLoopCount);
9732   Built.Finals.resize(NestedLoopCount);
9733   Built.DependentCounters.resize(NestedLoopCount);
9734   Built.DependentInits.resize(NestedLoopCount);
9735   Built.FinalsConditions.resize(NestedLoopCount);
9736   {
9737     // We implement the following algorithm for obtaining the
9738     // original loop iteration variable values based on the
9739     // value of the collapsed loop iteration variable IV.
9740     //
9741     // Let n+1 be the number of collapsed loops in the nest.
9742     // Iteration variables (I0, I1, .... In)
9743     // Iteration counts (N0, N1, ... Nn)
9744     //
9745     // Acc = IV;
9746     //
9747     // To compute Ik for loop k, 0 <= k <= n, generate:
9748     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9749     //    Ik = Acc / Prod;
9750     //    Acc -= Ik * Prod;
9751     //
9752     ExprResult Acc = IV;
9753     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9754       LoopIterationSpace &IS = IterSpaces[Cnt];
9755       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9756       ExprResult Iter;
9757 
9758       // Compute prod
9759       ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9760       for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
9761         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9762                                   IterSpaces[K].NumIterations);
9763 
9764       // Iter = Acc / Prod
9765       // If there is at least one more inner loop to avoid
9766       // multiplication by 1.
9767       if (Cnt + 1 < NestedLoopCount)
9768         Iter =
9769             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
9770       else
9771         Iter = Acc;
9772       if (!Iter.isUsable()) {
9773         HasErrors = true;
9774         break;
9775       }
9776 
9777       // Update Acc:
9778       // Acc -= Iter * Prod
9779       // Check if there is at least one more inner loop to avoid
9780       // multiplication by 1.
9781       if (Cnt + 1 < NestedLoopCount)
9782         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
9783                                   Prod.get());
9784       else
9785         Prod = Iter;
9786       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
9787 
9788       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9789       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9790       DeclRefExpr *CounterVar = buildDeclRefExpr(
9791           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9792           /*RefersToCapture=*/true);
9793       ExprResult Init =
9794           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9795                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9796       if (!Init.isUsable()) {
9797         HasErrors = true;
9798         break;
9799       }
9800       ExprResult Update = buildCounterUpdate(
9801           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9802           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9803       if (!Update.isUsable()) {
9804         HasErrors = true;
9805         break;
9806       }
9807 
9808       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9809       ExprResult Final =
9810           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9811                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9812                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9813       if (!Final.isUsable()) {
9814         HasErrors = true;
9815         break;
9816       }
9817 
9818       if (!Update.isUsable() || !Final.isUsable()) {
9819         HasErrors = true;
9820         break;
9821       }
9822       // Save results
9823       Built.Counters[Cnt] = IS.CounterVar;
9824       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9825       Built.Inits[Cnt] = Init.get();
9826       Built.Updates[Cnt] = Update.get();
9827       Built.Finals[Cnt] = Final.get();
9828       Built.DependentCounters[Cnt] = nullptr;
9829       Built.DependentInits[Cnt] = nullptr;
9830       Built.FinalsConditions[Cnt] = nullptr;
9831       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9832         Built.DependentCounters[Cnt] =
9833             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9834         Built.DependentInits[Cnt] =
9835             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9836         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9837       }
9838     }
9839   }
9840 
9841   if (HasErrors)
9842     return 0;
9843 
9844   // Save results
9845   Built.IterationVarRef = IV.get();
9846   Built.LastIteration = LastIteration.get();
9847   Built.NumIterations = NumIterations.get();
9848   Built.CalcLastIteration = SemaRef
9849                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9850                                                      /*DiscardedValue=*/false)
9851                                 .get();
9852   Built.PreCond = PreCond.get();
9853   Built.PreInits = buildPreInits(C, Captures);
9854   Built.Cond = Cond.get();
9855   Built.Init = Init.get();
9856   Built.Inc = Inc.get();
9857   Built.LB = LB.get();
9858   Built.UB = UB.get();
9859   Built.IL = IL.get();
9860   Built.ST = ST.get();
9861   Built.EUB = EUB.get();
9862   Built.NLB = NextLB.get();
9863   Built.NUB = NextUB.get();
9864   Built.PrevLB = PrevLB.get();
9865   Built.PrevUB = PrevUB.get();
9866   Built.DistInc = DistInc.get();
9867   Built.PrevEUB = PrevEUB.get();
9868   Built.DistCombinedFields.LB = CombLB.get();
9869   Built.DistCombinedFields.UB = CombUB.get();
9870   Built.DistCombinedFields.EUB = CombEUB.get();
9871   Built.DistCombinedFields.Init = CombInit.get();
9872   Built.DistCombinedFields.Cond = CombCond.get();
9873   Built.DistCombinedFields.NLB = CombNextLB.get();
9874   Built.DistCombinedFields.NUB = CombNextUB.get();
9875   Built.DistCombinedFields.DistCond = CombDistCond.get();
9876   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9877 
9878   return NestedLoopCount;
9879 }
9880 
9881 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9882   auto CollapseClauses =
9883       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9884   if (CollapseClauses.begin() != CollapseClauses.end())
9885     return (*CollapseClauses.begin())->getNumForLoops();
9886   return nullptr;
9887 }
9888 
9889 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9890   auto OrderedClauses =
9891       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9892   if (OrderedClauses.begin() != OrderedClauses.end())
9893     return (*OrderedClauses.begin())->getNumForLoops();
9894   return nullptr;
9895 }
9896 
9897 static bool checkSimdlenSafelenSpecified(Sema &S,
9898                                          const ArrayRef<OMPClause *> Clauses) {
9899   const OMPSafelenClause *Safelen = nullptr;
9900   const OMPSimdlenClause *Simdlen = nullptr;
9901 
9902   for (const OMPClause *Clause : Clauses) {
9903     if (Clause->getClauseKind() == OMPC_safelen)
9904       Safelen = cast<OMPSafelenClause>(Clause);
9905     else if (Clause->getClauseKind() == OMPC_simdlen)
9906       Simdlen = cast<OMPSimdlenClause>(Clause);
9907     if (Safelen && Simdlen)
9908       break;
9909   }
9910 
9911   if (Simdlen && Safelen) {
9912     const Expr *SimdlenLength = Simdlen->getSimdlen();
9913     const Expr *SafelenLength = Safelen->getSafelen();
9914     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9915         SimdlenLength->isInstantiationDependent() ||
9916         SimdlenLength->containsUnexpandedParameterPack())
9917       return false;
9918     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9919         SafelenLength->isInstantiationDependent() ||
9920         SafelenLength->containsUnexpandedParameterPack())
9921       return false;
9922     Expr::EvalResult SimdlenResult, SafelenResult;
9923     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9924     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9925     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9926     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9927     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9928     // If both simdlen and safelen clauses are specified, the value of the
9929     // simdlen parameter must be less than or equal to the value of the safelen
9930     // parameter.
9931     if (SimdlenRes > SafelenRes) {
9932       S.Diag(SimdlenLength->getExprLoc(),
9933              diag::err_omp_wrong_simdlen_safelen_values)
9934           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9935       return true;
9936     }
9937   }
9938   return false;
9939 }
9940 
9941 StmtResult
9942 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9943                                SourceLocation StartLoc, SourceLocation EndLoc,
9944                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9945   if (!AStmt)
9946     return StmtError();
9947 
9948   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9949   OMPLoopBasedDirective::HelperExprs B;
9950   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9951   // define the nested loops number.
9952   unsigned NestedLoopCount = checkOpenMPLoop(
9953       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9954       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9955   if (NestedLoopCount == 0)
9956     return StmtError();
9957 
9958   assert((CurContext->isDependentContext() || B.builtAll()) &&
9959          "omp simd loop exprs were not built");
9960 
9961   if (!CurContext->isDependentContext()) {
9962     // Finalize the clauses that need pre-built expressions for CodeGen.
9963     for (OMPClause *C : Clauses) {
9964       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9965         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9966                                      B.NumIterations, *this, CurScope,
9967                                      DSAStack))
9968           return StmtError();
9969     }
9970   }
9971 
9972   if (checkSimdlenSafelenSpecified(*this, Clauses))
9973     return StmtError();
9974 
9975   setFunctionHasBranchProtectedScope();
9976   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9977                                   Clauses, AStmt, B);
9978 }
9979 
9980 StmtResult
9981 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9982                               SourceLocation StartLoc, SourceLocation EndLoc,
9983                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9984   if (!AStmt)
9985     return StmtError();
9986 
9987   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9988   OMPLoopBasedDirective::HelperExprs B;
9989   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9990   // define the nested loops number.
9991   unsigned NestedLoopCount = checkOpenMPLoop(
9992       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9993       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9994   if (NestedLoopCount == 0)
9995     return StmtError();
9996 
9997   assert((CurContext->isDependentContext() || B.builtAll()) &&
9998          "omp for loop exprs were not built");
9999 
10000   if (!CurContext->isDependentContext()) {
10001     // Finalize the clauses that need pre-built expressions for CodeGen.
10002     for (OMPClause *C : Clauses) {
10003       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10004         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10005                                      B.NumIterations, *this, CurScope,
10006                                      DSAStack))
10007           return StmtError();
10008     }
10009   }
10010 
10011   setFunctionHasBranchProtectedScope();
10012   return OMPForDirective::Create(
10013       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10014       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10015 }
10016 
10017 StmtResult Sema::ActOnOpenMPForSimdDirective(
10018     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10019     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10020   if (!AStmt)
10021     return StmtError();
10022 
10023   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10024   OMPLoopBasedDirective::HelperExprs B;
10025   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10026   // define the nested loops number.
10027   unsigned NestedLoopCount =
10028       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
10029                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10030                       VarsWithImplicitDSA, B);
10031   if (NestedLoopCount == 0)
10032     return StmtError();
10033 
10034   assert((CurContext->isDependentContext() || B.builtAll()) &&
10035          "omp for simd loop exprs were not built");
10036 
10037   if (!CurContext->isDependentContext()) {
10038     // Finalize the clauses that need pre-built expressions for CodeGen.
10039     for (OMPClause *C : Clauses) {
10040       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10041         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10042                                      B.NumIterations, *this, CurScope,
10043                                      DSAStack))
10044           return StmtError();
10045     }
10046   }
10047 
10048   if (checkSimdlenSafelenSpecified(*this, Clauses))
10049     return StmtError();
10050 
10051   setFunctionHasBranchProtectedScope();
10052   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
10053                                      Clauses, AStmt, B);
10054 }
10055 
10056 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10057                                               Stmt *AStmt,
10058                                               SourceLocation StartLoc,
10059                                               SourceLocation EndLoc) {
10060   if (!AStmt)
10061     return StmtError();
10062 
10063   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10064   auto BaseStmt = AStmt;
10065   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10066     BaseStmt = CS->getCapturedStmt();
10067   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10068     auto S = C->children();
10069     if (S.begin() == S.end())
10070       return StmtError();
10071     // All associated statements must be '#pragma omp section' except for
10072     // the first one.
10073     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10074       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10075         if (SectionStmt)
10076           Diag(SectionStmt->getBeginLoc(),
10077                diag::err_omp_sections_substmt_not_section);
10078         return StmtError();
10079       }
10080       cast<OMPSectionDirective>(SectionStmt)
10081           ->setHasCancel(DSAStack->isCancelRegion());
10082     }
10083   } else {
10084     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
10085     return StmtError();
10086   }
10087 
10088   setFunctionHasBranchProtectedScope();
10089 
10090   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10091                                       DSAStack->getTaskgroupReductionRef(),
10092                                       DSAStack->isCancelRegion());
10093 }
10094 
10095 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
10096                                              SourceLocation StartLoc,
10097                                              SourceLocation EndLoc) {
10098   if (!AStmt)
10099     return StmtError();
10100 
10101   setFunctionHasBranchProtectedScope();
10102   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
10103 
10104   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
10105                                      DSAStack->isCancelRegion());
10106 }
10107 
10108 static Expr *getDirectCallExpr(Expr *E) {
10109   E = E->IgnoreParenCasts()->IgnoreImplicit();
10110   if (auto *CE = dyn_cast<CallExpr>(E))
10111     if (CE->getDirectCallee())
10112       return E;
10113   return nullptr;
10114 }
10115 
10116 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10117                                               Stmt *AStmt,
10118                                               SourceLocation StartLoc,
10119                                               SourceLocation EndLoc) {
10120   if (!AStmt)
10121     return StmtError();
10122 
10123   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
10124 
10125   // 5.1 OpenMP
10126   // expression-stmt : an expression statement with one of the following forms:
10127   //   expression = target-call ( [expression-list] );
10128   //   target-call ( [expression-list] );
10129 
10130   SourceLocation TargetCallLoc;
10131 
10132   if (!CurContext->isDependentContext()) {
10133     Expr *TargetCall = nullptr;
10134 
10135     auto *E = dyn_cast<Expr>(S);
10136     if (!E) {
10137       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10138       return StmtError();
10139     }
10140 
10141     E = E->IgnoreParenCasts()->IgnoreImplicit();
10142 
10143     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
10144       if (BO->getOpcode() == BO_Assign)
10145         TargetCall = getDirectCallExpr(BO->getRHS());
10146     } else {
10147       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
10148         if (COCE->getOperator() == OO_Equal)
10149           TargetCall = getDirectCallExpr(COCE->getArg(1));
10150       if (!TargetCall)
10151         TargetCall = getDirectCallExpr(E);
10152     }
10153     if (!TargetCall) {
10154       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10155       return StmtError();
10156     }
10157     TargetCallLoc = TargetCall->getExprLoc();
10158   }
10159 
10160   setFunctionHasBranchProtectedScope();
10161 
10162   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10163                                       TargetCallLoc);
10164 }
10165 
10166 static bool checkGenericLoopLastprivate(Sema &S, ArrayRef<OMPClause *> Clauses,
10167                                         OpenMPDirectiveKind K,
10168                                         DSAStackTy *Stack) {
10169   bool ErrorFound = false;
10170   for (OMPClause *C : Clauses) {
10171     if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
10172       for (Expr *RefExpr : LPC->varlists()) {
10173         SourceLocation ELoc;
10174         SourceRange ERange;
10175         Expr *SimpleRefExpr = RefExpr;
10176         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
10177         if (ValueDecl *D = Res.first) {
10178           auto &&Info = Stack->isLoopControlVariable(D);
10179           if (!Info.first) {
10180             S.Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration)
10181                 << getOpenMPDirectiveName(K);
10182             ErrorFound = true;
10183           }
10184         }
10185       }
10186     }
10187   }
10188   return ErrorFound;
10189 }
10190 
10191 StmtResult Sema::ActOnOpenMPGenericLoopDirective(
10192     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10193     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10194   if (!AStmt)
10195     return StmtError();
10196 
10197   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10198   // A list item may not appear in a lastprivate clause unless it is the
10199   // loop iteration variable of a loop that is associated with the construct.
10200   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_loop, DSAStack))
10201     return StmtError();
10202 
10203   auto *CS = cast<CapturedStmt>(AStmt);
10204   // 1.2.2 OpenMP Language Terminology
10205   // Structured block - An executable statement with a single entry at the
10206   // top and a single exit at the bottom.
10207   // The point of exit cannot be a branch out of the structured block.
10208   // longjmp() and throw() must not violate the entry/exit criteria.
10209   CS->getCapturedDecl()->setNothrow();
10210 
10211   OMPLoopDirective::HelperExprs B;
10212   // In presence of clause 'collapse', it will define the nested loops number.
10213   unsigned NestedLoopCount = checkOpenMPLoop(
10214       OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10215       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10216   if (NestedLoopCount == 0)
10217     return StmtError();
10218 
10219   assert((CurContext->isDependentContext() || B.builtAll()) &&
10220          "omp loop exprs were not built");
10221 
10222   setFunctionHasBranchProtectedScope();
10223   return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
10224                                          NestedLoopCount, Clauses, AStmt, B);
10225 }
10226 
10227 StmtResult Sema::ActOnOpenMPTeamsGenericLoopDirective(
10228     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10229     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10230   if (!AStmt)
10231     return StmtError();
10232 
10233   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10234   // A list item may not appear in a lastprivate clause unless it is the
10235   // loop iteration variable of a loop that is associated with the construct.
10236   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_teams_loop, DSAStack))
10237     return StmtError();
10238 
10239   auto *CS = cast<CapturedStmt>(AStmt);
10240   // 1.2.2 OpenMP Language Terminology
10241   // Structured block - An executable statement with a single entry at the
10242   // top and a single exit at the bottom.
10243   // The point of exit cannot be a branch out of the structured block.
10244   // longjmp() and throw() must not violate the entry/exit criteria.
10245   CS->getCapturedDecl()->setNothrow();
10246   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_loop);
10247        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10248     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10249     // 1.2.2 OpenMP Language Terminology
10250     // Structured block - An executable statement with a single entry at the
10251     // top and a single exit at the bottom.
10252     // The point of exit cannot be a branch out of the structured block.
10253     // longjmp() and throw() must not violate the entry/exit criteria.
10254     CS->getCapturedDecl()->setNothrow();
10255   }
10256 
10257   OMPLoopDirective::HelperExprs B;
10258   // In presence of clause 'collapse', it will define the nested loops number.
10259   unsigned NestedLoopCount =
10260       checkOpenMPLoop(OMPD_teams_loop, getCollapseNumberExpr(Clauses),
10261                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10262                       VarsWithImplicitDSA, B);
10263   if (NestedLoopCount == 0)
10264     return StmtError();
10265 
10266   assert((CurContext->isDependentContext() || B.builtAll()) &&
10267          "omp loop exprs were not built");
10268 
10269   setFunctionHasBranchProtectedScope();
10270   DSAStack->setParentTeamsRegionLoc(StartLoc);
10271 
10272   return OMPTeamsGenericLoopDirective::Create(
10273       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10274 }
10275 
10276 StmtResult Sema::ActOnOpenMPTargetTeamsGenericLoopDirective(
10277     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10278     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10279   if (!AStmt)
10280     return StmtError();
10281 
10282   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10283   // A list item may not appear in a lastprivate clause unless it is the
10284   // loop iteration variable of a loop that is associated with the construct.
10285   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_teams_loop,
10286                                   DSAStack))
10287     return StmtError();
10288 
10289   auto *CS = cast<CapturedStmt>(AStmt);
10290   // 1.2.2 OpenMP Language Terminology
10291   // Structured block - An executable statement with a single entry at the
10292   // top and a single exit at the bottom.
10293   // The point of exit cannot be a branch out of the structured block.
10294   // longjmp() and throw() must not violate the entry/exit criteria.
10295   CS->getCapturedDecl()->setNothrow();
10296   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams_loop);
10297        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10298     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10299     // 1.2.2 OpenMP Language Terminology
10300     // Structured block - An executable statement with a single entry at the
10301     // top and a single exit at the bottom.
10302     // The point of exit cannot be a branch out of the structured block.
10303     // longjmp() and throw() must not violate the entry/exit criteria.
10304     CS->getCapturedDecl()->setNothrow();
10305   }
10306 
10307   OMPLoopDirective::HelperExprs B;
10308   // In presence of clause 'collapse', it will define the nested loops number.
10309   unsigned NestedLoopCount =
10310       checkOpenMPLoop(OMPD_target_teams_loop, getCollapseNumberExpr(Clauses),
10311                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10312                       VarsWithImplicitDSA, B);
10313   if (NestedLoopCount == 0)
10314     return StmtError();
10315 
10316   assert((CurContext->isDependentContext() || B.builtAll()) &&
10317          "omp loop exprs were not built");
10318 
10319   setFunctionHasBranchProtectedScope();
10320 
10321   return OMPTargetTeamsGenericLoopDirective::Create(
10322       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10323 }
10324 
10325 StmtResult Sema::ActOnOpenMPParallelGenericLoopDirective(
10326     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10327     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10328   if (!AStmt)
10329     return StmtError();
10330 
10331   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10332   // A list item may not appear in a lastprivate clause unless it is the
10333   // loop iteration variable of a loop that is associated with the construct.
10334   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_parallel_loop, DSAStack))
10335     return StmtError();
10336 
10337   auto *CS = cast<CapturedStmt>(AStmt);
10338   // 1.2.2 OpenMP Language Terminology
10339   // Structured block - An executable statement with a single entry at the
10340   // top and a single exit at the bottom.
10341   // The point of exit cannot be a branch out of the structured block.
10342   // longjmp() and throw() must not violate the entry/exit criteria.
10343   CS->getCapturedDecl()->setNothrow();
10344   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_parallel_loop);
10345        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10346     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10347     // 1.2.2 OpenMP Language Terminology
10348     // Structured block - An executable statement with a single entry at the
10349     // top and a single exit at the bottom.
10350     // The point of exit cannot be a branch out of the structured block.
10351     // longjmp() and throw() must not violate the entry/exit criteria.
10352     CS->getCapturedDecl()->setNothrow();
10353   }
10354 
10355   OMPLoopDirective::HelperExprs B;
10356   // In presence of clause 'collapse', it will define the nested loops number.
10357   unsigned NestedLoopCount =
10358       checkOpenMPLoop(OMPD_parallel_loop, getCollapseNumberExpr(Clauses),
10359                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10360                       VarsWithImplicitDSA, B);
10361   if (NestedLoopCount == 0)
10362     return StmtError();
10363 
10364   assert((CurContext->isDependentContext() || B.builtAll()) &&
10365          "omp loop exprs were not built");
10366 
10367   setFunctionHasBranchProtectedScope();
10368 
10369   return OMPParallelGenericLoopDirective::Create(
10370       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10371 }
10372 
10373 StmtResult Sema::ActOnOpenMPTargetParallelGenericLoopDirective(
10374     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10375     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10376   if (!AStmt)
10377     return StmtError();
10378 
10379   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10380   // A list item may not appear in a lastprivate clause unless it is the
10381   // loop iteration variable of a loop that is associated with the construct.
10382   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_parallel_loop,
10383                                   DSAStack))
10384     return StmtError();
10385 
10386   auto *CS = cast<CapturedStmt>(AStmt);
10387   // 1.2.2 OpenMP Language Terminology
10388   // Structured block - An executable statement with a single entry at the
10389   // top and a single exit at the bottom.
10390   // The point of exit cannot be a branch out of the structured block.
10391   // longjmp() and throw() must not violate the entry/exit criteria.
10392   CS->getCapturedDecl()->setNothrow();
10393   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_loop);
10394        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10395     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10396     // 1.2.2 OpenMP Language Terminology
10397     // Structured block - An executable statement with a single entry at the
10398     // top and a single exit at the bottom.
10399     // The point of exit cannot be a branch out of the structured block.
10400     // longjmp() and throw() must not violate the entry/exit criteria.
10401     CS->getCapturedDecl()->setNothrow();
10402   }
10403 
10404   OMPLoopDirective::HelperExprs B;
10405   // In presence of clause 'collapse', it will define the nested loops number.
10406   unsigned NestedLoopCount =
10407       checkOpenMPLoop(OMPD_target_parallel_loop, getCollapseNumberExpr(Clauses),
10408                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10409                       VarsWithImplicitDSA, B);
10410   if (NestedLoopCount == 0)
10411     return StmtError();
10412 
10413   assert((CurContext->isDependentContext() || B.builtAll()) &&
10414          "omp loop exprs were not built");
10415 
10416   setFunctionHasBranchProtectedScope();
10417 
10418   return OMPTargetParallelGenericLoopDirective::Create(
10419       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10420 }
10421 
10422 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10423                                             Stmt *AStmt,
10424                                             SourceLocation StartLoc,
10425                                             SourceLocation EndLoc) {
10426   if (!AStmt)
10427     return StmtError();
10428 
10429   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10430 
10431   setFunctionHasBranchProtectedScope();
10432 
10433   // OpenMP [2.7.3, single Construct, Restrictions]
10434   // The copyprivate clause must not be used with the nowait clause.
10435   const OMPClause *Nowait = nullptr;
10436   const OMPClause *Copyprivate = nullptr;
10437   for (const OMPClause *Clause : Clauses) {
10438     if (Clause->getClauseKind() == OMPC_nowait)
10439       Nowait = Clause;
10440     else if (Clause->getClauseKind() == OMPC_copyprivate)
10441       Copyprivate = Clause;
10442     if (Copyprivate && Nowait) {
10443       Diag(Copyprivate->getBeginLoc(),
10444            diag::err_omp_single_copyprivate_with_nowait);
10445       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
10446       return StmtError();
10447     }
10448   }
10449 
10450   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10451 }
10452 
10453 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
10454                                             SourceLocation StartLoc,
10455                                             SourceLocation EndLoc) {
10456   if (!AStmt)
10457     return StmtError();
10458 
10459   setFunctionHasBranchProtectedScope();
10460 
10461   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
10462 }
10463 
10464 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10465                                             Stmt *AStmt,
10466                                             SourceLocation StartLoc,
10467                                             SourceLocation EndLoc) {
10468   if (!AStmt)
10469     return StmtError();
10470 
10471   setFunctionHasBranchProtectedScope();
10472 
10473   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10474 }
10475 
10476 StmtResult Sema::ActOnOpenMPCriticalDirective(
10477     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
10478     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
10479   if (!AStmt)
10480     return StmtError();
10481 
10482   bool ErrorFound = false;
10483   llvm::APSInt Hint;
10484   SourceLocation HintLoc;
10485   bool DependentHint = false;
10486   for (const OMPClause *C : Clauses) {
10487     if (C->getClauseKind() == OMPC_hint) {
10488       if (!DirName.getName()) {
10489         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
10490         ErrorFound = true;
10491       }
10492       Expr *E = cast<OMPHintClause>(C)->getHint();
10493       if (E->isTypeDependent() || E->isValueDependent() ||
10494           E->isInstantiationDependent()) {
10495         DependentHint = true;
10496       } else {
10497         Hint = E->EvaluateKnownConstInt(Context);
10498         HintLoc = C->getBeginLoc();
10499       }
10500     }
10501   }
10502   if (ErrorFound)
10503     return StmtError();
10504   const auto Pair = DSAStack->getCriticalWithHint(DirName);
10505   if (Pair.first && DirName.getName() && !DependentHint) {
10506     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
10507       Diag(StartLoc, diag::err_omp_critical_with_hint);
10508       if (HintLoc.isValid())
10509         Diag(HintLoc, diag::note_omp_critical_hint_here)
10510             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
10511       else
10512         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10513       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10514         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10515             << 1
10516             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10517                         /*Radix=*/10, /*Signed=*/false);
10518       } else {
10519         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10520       }
10521     }
10522   }
10523 
10524   setFunctionHasBranchProtectedScope();
10525 
10526   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10527                                            Clauses, AStmt);
10528   if (!Pair.first && DirName.getName() && !DependentHint)
10529     DSAStack->addCriticalWithHint(Dir, Hint);
10530   return Dir;
10531 }
10532 
10533 StmtResult Sema::ActOnOpenMPParallelForDirective(
10534     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10535     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10536   if (!AStmt)
10537     return StmtError();
10538 
10539   auto *CS = cast<CapturedStmt>(AStmt);
10540   // 1.2.2 OpenMP Language Terminology
10541   // Structured block - An executable statement with a single entry at the
10542   // top and a single exit at the bottom.
10543   // The point of exit cannot be a branch out of the structured block.
10544   // longjmp() and throw() must not violate the entry/exit criteria.
10545   CS->getCapturedDecl()->setNothrow();
10546 
10547   OMPLoopBasedDirective::HelperExprs B;
10548   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10549   // define the nested loops number.
10550   unsigned NestedLoopCount =
10551       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10552                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10553                       VarsWithImplicitDSA, B);
10554   if (NestedLoopCount == 0)
10555     return StmtError();
10556 
10557   assert((CurContext->isDependentContext() || B.builtAll()) &&
10558          "omp parallel for loop exprs were not built");
10559 
10560   if (!CurContext->isDependentContext()) {
10561     // Finalize the clauses that need pre-built expressions for CodeGen.
10562     for (OMPClause *C : Clauses) {
10563       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10564         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10565                                      B.NumIterations, *this, CurScope,
10566                                      DSAStack))
10567           return StmtError();
10568     }
10569   }
10570 
10571   setFunctionHasBranchProtectedScope();
10572   return OMPParallelForDirective::Create(
10573       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10574       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10575 }
10576 
10577 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10578     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10579     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10580   if (!AStmt)
10581     return StmtError();
10582 
10583   auto *CS = cast<CapturedStmt>(AStmt);
10584   // 1.2.2 OpenMP Language Terminology
10585   // Structured block - An executable statement with a single entry at the
10586   // top and a single exit at the bottom.
10587   // The point of exit cannot be a branch out of the structured block.
10588   // longjmp() and throw() must not violate the entry/exit criteria.
10589   CS->getCapturedDecl()->setNothrow();
10590 
10591   OMPLoopBasedDirective::HelperExprs B;
10592   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10593   // define the nested loops number.
10594   unsigned NestedLoopCount =
10595       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10596                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10597                       VarsWithImplicitDSA, B);
10598   if (NestedLoopCount == 0)
10599     return StmtError();
10600 
10601   if (!CurContext->isDependentContext()) {
10602     // Finalize the clauses that need pre-built expressions for CodeGen.
10603     for (OMPClause *C : Clauses) {
10604       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10605         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10606                                      B.NumIterations, *this, CurScope,
10607                                      DSAStack))
10608           return StmtError();
10609     }
10610   }
10611 
10612   if (checkSimdlenSafelenSpecified(*this, Clauses))
10613     return StmtError();
10614 
10615   setFunctionHasBranchProtectedScope();
10616   return OMPParallelForSimdDirective::Create(
10617       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10618 }
10619 
10620 StmtResult
10621 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10622                                          Stmt *AStmt, SourceLocation StartLoc,
10623                                          SourceLocation EndLoc) {
10624   if (!AStmt)
10625     return StmtError();
10626 
10627   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10628   auto *CS = cast<CapturedStmt>(AStmt);
10629   // 1.2.2 OpenMP Language Terminology
10630   // Structured block - An executable statement with a single entry at the
10631   // top and a single exit at the bottom.
10632   // The point of exit cannot be a branch out of the structured block.
10633   // longjmp() and throw() must not violate the entry/exit criteria.
10634   CS->getCapturedDecl()->setNothrow();
10635 
10636   setFunctionHasBranchProtectedScope();
10637 
10638   return OMPParallelMasterDirective::Create(
10639       Context, StartLoc, EndLoc, Clauses, AStmt,
10640       DSAStack->getTaskgroupReductionRef());
10641 }
10642 
10643 StmtResult
10644 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10645                                            Stmt *AStmt, SourceLocation StartLoc,
10646                                            SourceLocation EndLoc) {
10647   if (!AStmt)
10648     return StmtError();
10649 
10650   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10651   auto BaseStmt = AStmt;
10652   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10653     BaseStmt = CS->getCapturedStmt();
10654   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10655     auto S = C->children();
10656     if (S.begin() == S.end())
10657       return StmtError();
10658     // All associated statements must be '#pragma omp section' except for
10659     // the first one.
10660     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10661       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10662         if (SectionStmt)
10663           Diag(SectionStmt->getBeginLoc(),
10664                diag::err_omp_parallel_sections_substmt_not_section);
10665         return StmtError();
10666       }
10667       cast<OMPSectionDirective>(SectionStmt)
10668           ->setHasCancel(DSAStack->isCancelRegion());
10669     }
10670   } else {
10671     Diag(AStmt->getBeginLoc(),
10672          diag::err_omp_parallel_sections_not_compound_stmt);
10673     return StmtError();
10674   }
10675 
10676   setFunctionHasBranchProtectedScope();
10677 
10678   return OMPParallelSectionsDirective::Create(
10679       Context, StartLoc, EndLoc, Clauses, AStmt,
10680       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10681 }
10682 
10683 /// Find and diagnose mutually exclusive clause kinds.
10684 static bool checkMutuallyExclusiveClauses(
10685     Sema &S, ArrayRef<OMPClause *> Clauses,
10686     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10687   const OMPClause *PrevClause = nullptr;
10688   bool ErrorFound = false;
10689   for (const OMPClause *C : Clauses) {
10690     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10691       if (!PrevClause) {
10692         PrevClause = C;
10693       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10694         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10695             << getOpenMPClauseName(C->getClauseKind())
10696             << getOpenMPClauseName(PrevClause->getClauseKind());
10697         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10698             << getOpenMPClauseName(PrevClause->getClauseKind());
10699         ErrorFound = true;
10700       }
10701     }
10702   }
10703   return ErrorFound;
10704 }
10705 
10706 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10707                                           Stmt *AStmt, SourceLocation StartLoc,
10708                                           SourceLocation EndLoc) {
10709   if (!AStmt)
10710     return StmtError();
10711 
10712   // OpenMP 5.0, 2.10.1 task Construct
10713   // If a detach clause appears on the directive, then a mergeable clause cannot
10714   // appear on the same directive.
10715   if (checkMutuallyExclusiveClauses(*this, Clauses,
10716                                     {OMPC_detach, OMPC_mergeable}))
10717     return StmtError();
10718 
10719   auto *CS = cast<CapturedStmt>(AStmt);
10720   // 1.2.2 OpenMP Language Terminology
10721   // Structured block - An executable statement with a single entry at the
10722   // top and a single exit at the bottom.
10723   // The point of exit cannot be a branch out of the structured block.
10724   // longjmp() and throw() must not violate the entry/exit criteria.
10725   CS->getCapturedDecl()->setNothrow();
10726 
10727   setFunctionHasBranchProtectedScope();
10728 
10729   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10730                                   DSAStack->isCancelRegion());
10731 }
10732 
10733 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10734                                                SourceLocation EndLoc) {
10735   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10736 }
10737 
10738 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10739                                              SourceLocation EndLoc) {
10740   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10741 }
10742 
10743 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10744                                               SourceLocation StartLoc,
10745                                               SourceLocation EndLoc) {
10746   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
10747 }
10748 
10749 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10750                                                Stmt *AStmt,
10751                                                SourceLocation StartLoc,
10752                                                SourceLocation EndLoc) {
10753   if (!AStmt)
10754     return StmtError();
10755 
10756   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10757 
10758   setFunctionHasBranchProtectedScope();
10759 
10760   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10761                                        AStmt,
10762                                        DSAStack->getTaskgroupReductionRef());
10763 }
10764 
10765 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10766                                            SourceLocation StartLoc,
10767                                            SourceLocation EndLoc) {
10768   OMPFlushClause *FC = nullptr;
10769   OMPClause *OrderClause = nullptr;
10770   for (OMPClause *C : Clauses) {
10771     if (C->getClauseKind() == OMPC_flush)
10772       FC = cast<OMPFlushClause>(C);
10773     else
10774       OrderClause = C;
10775   }
10776   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10777   SourceLocation MemOrderLoc;
10778   for (const OMPClause *C : Clauses) {
10779     if (C->getClauseKind() == OMPC_acq_rel ||
10780         C->getClauseKind() == OMPC_acquire ||
10781         C->getClauseKind() == OMPC_release) {
10782       if (MemOrderKind != OMPC_unknown) {
10783         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10784             << getOpenMPDirectiveName(OMPD_flush) << 1
10785             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10786         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10787             << getOpenMPClauseName(MemOrderKind);
10788       } else {
10789         MemOrderKind = C->getClauseKind();
10790         MemOrderLoc = C->getBeginLoc();
10791       }
10792     }
10793   }
10794   if (FC && OrderClause) {
10795     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10796         << getOpenMPClauseName(OrderClause->getClauseKind());
10797     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10798         << getOpenMPClauseName(OrderClause->getClauseKind());
10799     return StmtError();
10800   }
10801   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10802 }
10803 
10804 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10805                                             SourceLocation StartLoc,
10806                                             SourceLocation EndLoc) {
10807   if (Clauses.empty()) {
10808     Diag(StartLoc, diag::err_omp_depobj_expected);
10809     return StmtError();
10810   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10811     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10812     return StmtError();
10813   }
10814   // Only depobj expression and another single clause is allowed.
10815   if (Clauses.size() > 2) {
10816     Diag(Clauses[2]->getBeginLoc(),
10817          diag::err_omp_depobj_single_clause_expected);
10818     return StmtError();
10819   } else if (Clauses.size() < 1) {
10820     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10821     return StmtError();
10822   }
10823   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10824 }
10825 
10826 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10827                                           SourceLocation StartLoc,
10828                                           SourceLocation EndLoc) {
10829   // Check that exactly one clause is specified.
10830   if (Clauses.size() != 1) {
10831     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10832          diag::err_omp_scan_single_clause_expected);
10833     return StmtError();
10834   }
10835   // Check that scan directive is used in the scopeof the OpenMP loop body.
10836   if (Scope *S = DSAStack->getCurScope()) {
10837     Scope *ParentS = S->getParent();
10838     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10839         !ParentS->getBreakParent()->isOpenMPLoopScope())
10840       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10841                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10842   }
10843   // Check that only one instance of scan directives is used in the same outer
10844   // region.
10845   if (DSAStack->doesParentHasScanDirective()) {
10846     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10847     Diag(DSAStack->getParentScanDirectiveLoc(),
10848          diag::note_omp_previous_directive)
10849         << "scan";
10850     return StmtError();
10851   }
10852   DSAStack->setParentHasScanDirective(StartLoc);
10853   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10854 }
10855 
10856 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10857                                              Stmt *AStmt,
10858                                              SourceLocation StartLoc,
10859                                              SourceLocation EndLoc) {
10860   const OMPClause *DependFound = nullptr;
10861   const OMPClause *DependSourceClause = nullptr;
10862   const OMPClause *DependSinkClause = nullptr;
10863   bool ErrorFound = false;
10864   const OMPThreadsClause *TC = nullptr;
10865   const OMPSIMDClause *SC = nullptr;
10866   for (const OMPClause *C : Clauses) {
10867     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10868       DependFound = C;
10869       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10870         if (DependSourceClause) {
10871           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10872               << getOpenMPDirectiveName(OMPD_ordered)
10873               << getOpenMPClauseName(OMPC_depend) << 2;
10874           ErrorFound = true;
10875         } else {
10876           DependSourceClause = C;
10877         }
10878         if (DependSinkClause) {
10879           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10880               << 0;
10881           ErrorFound = true;
10882         }
10883       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10884         if (DependSourceClause) {
10885           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10886               << 1;
10887           ErrorFound = true;
10888         }
10889         DependSinkClause = C;
10890       }
10891     } else if (C->getClauseKind() == OMPC_threads) {
10892       TC = cast<OMPThreadsClause>(C);
10893     } else if (C->getClauseKind() == OMPC_simd) {
10894       SC = cast<OMPSIMDClause>(C);
10895     }
10896   }
10897   if (!ErrorFound && !SC &&
10898       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10899     // OpenMP [2.8.1,simd Construct, Restrictions]
10900     // An ordered construct with the simd clause is the only OpenMP construct
10901     // that can appear in the simd region.
10902     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10903         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10904     ErrorFound = true;
10905   } else if (DependFound && (TC || SC)) {
10906     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10907         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10908     ErrorFound = true;
10909   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10910     Diag(DependFound->getBeginLoc(),
10911          diag::err_omp_ordered_directive_without_param);
10912     ErrorFound = true;
10913   } else if (TC || Clauses.empty()) {
10914     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10915       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10916       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10917           << (TC != nullptr);
10918       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10919       ErrorFound = true;
10920     }
10921   }
10922   if ((!AStmt && !DependFound) || ErrorFound)
10923     return StmtError();
10924 
10925   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10926   // During execution of an iteration of a worksharing-loop or a loop nest
10927   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10928   // must not execute more than one ordered region corresponding to an ordered
10929   // construct without a depend clause.
10930   if (!DependFound) {
10931     if (DSAStack->doesParentHasOrderedDirective()) {
10932       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10933       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10934            diag::note_omp_previous_directive)
10935           << "ordered";
10936       return StmtError();
10937     }
10938     DSAStack->setParentHasOrderedDirective(StartLoc);
10939   }
10940 
10941   if (AStmt) {
10942     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10943 
10944     setFunctionHasBranchProtectedScope();
10945   }
10946 
10947   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10948 }
10949 
10950 namespace {
10951 /// Helper class for checking expression in 'omp atomic [update]'
10952 /// construct.
10953 class OpenMPAtomicUpdateChecker {
10954   /// Error results for atomic update expressions.
10955   enum ExprAnalysisErrorCode {
10956     /// A statement is not an expression statement.
10957     NotAnExpression,
10958     /// Expression is not builtin binary or unary operation.
10959     NotABinaryOrUnaryExpression,
10960     /// Unary operation is not post-/pre- increment/decrement operation.
10961     NotAnUnaryIncDecExpression,
10962     /// An expression is not of scalar type.
10963     NotAScalarType,
10964     /// A binary operation is not an assignment operation.
10965     NotAnAssignmentOp,
10966     /// RHS part of the binary operation is not a binary expression.
10967     NotABinaryExpression,
10968     /// RHS part is not additive/multiplicative/shift/biwise binary
10969     /// expression.
10970     NotABinaryOperator,
10971     /// RHS binary operation does not have reference to the updated LHS
10972     /// part.
10973     NotAnUpdateExpression,
10974     /// No errors is found.
10975     NoError
10976   };
10977   /// Reference to Sema.
10978   Sema &SemaRef;
10979   /// A location for note diagnostics (when error is found).
10980   SourceLocation NoteLoc;
10981   /// 'x' lvalue part of the source atomic expression.
10982   Expr *X;
10983   /// 'expr' rvalue part of the source atomic expression.
10984   Expr *E;
10985   /// Helper expression of the form
10986   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10987   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10988   Expr *UpdateExpr;
10989   /// Is 'x' a LHS in a RHS part of full update expression. It is
10990   /// important for non-associative operations.
10991   bool IsXLHSInRHSPart;
10992   BinaryOperatorKind Op;
10993   SourceLocation OpLoc;
10994   /// true if the source expression is a postfix unary operation, false
10995   /// if it is a prefix unary operation.
10996   bool IsPostfixUpdate;
10997 
10998 public:
10999   OpenMPAtomicUpdateChecker(Sema &SemaRef)
11000       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
11001         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
11002   /// Check specified statement that it is suitable for 'atomic update'
11003   /// constructs and extract 'x', 'expr' and Operation from the original
11004   /// expression. If DiagId and NoteId == 0, then only check is performed
11005   /// without error notification.
11006   /// \param DiagId Diagnostic which should be emitted if error is found.
11007   /// \param NoteId Diagnostic note for the main error message.
11008   /// \return true if statement is not an update expression, false otherwise.
11009   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
11010   /// Return the 'x' lvalue part of the source atomic expression.
11011   Expr *getX() const { return X; }
11012   /// Return the 'expr' rvalue part of the source atomic expression.
11013   Expr *getExpr() const { return E; }
11014   /// Return the update expression used in calculation of the updated
11015   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
11016   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
11017   Expr *getUpdateExpr() const { return UpdateExpr; }
11018   /// Return true if 'x' is LHS in RHS part of full update expression,
11019   /// false otherwise.
11020   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
11021 
11022   /// true if the source expression is a postfix unary operation, false
11023   /// if it is a prefix unary operation.
11024   bool isPostfixUpdate() const { return IsPostfixUpdate; }
11025 
11026 private:
11027   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
11028                             unsigned NoteId = 0);
11029 };
11030 
11031 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
11032     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
11033   ExprAnalysisErrorCode ErrorFound = NoError;
11034   SourceLocation ErrorLoc, NoteLoc;
11035   SourceRange ErrorRange, NoteRange;
11036   // Allowed constructs are:
11037   //  x = x binop expr;
11038   //  x = expr binop x;
11039   if (AtomicBinOp->getOpcode() == BO_Assign) {
11040     X = AtomicBinOp->getLHS();
11041     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
11042             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
11043       if (AtomicInnerBinOp->isMultiplicativeOp() ||
11044           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
11045           AtomicInnerBinOp->isBitwiseOp()) {
11046         Op = AtomicInnerBinOp->getOpcode();
11047         OpLoc = AtomicInnerBinOp->getOperatorLoc();
11048         Expr *LHS = AtomicInnerBinOp->getLHS();
11049         Expr *RHS = AtomicInnerBinOp->getRHS();
11050         llvm::FoldingSetNodeID XId, LHSId, RHSId;
11051         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
11052                                           /*Canonical=*/true);
11053         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
11054                                             /*Canonical=*/true);
11055         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
11056                                             /*Canonical=*/true);
11057         if (XId == LHSId) {
11058           E = RHS;
11059           IsXLHSInRHSPart = true;
11060         } else if (XId == RHSId) {
11061           E = LHS;
11062           IsXLHSInRHSPart = false;
11063         } else {
11064           ErrorLoc = AtomicInnerBinOp->getExprLoc();
11065           ErrorRange = AtomicInnerBinOp->getSourceRange();
11066           NoteLoc = X->getExprLoc();
11067           NoteRange = X->getSourceRange();
11068           ErrorFound = NotAnUpdateExpression;
11069         }
11070       } else {
11071         ErrorLoc = AtomicInnerBinOp->getExprLoc();
11072         ErrorRange = AtomicInnerBinOp->getSourceRange();
11073         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
11074         NoteRange = SourceRange(NoteLoc, NoteLoc);
11075         ErrorFound = NotABinaryOperator;
11076       }
11077     } else {
11078       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
11079       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
11080       ErrorFound = NotABinaryExpression;
11081     }
11082   } else {
11083     ErrorLoc = AtomicBinOp->getExprLoc();
11084     ErrorRange = AtomicBinOp->getSourceRange();
11085     NoteLoc = AtomicBinOp->getOperatorLoc();
11086     NoteRange = SourceRange(NoteLoc, NoteLoc);
11087     ErrorFound = NotAnAssignmentOp;
11088   }
11089   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
11090     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
11091     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
11092     return true;
11093   }
11094   if (SemaRef.CurContext->isDependentContext())
11095     E = X = UpdateExpr = nullptr;
11096   return ErrorFound != NoError;
11097 }
11098 
11099 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
11100                                                unsigned NoteId) {
11101   ExprAnalysisErrorCode ErrorFound = NoError;
11102   SourceLocation ErrorLoc, NoteLoc;
11103   SourceRange ErrorRange, NoteRange;
11104   // Allowed constructs are:
11105   //  x++;
11106   //  x--;
11107   //  ++x;
11108   //  --x;
11109   //  x binop= expr;
11110   //  x = x binop expr;
11111   //  x = expr binop x;
11112   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
11113     AtomicBody = AtomicBody->IgnoreParenImpCasts();
11114     if (AtomicBody->getType()->isScalarType() ||
11115         AtomicBody->isInstantiationDependent()) {
11116       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
11117               AtomicBody->IgnoreParenImpCasts())) {
11118         // Check for Compound Assignment Operation
11119         Op = BinaryOperator::getOpForCompoundAssignment(
11120             AtomicCompAssignOp->getOpcode());
11121         OpLoc = AtomicCompAssignOp->getOperatorLoc();
11122         E = AtomicCompAssignOp->getRHS();
11123         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
11124         IsXLHSInRHSPart = true;
11125       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
11126                      AtomicBody->IgnoreParenImpCasts())) {
11127         // Check for Binary Operation
11128         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
11129           return true;
11130       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
11131                      AtomicBody->IgnoreParenImpCasts())) {
11132         // Check for Unary Operation
11133         if (AtomicUnaryOp->isIncrementDecrementOp()) {
11134           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
11135           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
11136           OpLoc = AtomicUnaryOp->getOperatorLoc();
11137           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
11138           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
11139           IsXLHSInRHSPart = true;
11140         } else {
11141           ErrorFound = NotAnUnaryIncDecExpression;
11142           ErrorLoc = AtomicUnaryOp->getExprLoc();
11143           ErrorRange = AtomicUnaryOp->getSourceRange();
11144           NoteLoc = AtomicUnaryOp->getOperatorLoc();
11145           NoteRange = SourceRange(NoteLoc, NoteLoc);
11146         }
11147       } else if (!AtomicBody->isInstantiationDependent()) {
11148         ErrorFound = NotABinaryOrUnaryExpression;
11149         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
11150         NoteRange = ErrorRange = AtomicBody->getSourceRange();
11151       }
11152     } else {
11153       ErrorFound = NotAScalarType;
11154       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
11155       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11156     }
11157   } else {
11158     ErrorFound = NotAnExpression;
11159     NoteLoc = ErrorLoc = S->getBeginLoc();
11160     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11161   }
11162   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
11163     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
11164     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
11165     return true;
11166   }
11167   if (SemaRef.CurContext->isDependentContext())
11168     E = X = UpdateExpr = nullptr;
11169   if (ErrorFound == NoError && E && X) {
11170     // Build an update expression of form 'OpaqueValueExpr(x) binop
11171     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
11172     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
11173     auto *OVEX = new (SemaRef.getASTContext())
11174         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
11175     auto *OVEExpr = new (SemaRef.getASTContext())
11176         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
11177     ExprResult Update =
11178         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
11179                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
11180     if (Update.isInvalid())
11181       return true;
11182     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
11183                                                Sema::AA_Casting);
11184     if (Update.isInvalid())
11185       return true;
11186     UpdateExpr = Update.get();
11187   }
11188   return ErrorFound != NoError;
11189 }
11190 
11191 /// Get the node id of the fixed point of an expression \a S.
11192 llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) {
11193   llvm::FoldingSetNodeID Id;
11194   S->IgnoreParenImpCasts()->Profile(Id, Context, true);
11195   return Id;
11196 }
11197 
11198 /// Check if two expressions are same.
11199 bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS,
11200                             const Expr *RHS) {
11201   return getNodeId(Context, LHS) == getNodeId(Context, RHS);
11202 }
11203 
11204 class OpenMPAtomicCompareChecker {
11205 public:
11206   /// All kinds of errors that can occur in `atomic compare`
11207   enum ErrorTy {
11208     /// Empty compound statement.
11209     NoStmt = 0,
11210     /// More than one statement in a compound statement.
11211     MoreThanOneStmt,
11212     /// Not an assignment binary operator.
11213     NotAnAssignment,
11214     /// Not a conditional operator.
11215     NotCondOp,
11216     /// Wrong false expr. According to the spec, 'x' should be at the false
11217     /// expression of a conditional expression.
11218     WrongFalseExpr,
11219     /// The condition of a conditional expression is not a binary operator.
11220     NotABinaryOp,
11221     /// Invalid binary operator (not <, >, or ==).
11222     InvalidBinaryOp,
11223     /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x).
11224     InvalidComparison,
11225     /// X is not a lvalue.
11226     XNotLValue,
11227     /// Not a scalar.
11228     NotScalar,
11229     /// Not an integer.
11230     NotInteger,
11231     /// 'else' statement is not expected.
11232     UnexpectedElse,
11233     /// Not an equality operator.
11234     NotEQ,
11235     /// Invalid assignment (not v == x).
11236     InvalidAssignment,
11237     /// Not if statement
11238     NotIfStmt,
11239     /// More than two statements in a compund statement.
11240     MoreThanTwoStmts,
11241     /// Not a compound statement.
11242     NotCompoundStmt,
11243     /// No else statement.
11244     NoElse,
11245     /// Not 'if (r)'.
11246     InvalidCondition,
11247     /// No error.
11248     NoError,
11249   };
11250 
11251   struct ErrorInfoTy {
11252     ErrorTy Error;
11253     SourceLocation ErrorLoc;
11254     SourceRange ErrorRange;
11255     SourceLocation NoteLoc;
11256     SourceRange NoteRange;
11257   };
11258 
11259   OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {}
11260 
11261   /// Check if statement \a S is valid for <tt>atomic compare</tt>.
11262   bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11263 
11264   Expr *getX() const { return X; }
11265   Expr *getE() const { return E; }
11266   Expr *getD() const { return D; }
11267   Expr *getCond() const { return C; }
11268   bool isXBinopExpr() const { return IsXBinopExpr; }
11269 
11270 protected:
11271   /// Reference to ASTContext
11272   ASTContext &ContextRef;
11273   /// 'x' lvalue part of the source atomic expression.
11274   Expr *X = nullptr;
11275   /// 'expr' or 'e' rvalue part of the source atomic expression.
11276   Expr *E = nullptr;
11277   /// 'd' rvalue part of the source atomic expression.
11278   Expr *D = nullptr;
11279   /// 'cond' part of the source atomic expression. It is in one of the following
11280   /// forms:
11281   /// expr ordop x
11282   /// x ordop expr
11283   /// x == e
11284   /// e == x
11285   Expr *C = nullptr;
11286   /// True if the cond expr is in the form of 'x ordop expr'.
11287   bool IsXBinopExpr = true;
11288 
11289   /// Check if it is a valid conditional update statement (cond-update-stmt).
11290   bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo);
11291 
11292   /// Check if it is a valid conditional expression statement (cond-expr-stmt).
11293   bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11294 
11295   /// Check if all captured values have right type.
11296   bool checkType(ErrorInfoTy &ErrorInfo) const;
11297 
11298   static bool CheckValue(const Expr *E, ErrorInfoTy &ErrorInfo,
11299                          bool ShouldBeLValue) {
11300     if (ShouldBeLValue && !E->isLValue()) {
11301       ErrorInfo.Error = ErrorTy::XNotLValue;
11302       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11303       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11304       return false;
11305     }
11306 
11307     if (!E->isInstantiationDependent()) {
11308       QualType QTy = E->getType();
11309       if (!QTy->isScalarType()) {
11310         ErrorInfo.Error = ErrorTy::NotScalar;
11311         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11312         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11313         return false;
11314       }
11315 
11316       if (!QTy->isIntegerType()) {
11317         ErrorInfo.Error = ErrorTy::NotInteger;
11318         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11319         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11320         return false;
11321       }
11322     }
11323 
11324     return true;
11325   }
11326 };
11327 
11328 bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S,
11329                                                      ErrorInfoTy &ErrorInfo) {
11330   auto *Then = S->getThen();
11331   if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
11332     if (CS->body_empty()) {
11333       ErrorInfo.Error = ErrorTy::NoStmt;
11334       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11335       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11336       return false;
11337     }
11338     if (CS->size() > 1) {
11339       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11340       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11341       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11342       return false;
11343     }
11344     Then = CS->body_front();
11345   }
11346 
11347   auto *BO = dyn_cast<BinaryOperator>(Then);
11348   if (!BO) {
11349     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11350     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
11351     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
11352     return false;
11353   }
11354   if (BO->getOpcode() != BO_Assign) {
11355     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11356     ErrorInfo.ErrorLoc = BO->getExprLoc();
11357     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11358     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11359     return false;
11360   }
11361 
11362   X = BO->getLHS();
11363 
11364   auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
11365   if (!Cond) {
11366     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11367     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
11368     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
11369     return false;
11370   }
11371 
11372   switch (Cond->getOpcode()) {
11373   case BO_EQ: {
11374     C = Cond;
11375     D = BO->getRHS()->IgnoreImpCasts();
11376     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11377       E = Cond->getRHS()->IgnoreImpCasts();
11378     } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11379       E = Cond->getLHS()->IgnoreImpCasts();
11380     } else {
11381       ErrorInfo.Error = ErrorTy::InvalidComparison;
11382       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11383       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11384       return false;
11385     }
11386     break;
11387   }
11388   case BO_LT:
11389   case BO_GT: {
11390     E = BO->getRHS()->IgnoreImpCasts();
11391     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
11392         checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
11393       C = Cond;
11394     } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
11395                checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11396       C = Cond;
11397       IsXBinopExpr = false;
11398     } else {
11399       ErrorInfo.Error = ErrorTy::InvalidComparison;
11400       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11401       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11402       return false;
11403     }
11404     break;
11405   }
11406   default:
11407     ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
11408     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11409     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11410     return false;
11411   }
11412 
11413   if (S->getElse()) {
11414     ErrorInfo.Error = ErrorTy::UnexpectedElse;
11415     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getElse()->getBeginLoc();
11416     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getElse()->getSourceRange();
11417     return false;
11418   }
11419 
11420   return true;
11421 }
11422 
11423 bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S,
11424                                                    ErrorInfoTy &ErrorInfo) {
11425   auto *BO = dyn_cast<BinaryOperator>(S);
11426   if (!BO) {
11427     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11428     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11429     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11430     return false;
11431   }
11432   if (BO->getOpcode() != BO_Assign) {
11433     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11434     ErrorInfo.ErrorLoc = BO->getExprLoc();
11435     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11436     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11437     return false;
11438   }
11439 
11440   X = BO->getLHS();
11441 
11442   auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts());
11443   if (!CO) {
11444     ErrorInfo.Error = ErrorTy::NotCondOp;
11445     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc();
11446     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange();
11447     return false;
11448   }
11449 
11450   if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) {
11451     ErrorInfo.Error = ErrorTy::WrongFalseExpr;
11452     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc();
11453     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11454         CO->getFalseExpr()->getSourceRange();
11455     return false;
11456   }
11457 
11458   auto *Cond = dyn_cast<BinaryOperator>(CO->getCond());
11459   if (!Cond) {
11460     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11461     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
11462     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11463         CO->getCond()->getSourceRange();
11464     return false;
11465   }
11466 
11467   switch (Cond->getOpcode()) {
11468   case BO_EQ: {
11469     C = Cond;
11470     D = CO->getTrueExpr()->IgnoreImpCasts();
11471     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11472       E = Cond->getRHS()->IgnoreImpCasts();
11473     } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11474       E = Cond->getLHS()->IgnoreImpCasts();
11475     } else {
11476       ErrorInfo.Error = ErrorTy::InvalidComparison;
11477       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11478       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11479       return false;
11480     }
11481     break;
11482   }
11483   case BO_LT:
11484   case BO_GT: {
11485     E = CO->getTrueExpr()->IgnoreImpCasts();
11486     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
11487         checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
11488       C = Cond;
11489     } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
11490                checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11491       C = Cond;
11492       IsXBinopExpr = false;
11493     } else {
11494       ErrorInfo.Error = ErrorTy::InvalidComparison;
11495       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11496       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11497       return false;
11498     }
11499     break;
11500   }
11501   default:
11502     ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
11503     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11504     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11505     return false;
11506   }
11507 
11508   return true;
11509 }
11510 
11511 bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const {
11512   // 'x' and 'e' cannot be nullptr
11513   assert(X && E && "X and E cannot be nullptr");
11514 
11515   if (!CheckValue(X, ErrorInfo, true))
11516     return false;
11517 
11518   if (!CheckValue(E, ErrorInfo, false))
11519     return false;
11520 
11521   if (D && !CheckValue(D, ErrorInfo, false))
11522     return false;
11523 
11524   return true;
11525 }
11526 
11527 bool OpenMPAtomicCompareChecker::checkStmt(
11528     Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) {
11529   auto *CS = dyn_cast<CompoundStmt>(S);
11530   if (CS) {
11531     if (CS->body_empty()) {
11532       ErrorInfo.Error = ErrorTy::NoStmt;
11533       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11534       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11535       return false;
11536     }
11537 
11538     if (CS->size() != 1) {
11539       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11540       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11541       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11542       return false;
11543     }
11544     S = CS->body_front();
11545   }
11546 
11547   auto Res = false;
11548 
11549   if (auto *IS = dyn_cast<IfStmt>(S)) {
11550     // Check if the statement is in one of the following forms
11551     // (cond-update-stmt):
11552     // if (expr ordop x) { x = expr; }
11553     // if (x ordop expr) { x = expr; }
11554     // if (x == e) { x = d; }
11555     Res = checkCondUpdateStmt(IS, ErrorInfo);
11556   } else {
11557     // Check if the statement is in one of the following forms (cond-expr-stmt):
11558     // x = expr ordop x ? expr : x;
11559     // x = x ordop expr ? expr : x;
11560     // x = x == e ? d : x;
11561     Res = checkCondExprStmt(S, ErrorInfo);
11562   }
11563 
11564   if (!Res)
11565     return false;
11566 
11567   return checkType(ErrorInfo);
11568 }
11569 
11570 class OpenMPAtomicCompareCaptureChecker final
11571     : public OpenMPAtomicCompareChecker {
11572 public:
11573   OpenMPAtomicCompareCaptureChecker(Sema &S) : OpenMPAtomicCompareChecker(S) {}
11574 
11575   Expr *getV() const { return V; }
11576   Expr *getR() const { return R; }
11577   bool isFailOnly() const { return IsFailOnly; }
11578 
11579   /// Check if statement \a S is valid for <tt>atomic compare capture</tt>.
11580   bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11581 
11582 private:
11583   bool checkType(ErrorInfoTy &ErrorInfo);
11584 
11585   // NOTE: Form 3, 4, 5 in the following comments mean the 3rd, 4th, and 5th
11586   // form of 'conditional-update-capture-atomic' structured block on the v5.2
11587   // spec p.p. 82:
11588   // (1) { v = x; cond-update-stmt }
11589   // (2) { cond-update-stmt v = x; }
11590   // (3) if(x == e) { x = d; } else { v = x; }
11591   // (4) { r = x == e; if(r) { x = d; } }
11592   // (5) { r = x == e; if(r) { x = d; } else { v = x; } }
11593 
11594   /// Check if it is valid 'if(x == e) { x = d; } else { v = x; }' (form 3)
11595   bool checkForm3(IfStmt *S, ErrorInfoTy &ErrorInfo);
11596 
11597   /// Check if it is valid '{ r = x == e; if(r) { x = d; } }',
11598   /// or '{ r = x == e; if(r) { x = d; } else { v = x; } }' (form 4 and 5)
11599   bool checkForm45(Stmt *S, ErrorInfoTy &ErrorInfo);
11600 
11601   /// 'v' lvalue part of the source atomic expression.
11602   Expr *V = nullptr;
11603   /// 'r' lvalue part of the source atomic expression.
11604   Expr *R = nullptr;
11605   /// If 'v' is only updated when the comparison fails.
11606   bool IsFailOnly = false;
11607 };
11608 
11609 bool OpenMPAtomicCompareCaptureChecker::checkType(ErrorInfoTy &ErrorInfo) {
11610   if (!OpenMPAtomicCompareChecker::checkType(ErrorInfo))
11611     return false;
11612 
11613   if (V && !CheckValue(V, ErrorInfo, true))
11614     return false;
11615 
11616   if (R && !CheckValue(R, ErrorInfo, true))
11617     return false;
11618 
11619   return true;
11620 }
11621 
11622 bool OpenMPAtomicCompareCaptureChecker::checkForm3(IfStmt *S,
11623                                                    ErrorInfoTy &ErrorInfo) {
11624   IsFailOnly = true;
11625 
11626   auto *Then = S->getThen();
11627   if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
11628     if (CS->body_empty()) {
11629       ErrorInfo.Error = ErrorTy::NoStmt;
11630       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11631       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11632       return false;
11633     }
11634     if (CS->size() > 1) {
11635       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11636       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11637       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11638       return false;
11639     }
11640     Then = CS->body_front();
11641   }
11642 
11643   auto *BO = dyn_cast<BinaryOperator>(Then);
11644   if (!BO) {
11645     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11646     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
11647     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
11648     return false;
11649   }
11650   if (BO->getOpcode() != BO_Assign) {
11651     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11652     ErrorInfo.ErrorLoc = BO->getExprLoc();
11653     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11654     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11655     return false;
11656   }
11657 
11658   X = BO->getLHS();
11659   D = BO->getRHS();
11660 
11661   auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
11662   if (!Cond) {
11663     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11664     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
11665     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
11666     return false;
11667   }
11668   if (Cond->getOpcode() != BO_EQ) {
11669     ErrorInfo.Error = ErrorTy::NotEQ;
11670     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11671     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11672     return false;
11673   }
11674 
11675   if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11676     E = Cond->getRHS();
11677   } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11678     E = Cond->getLHS();
11679   } else {
11680     ErrorInfo.Error = ErrorTy::InvalidComparison;
11681     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11682     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11683     return false;
11684   }
11685 
11686   C = Cond;
11687 
11688   if (!S->getElse()) {
11689     ErrorInfo.Error = ErrorTy::NoElse;
11690     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11691     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11692     return false;
11693   }
11694 
11695   auto *Else = S->getElse();
11696   if (auto *CS = dyn_cast<CompoundStmt>(Else)) {
11697     if (CS->body_empty()) {
11698       ErrorInfo.Error = ErrorTy::NoStmt;
11699       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11700       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11701       return false;
11702     }
11703     if (CS->size() > 1) {
11704       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11705       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11706       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11707       return false;
11708     }
11709     Else = CS->body_front();
11710   }
11711 
11712   auto *ElseBO = dyn_cast<BinaryOperator>(Else);
11713   if (!ElseBO) {
11714     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11715     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
11716     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
11717     return false;
11718   }
11719   if (ElseBO->getOpcode() != BO_Assign) {
11720     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11721     ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
11722     ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
11723     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
11724     return false;
11725   }
11726 
11727   if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
11728     ErrorInfo.Error = ErrorTy::InvalidAssignment;
11729     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseBO->getRHS()->getExprLoc();
11730     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11731         ElseBO->getRHS()->getSourceRange();
11732     return false;
11733   }
11734 
11735   V = ElseBO->getLHS();
11736 
11737   return checkType(ErrorInfo);
11738 }
11739 
11740 bool OpenMPAtomicCompareCaptureChecker::checkForm45(Stmt *S,
11741                                                     ErrorInfoTy &ErrorInfo) {
11742   // We don't check here as they should be already done before call this
11743   // function.
11744   auto *CS = cast<CompoundStmt>(S);
11745   assert(CS->size() == 2 && "CompoundStmt size is not expected");
11746   auto *S1 = cast<BinaryOperator>(CS->body_front());
11747   auto *S2 = cast<IfStmt>(CS->body_back());
11748   assert(S1->getOpcode() == BO_Assign && "unexpected binary operator");
11749 
11750   if (!checkIfTwoExprsAreSame(ContextRef, S1->getLHS(), S2->getCond())) {
11751     ErrorInfo.Error = ErrorTy::InvalidCondition;
11752     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getCond()->getExprLoc();
11753     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S1->getLHS()->getSourceRange();
11754     return false;
11755   }
11756 
11757   R = S1->getLHS();
11758 
11759   auto *Then = S2->getThen();
11760   if (auto *ThenCS = dyn_cast<CompoundStmt>(Then)) {
11761     if (ThenCS->body_empty()) {
11762       ErrorInfo.Error = ErrorTy::NoStmt;
11763       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
11764       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
11765       return false;
11766     }
11767     if (ThenCS->size() > 1) {
11768       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11769       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
11770       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
11771       return false;
11772     }
11773     Then = ThenCS->body_front();
11774   }
11775 
11776   auto *ThenBO = dyn_cast<BinaryOperator>(Then);
11777   if (!ThenBO) {
11778     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11779     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getBeginLoc();
11780     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S2->getSourceRange();
11781     return false;
11782   }
11783   if (ThenBO->getOpcode() != BO_Assign) {
11784     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11785     ErrorInfo.ErrorLoc = ThenBO->getExprLoc();
11786     ErrorInfo.NoteLoc = ThenBO->getOperatorLoc();
11787     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenBO->getSourceRange();
11788     return false;
11789   }
11790 
11791   X = ThenBO->getLHS();
11792   D = ThenBO->getRHS();
11793 
11794   auto *BO = cast<BinaryOperator>(S1->getRHS()->IgnoreImpCasts());
11795   if (BO->getOpcode() != BO_EQ) {
11796     ErrorInfo.Error = ErrorTy::NotEQ;
11797     ErrorInfo.ErrorLoc = BO->getExprLoc();
11798     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11799     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11800     return false;
11801   }
11802 
11803   C = BO;
11804 
11805   if (checkIfTwoExprsAreSame(ContextRef, X, BO->getLHS())) {
11806     E = BO->getRHS();
11807   } else if (checkIfTwoExprsAreSame(ContextRef, X, BO->getRHS())) {
11808     E = BO->getLHS();
11809   } else {
11810     ErrorInfo.Error = ErrorTy::InvalidComparison;
11811     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getExprLoc();
11812     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11813     return false;
11814   }
11815 
11816   if (S2->getElse()) {
11817     IsFailOnly = true;
11818 
11819     auto *Else = S2->getElse();
11820     if (auto *ElseCS = dyn_cast<CompoundStmt>(Else)) {
11821       if (ElseCS->body_empty()) {
11822         ErrorInfo.Error = ErrorTy::NoStmt;
11823         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
11824         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
11825         return false;
11826       }
11827       if (ElseCS->size() > 1) {
11828         ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11829         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
11830         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
11831         return false;
11832       }
11833       Else = ElseCS->body_front();
11834     }
11835 
11836     auto *ElseBO = dyn_cast<BinaryOperator>(Else);
11837     if (!ElseBO) {
11838       ErrorInfo.Error = ErrorTy::NotAnAssignment;
11839       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
11840       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
11841       return false;
11842     }
11843     if (ElseBO->getOpcode() != BO_Assign) {
11844       ErrorInfo.Error = ErrorTy::NotAnAssignment;
11845       ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
11846       ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
11847       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
11848       return false;
11849     }
11850     if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
11851       ErrorInfo.Error = ErrorTy::InvalidAssignment;
11852       ErrorInfo.ErrorLoc = ElseBO->getRHS()->getExprLoc();
11853       ErrorInfo.NoteLoc = X->getExprLoc();
11854       ErrorInfo.ErrorRange = ElseBO->getRHS()->getSourceRange();
11855       ErrorInfo.NoteRange = X->getSourceRange();
11856       return false;
11857     }
11858 
11859     V = ElseBO->getLHS();
11860   }
11861 
11862   return checkType(ErrorInfo);
11863 }
11864 
11865 bool OpenMPAtomicCompareCaptureChecker::checkStmt(Stmt *S,
11866                                                   ErrorInfoTy &ErrorInfo) {
11867   // if(x == e) { x = d; } else { v = x; }
11868   if (auto *IS = dyn_cast<IfStmt>(S))
11869     return checkForm3(IS, ErrorInfo);
11870 
11871   auto *CS = dyn_cast<CompoundStmt>(S);
11872   if (!CS) {
11873     ErrorInfo.Error = ErrorTy::NotCompoundStmt;
11874     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11875     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11876     return false;
11877   }
11878   if (CS->body_empty()) {
11879     ErrorInfo.Error = ErrorTy::NoStmt;
11880     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11881     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11882     return false;
11883   }
11884 
11885   // { if(x == e) { x = d; } else { v = x; } }
11886   if (CS->size() == 1) {
11887     auto *IS = dyn_cast<IfStmt>(CS->body_front());
11888     if (!IS) {
11889       ErrorInfo.Error = ErrorTy::NotIfStmt;
11890       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->body_front()->getBeginLoc();
11891       ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11892           CS->body_front()->getSourceRange();
11893       return false;
11894     }
11895 
11896     return checkForm3(IS, ErrorInfo);
11897   } else if (CS->size() == 2) {
11898     auto *S1 = CS->body_front();
11899     auto *S2 = CS->body_back();
11900 
11901     Stmt *UpdateStmt = nullptr;
11902     Stmt *CondUpdateStmt = nullptr;
11903 
11904     if (auto *BO = dyn_cast<BinaryOperator>(S1)) {
11905       // { v = x; cond-update-stmt } or form 45.
11906       UpdateStmt = S1;
11907       CondUpdateStmt = S2;
11908       // Check if form 45.
11909       if (dyn_cast<BinaryOperator>(BO->getRHS()->IgnoreImpCasts()) &&
11910           dyn_cast<IfStmt>(S2))
11911         return checkForm45(CS, ErrorInfo);
11912     } else {
11913       // { cond-update-stmt v = x; }
11914       UpdateStmt = S2;
11915       CondUpdateStmt = S1;
11916     }
11917 
11918     auto CheckCondUpdateStmt = [this, &ErrorInfo](Stmt *CUS) {
11919       auto *IS = dyn_cast<IfStmt>(CUS);
11920       if (!IS) {
11921         ErrorInfo.Error = ErrorTy::NotIfStmt;
11922         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CUS->getBeginLoc();
11923         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CUS->getSourceRange();
11924         return false;
11925       }
11926 
11927       if (!checkCondUpdateStmt(IS, ErrorInfo))
11928         return false;
11929 
11930       return true;
11931     };
11932 
11933     // CheckUpdateStmt has to be called *after* CheckCondUpdateStmt.
11934     auto CheckUpdateStmt = [this, &ErrorInfo](Stmt *US) {
11935       auto *BO = dyn_cast<BinaryOperator>(US);
11936       if (!BO) {
11937         ErrorInfo.Error = ErrorTy::NotAnAssignment;
11938         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = US->getBeginLoc();
11939         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = US->getSourceRange();
11940         return false;
11941       }
11942       if (BO->getOpcode() != BO_Assign) {
11943         ErrorInfo.Error = ErrorTy::NotAnAssignment;
11944         ErrorInfo.ErrorLoc = BO->getExprLoc();
11945         ErrorInfo.NoteLoc = BO->getOperatorLoc();
11946         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11947         return false;
11948       }
11949       if (!checkIfTwoExprsAreSame(ContextRef, this->X, BO->getRHS())) {
11950         ErrorInfo.Error = ErrorTy::InvalidAssignment;
11951         ErrorInfo.ErrorLoc = BO->getRHS()->getExprLoc();
11952         ErrorInfo.NoteLoc = this->X->getExprLoc();
11953         ErrorInfo.ErrorRange = BO->getRHS()->getSourceRange();
11954         ErrorInfo.NoteRange = this->X->getSourceRange();
11955         return false;
11956       }
11957 
11958       this->V = BO->getLHS();
11959 
11960       return true;
11961     };
11962 
11963     if (!CheckCondUpdateStmt(CondUpdateStmt))
11964       return false;
11965     if (!CheckUpdateStmt(UpdateStmt))
11966       return false;
11967   } else {
11968     ErrorInfo.Error = ErrorTy::MoreThanTwoStmts;
11969     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11970     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11971     return false;
11972   }
11973 
11974   return checkType(ErrorInfo);
11975 }
11976 } // namespace
11977 
11978 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11979                                             Stmt *AStmt,
11980                                             SourceLocation StartLoc,
11981                                             SourceLocation EndLoc) {
11982   // Register location of the first atomic directive.
11983   DSAStack->addAtomicDirectiveLoc(StartLoc);
11984   if (!AStmt)
11985     return StmtError();
11986 
11987   // 1.2.2 OpenMP Language Terminology
11988   // Structured block - An executable statement with a single entry at the
11989   // top and a single exit at the bottom.
11990   // The point of exit cannot be a branch out of the structured block.
11991   // longjmp() and throw() must not violate the entry/exit criteria.
11992   OpenMPClauseKind AtomicKind = OMPC_unknown;
11993   SourceLocation AtomicKindLoc;
11994   OpenMPClauseKind MemOrderKind = OMPC_unknown;
11995   SourceLocation MemOrderLoc;
11996   bool MutexClauseEncountered = false;
11997   llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds;
11998   for (const OMPClause *C : Clauses) {
11999     switch (C->getClauseKind()) {
12000     case OMPC_read:
12001     case OMPC_write:
12002     case OMPC_update:
12003       MutexClauseEncountered = true;
12004       LLVM_FALLTHROUGH;
12005     case OMPC_capture:
12006     case OMPC_compare: {
12007       if (AtomicKind != OMPC_unknown && MutexClauseEncountered) {
12008         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
12009             << SourceRange(C->getBeginLoc(), C->getEndLoc());
12010         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
12011             << getOpenMPClauseName(AtomicKind);
12012       } else {
12013         AtomicKind = C->getClauseKind();
12014         AtomicKindLoc = C->getBeginLoc();
12015         if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) {
12016           Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
12017               << SourceRange(C->getBeginLoc(), C->getEndLoc());
12018           Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
12019               << getOpenMPClauseName(AtomicKind);
12020         }
12021       }
12022       break;
12023     }
12024     case OMPC_seq_cst:
12025     case OMPC_acq_rel:
12026     case OMPC_acquire:
12027     case OMPC_release:
12028     case OMPC_relaxed: {
12029       if (MemOrderKind != OMPC_unknown) {
12030         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
12031             << getOpenMPDirectiveName(OMPD_atomic) << 0
12032             << SourceRange(C->getBeginLoc(), C->getEndLoc());
12033         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
12034             << getOpenMPClauseName(MemOrderKind);
12035       } else {
12036         MemOrderKind = C->getClauseKind();
12037         MemOrderLoc = C->getBeginLoc();
12038       }
12039       break;
12040     }
12041     // The following clauses are allowed, but we don't need to do anything here.
12042     case OMPC_hint:
12043       break;
12044     default:
12045       llvm_unreachable("unknown clause is encountered");
12046     }
12047   }
12048   bool IsCompareCapture = false;
12049   if (EncounteredAtomicKinds.contains(OMPC_compare) &&
12050       EncounteredAtomicKinds.contains(OMPC_capture)) {
12051     IsCompareCapture = true;
12052     AtomicKind = OMPC_compare;
12053   }
12054   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
12055   // If atomic-clause is read then memory-order-clause must not be acq_rel or
12056   // release.
12057   // If atomic-clause is write then memory-order-clause must not be acq_rel or
12058   // acquire.
12059   // If atomic-clause is update or not present then memory-order-clause must not
12060   // be acq_rel or acquire.
12061   if ((AtomicKind == OMPC_read &&
12062        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
12063       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
12064         AtomicKind == OMPC_unknown) &&
12065        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
12066     SourceLocation Loc = AtomicKindLoc;
12067     if (AtomicKind == OMPC_unknown)
12068       Loc = StartLoc;
12069     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
12070         << getOpenMPClauseName(AtomicKind)
12071         << (AtomicKind == OMPC_unknown ? 1 : 0)
12072         << getOpenMPClauseName(MemOrderKind);
12073     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
12074         << getOpenMPClauseName(MemOrderKind);
12075   }
12076 
12077   Stmt *Body = AStmt;
12078   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
12079     Body = EWC->getSubExpr();
12080 
12081   Expr *X = nullptr;
12082   Expr *V = nullptr;
12083   Expr *E = nullptr;
12084   Expr *UE = nullptr;
12085   Expr *D = nullptr;
12086   Expr *CE = nullptr;
12087   bool IsXLHSInRHSPart = false;
12088   bool IsPostfixUpdate = false;
12089   // OpenMP [2.12.6, atomic Construct]
12090   // In the next expressions:
12091   // * x and v (as applicable) are both l-value expressions with scalar type.
12092   // * During the execution of an atomic region, multiple syntactic
12093   // occurrences of x must designate the same storage location.
12094   // * Neither of v and expr (as applicable) may access the storage location
12095   // designated by x.
12096   // * Neither of x and expr (as applicable) may access the storage location
12097   // designated by v.
12098   // * expr is an expression with scalar type.
12099   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
12100   // * binop, binop=, ++, and -- are not overloaded operators.
12101   // * The expression x binop expr must be numerically equivalent to x binop
12102   // (expr). This requirement is satisfied if the operators in expr have
12103   // precedence greater than binop, or by using parentheses around expr or
12104   // subexpressions of expr.
12105   // * The expression expr binop x must be numerically equivalent to (expr)
12106   // binop x. This requirement is satisfied if the operators in expr have
12107   // precedence equal to or greater than binop, or by using parentheses around
12108   // expr or subexpressions of expr.
12109   // * For forms that allow multiple occurrences of x, the number of times
12110   // that x is evaluated is unspecified.
12111   if (AtomicKind == OMPC_read) {
12112     enum {
12113       NotAnExpression,
12114       NotAnAssignmentOp,
12115       NotAScalarType,
12116       NotAnLValue,
12117       NoError
12118     } ErrorFound = NoError;
12119     SourceLocation ErrorLoc, NoteLoc;
12120     SourceRange ErrorRange, NoteRange;
12121     // If clause is read:
12122     //  v = x;
12123     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
12124       const auto *AtomicBinOp =
12125           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
12126       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
12127         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
12128         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
12129         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
12130             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
12131           if (!X->isLValue() || !V->isLValue()) {
12132             const Expr *NotLValueExpr = X->isLValue() ? V : X;
12133             ErrorFound = NotAnLValue;
12134             ErrorLoc = AtomicBinOp->getExprLoc();
12135             ErrorRange = AtomicBinOp->getSourceRange();
12136             NoteLoc = NotLValueExpr->getExprLoc();
12137             NoteRange = NotLValueExpr->getSourceRange();
12138           }
12139         } else if (!X->isInstantiationDependent() ||
12140                    !V->isInstantiationDependent()) {
12141           const Expr *NotScalarExpr =
12142               (X->isInstantiationDependent() || X->getType()->isScalarType())
12143                   ? V
12144                   : X;
12145           ErrorFound = NotAScalarType;
12146           ErrorLoc = AtomicBinOp->getExprLoc();
12147           ErrorRange = AtomicBinOp->getSourceRange();
12148           NoteLoc = NotScalarExpr->getExprLoc();
12149           NoteRange = NotScalarExpr->getSourceRange();
12150         }
12151       } else if (!AtomicBody->isInstantiationDependent()) {
12152         ErrorFound = NotAnAssignmentOp;
12153         ErrorLoc = AtomicBody->getExprLoc();
12154         ErrorRange = AtomicBody->getSourceRange();
12155         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
12156                               : AtomicBody->getExprLoc();
12157         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
12158                                 : AtomicBody->getSourceRange();
12159       }
12160     } else {
12161       ErrorFound = NotAnExpression;
12162       NoteLoc = ErrorLoc = Body->getBeginLoc();
12163       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
12164     }
12165     if (ErrorFound != NoError) {
12166       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
12167           << ErrorRange;
12168       Diag(NoteLoc, diag::note_omp_atomic_read_write)
12169           << ErrorFound << NoteRange;
12170       return StmtError();
12171     }
12172     if (CurContext->isDependentContext())
12173       V = X = nullptr;
12174   } else if (AtomicKind == OMPC_write) {
12175     enum {
12176       NotAnExpression,
12177       NotAnAssignmentOp,
12178       NotAScalarType,
12179       NotAnLValue,
12180       NoError
12181     } ErrorFound = NoError;
12182     SourceLocation ErrorLoc, NoteLoc;
12183     SourceRange ErrorRange, NoteRange;
12184     // If clause is write:
12185     //  x = expr;
12186     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
12187       const auto *AtomicBinOp =
12188           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
12189       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
12190         X = AtomicBinOp->getLHS();
12191         E = AtomicBinOp->getRHS();
12192         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
12193             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
12194           if (!X->isLValue()) {
12195             ErrorFound = NotAnLValue;
12196             ErrorLoc = AtomicBinOp->getExprLoc();
12197             ErrorRange = AtomicBinOp->getSourceRange();
12198             NoteLoc = X->getExprLoc();
12199             NoteRange = X->getSourceRange();
12200           }
12201         } else if (!X->isInstantiationDependent() ||
12202                    !E->isInstantiationDependent()) {
12203           const Expr *NotScalarExpr =
12204               (X->isInstantiationDependent() || X->getType()->isScalarType())
12205                   ? E
12206                   : X;
12207           ErrorFound = NotAScalarType;
12208           ErrorLoc = AtomicBinOp->getExprLoc();
12209           ErrorRange = AtomicBinOp->getSourceRange();
12210           NoteLoc = NotScalarExpr->getExprLoc();
12211           NoteRange = NotScalarExpr->getSourceRange();
12212         }
12213       } else if (!AtomicBody->isInstantiationDependent()) {
12214         ErrorFound = NotAnAssignmentOp;
12215         ErrorLoc = AtomicBody->getExprLoc();
12216         ErrorRange = AtomicBody->getSourceRange();
12217         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
12218                               : AtomicBody->getExprLoc();
12219         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
12220                                 : AtomicBody->getSourceRange();
12221       }
12222     } else {
12223       ErrorFound = NotAnExpression;
12224       NoteLoc = ErrorLoc = Body->getBeginLoc();
12225       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
12226     }
12227     if (ErrorFound != NoError) {
12228       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
12229           << ErrorRange;
12230       Diag(NoteLoc, diag::note_omp_atomic_read_write)
12231           << ErrorFound << NoteRange;
12232       return StmtError();
12233     }
12234     if (CurContext->isDependentContext())
12235       E = X = nullptr;
12236   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
12237     // If clause is update:
12238     //  x++;
12239     //  x--;
12240     //  ++x;
12241     //  --x;
12242     //  x binop= expr;
12243     //  x = x binop expr;
12244     //  x = expr binop x;
12245     OpenMPAtomicUpdateChecker Checker(*this);
12246     if (Checker.checkStatement(
12247             Body,
12248             (AtomicKind == OMPC_update)
12249                 ? diag::err_omp_atomic_update_not_expression_statement
12250                 : diag::err_omp_atomic_not_expression_statement,
12251             diag::note_omp_atomic_update))
12252       return StmtError();
12253     if (!CurContext->isDependentContext()) {
12254       E = Checker.getExpr();
12255       X = Checker.getX();
12256       UE = Checker.getUpdateExpr();
12257       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12258     }
12259   } else if (AtomicKind == OMPC_capture) {
12260     enum {
12261       NotAnAssignmentOp,
12262       NotACompoundStatement,
12263       NotTwoSubstatements,
12264       NotASpecificExpression,
12265       NoError
12266     } ErrorFound = NoError;
12267     SourceLocation ErrorLoc, NoteLoc;
12268     SourceRange ErrorRange, NoteRange;
12269     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
12270       // If clause is a capture:
12271       //  v = x++;
12272       //  v = x--;
12273       //  v = ++x;
12274       //  v = --x;
12275       //  v = x binop= expr;
12276       //  v = x = x binop expr;
12277       //  v = x = expr binop x;
12278       const auto *AtomicBinOp =
12279           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
12280       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
12281         V = AtomicBinOp->getLHS();
12282         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
12283         OpenMPAtomicUpdateChecker Checker(*this);
12284         if (Checker.checkStatement(
12285                 Body, diag::err_omp_atomic_capture_not_expression_statement,
12286                 diag::note_omp_atomic_update))
12287           return StmtError();
12288         E = Checker.getExpr();
12289         X = Checker.getX();
12290         UE = Checker.getUpdateExpr();
12291         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12292         IsPostfixUpdate = Checker.isPostfixUpdate();
12293       } else if (!AtomicBody->isInstantiationDependent()) {
12294         ErrorLoc = AtomicBody->getExprLoc();
12295         ErrorRange = AtomicBody->getSourceRange();
12296         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
12297                               : AtomicBody->getExprLoc();
12298         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
12299                                 : AtomicBody->getSourceRange();
12300         ErrorFound = NotAnAssignmentOp;
12301       }
12302       if (ErrorFound != NoError) {
12303         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
12304             << ErrorRange;
12305         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
12306         return StmtError();
12307       }
12308       if (CurContext->isDependentContext())
12309         UE = V = E = X = nullptr;
12310     } else {
12311       // If clause is a capture:
12312       //  { v = x; x = expr; }
12313       //  { v = x; x++; }
12314       //  { v = x; x--; }
12315       //  { v = x; ++x; }
12316       //  { v = x; --x; }
12317       //  { v = x; x binop= expr; }
12318       //  { v = x; x = x binop expr; }
12319       //  { v = x; x = expr binop x; }
12320       //  { x++; v = x; }
12321       //  { x--; v = x; }
12322       //  { ++x; v = x; }
12323       //  { --x; v = x; }
12324       //  { x binop= expr; v = x; }
12325       //  { x = x binop expr; v = x; }
12326       //  { x = expr binop x; v = x; }
12327       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
12328         // Check that this is { expr1; expr2; }
12329         if (CS->size() == 2) {
12330           Stmt *First = CS->body_front();
12331           Stmt *Second = CS->body_back();
12332           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
12333             First = EWC->getSubExpr()->IgnoreParenImpCasts();
12334           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
12335             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
12336           // Need to find what subexpression is 'v' and what is 'x'.
12337           OpenMPAtomicUpdateChecker Checker(*this);
12338           bool IsUpdateExprFound = !Checker.checkStatement(Second);
12339           BinaryOperator *BinOp = nullptr;
12340           if (IsUpdateExprFound) {
12341             BinOp = dyn_cast<BinaryOperator>(First);
12342             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
12343           }
12344           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
12345             //  { v = x; x++; }
12346             //  { v = x; x--; }
12347             //  { v = x; ++x; }
12348             //  { v = x; --x; }
12349             //  { v = x; x binop= expr; }
12350             //  { v = x; x = x binop expr; }
12351             //  { v = x; x = expr binop x; }
12352             // Check that the first expression has form v = x.
12353             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
12354             llvm::FoldingSetNodeID XId, PossibleXId;
12355             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
12356             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
12357             IsUpdateExprFound = XId == PossibleXId;
12358             if (IsUpdateExprFound) {
12359               V = BinOp->getLHS();
12360               X = Checker.getX();
12361               E = Checker.getExpr();
12362               UE = Checker.getUpdateExpr();
12363               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12364               IsPostfixUpdate = true;
12365             }
12366           }
12367           if (!IsUpdateExprFound) {
12368             IsUpdateExprFound = !Checker.checkStatement(First);
12369             BinOp = nullptr;
12370             if (IsUpdateExprFound) {
12371               BinOp = dyn_cast<BinaryOperator>(Second);
12372               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
12373             }
12374             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
12375               //  { x++; v = x; }
12376               //  { x--; v = x; }
12377               //  { ++x; v = x; }
12378               //  { --x; v = x; }
12379               //  { x binop= expr; v = x; }
12380               //  { x = x binop expr; v = x; }
12381               //  { x = expr binop x; v = x; }
12382               // Check that the second expression has form v = x.
12383               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
12384               llvm::FoldingSetNodeID XId, PossibleXId;
12385               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
12386               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
12387               IsUpdateExprFound = XId == PossibleXId;
12388               if (IsUpdateExprFound) {
12389                 V = BinOp->getLHS();
12390                 X = Checker.getX();
12391                 E = Checker.getExpr();
12392                 UE = Checker.getUpdateExpr();
12393                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12394                 IsPostfixUpdate = false;
12395               }
12396             }
12397           }
12398           if (!IsUpdateExprFound) {
12399             //  { v = x; x = expr; }
12400             auto *FirstExpr = dyn_cast<Expr>(First);
12401             auto *SecondExpr = dyn_cast<Expr>(Second);
12402             if (!FirstExpr || !SecondExpr ||
12403                 !(FirstExpr->isInstantiationDependent() ||
12404                   SecondExpr->isInstantiationDependent())) {
12405               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
12406               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
12407                 ErrorFound = NotAnAssignmentOp;
12408                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
12409                                                 : First->getBeginLoc();
12410                 NoteRange = ErrorRange = FirstBinOp
12411                                              ? FirstBinOp->getSourceRange()
12412                                              : SourceRange(ErrorLoc, ErrorLoc);
12413               } else {
12414                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
12415                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
12416                   ErrorFound = NotAnAssignmentOp;
12417                   NoteLoc = ErrorLoc = SecondBinOp
12418                                            ? SecondBinOp->getOperatorLoc()
12419                                            : Second->getBeginLoc();
12420                   NoteRange = ErrorRange =
12421                       SecondBinOp ? SecondBinOp->getSourceRange()
12422                                   : SourceRange(ErrorLoc, ErrorLoc);
12423                 } else {
12424                   Expr *PossibleXRHSInFirst =
12425                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
12426                   Expr *PossibleXLHSInSecond =
12427                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
12428                   llvm::FoldingSetNodeID X1Id, X2Id;
12429                   PossibleXRHSInFirst->Profile(X1Id, Context,
12430                                                /*Canonical=*/true);
12431                   PossibleXLHSInSecond->Profile(X2Id, Context,
12432                                                 /*Canonical=*/true);
12433                   IsUpdateExprFound = X1Id == X2Id;
12434                   if (IsUpdateExprFound) {
12435                     V = FirstBinOp->getLHS();
12436                     X = SecondBinOp->getLHS();
12437                     E = SecondBinOp->getRHS();
12438                     UE = nullptr;
12439                     IsXLHSInRHSPart = false;
12440                     IsPostfixUpdate = true;
12441                   } else {
12442                     ErrorFound = NotASpecificExpression;
12443                     ErrorLoc = FirstBinOp->getExprLoc();
12444                     ErrorRange = FirstBinOp->getSourceRange();
12445                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
12446                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
12447                   }
12448                 }
12449               }
12450             }
12451           }
12452         } else {
12453           NoteLoc = ErrorLoc = Body->getBeginLoc();
12454           NoteRange = ErrorRange =
12455               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
12456           ErrorFound = NotTwoSubstatements;
12457         }
12458       } else {
12459         NoteLoc = ErrorLoc = Body->getBeginLoc();
12460         NoteRange = ErrorRange =
12461             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
12462         ErrorFound = NotACompoundStatement;
12463       }
12464     }
12465     if (ErrorFound != NoError) {
12466       Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
12467           << ErrorRange;
12468       Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
12469       return StmtError();
12470     }
12471     if (CurContext->isDependentContext())
12472       UE = V = E = X = nullptr;
12473   } else if (AtomicKind == OMPC_compare) {
12474     if (IsCompareCapture) {
12475       OpenMPAtomicCompareCaptureChecker::ErrorInfoTy ErrorInfo;
12476       OpenMPAtomicCompareCaptureChecker Checker(*this);
12477       if (!Checker.checkStmt(Body, ErrorInfo)) {
12478         Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare_capture)
12479             << ErrorInfo.ErrorRange;
12480         Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
12481             << ErrorInfo.Error << ErrorInfo.NoteRange;
12482         return StmtError();
12483       }
12484       // TODO: We don't set X, D, E, etc. here because in code gen we will emit
12485       // error directly.
12486     } else {
12487       OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo;
12488       OpenMPAtomicCompareChecker Checker(*this);
12489       if (!Checker.checkStmt(Body, ErrorInfo)) {
12490         Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare)
12491             << ErrorInfo.ErrorRange;
12492         Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
12493             << ErrorInfo.Error << ErrorInfo.NoteRange;
12494         return StmtError();
12495       }
12496       X = Checker.getX();
12497       E = Checker.getE();
12498       D = Checker.getD();
12499       CE = Checker.getCond();
12500       // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'.
12501       IsXLHSInRHSPart = Checker.isXBinopExpr();
12502     }
12503   }
12504 
12505   setFunctionHasBranchProtectedScope();
12506 
12507   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
12508                                     X, V, E, UE, D, CE, IsXLHSInRHSPart,
12509                                     IsPostfixUpdate);
12510 }
12511 
12512 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
12513                                             Stmt *AStmt,
12514                                             SourceLocation StartLoc,
12515                                             SourceLocation EndLoc) {
12516   if (!AStmt)
12517     return StmtError();
12518 
12519   auto *CS = cast<CapturedStmt>(AStmt);
12520   // 1.2.2 OpenMP Language Terminology
12521   // Structured block - An executable statement with a single entry at the
12522   // top and a single exit at the bottom.
12523   // The point of exit cannot be a branch out of the structured block.
12524   // longjmp() and throw() must not violate the entry/exit criteria.
12525   CS->getCapturedDecl()->setNothrow();
12526   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
12527        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12528     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12529     // 1.2.2 OpenMP Language Terminology
12530     // Structured block - An executable statement with a single entry at the
12531     // top and a single exit at the bottom.
12532     // The point of exit cannot be a branch out of the structured block.
12533     // longjmp() and throw() must not violate the entry/exit criteria.
12534     CS->getCapturedDecl()->setNothrow();
12535   }
12536 
12537   // OpenMP [2.16, Nesting of Regions]
12538   // If specified, a teams construct must be contained within a target
12539   // construct. That target construct must contain no statements or directives
12540   // outside of the teams construct.
12541   if (DSAStack->hasInnerTeamsRegion()) {
12542     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
12543     bool OMPTeamsFound = true;
12544     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
12545       auto I = CS->body_begin();
12546       while (I != CS->body_end()) {
12547         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
12548         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
12549             OMPTeamsFound) {
12550 
12551           OMPTeamsFound = false;
12552           break;
12553         }
12554         ++I;
12555       }
12556       assert(I != CS->body_end() && "Not found statement");
12557       S = *I;
12558     } else {
12559       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
12560       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
12561     }
12562     if (!OMPTeamsFound) {
12563       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
12564       Diag(DSAStack->getInnerTeamsRegionLoc(),
12565            diag::note_omp_nested_teams_construct_here);
12566       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
12567           << isa<OMPExecutableDirective>(S);
12568       return StmtError();
12569     }
12570   }
12571 
12572   setFunctionHasBranchProtectedScope();
12573 
12574   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
12575 }
12576 
12577 StmtResult
12578 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
12579                                          Stmt *AStmt, SourceLocation StartLoc,
12580                                          SourceLocation EndLoc) {
12581   if (!AStmt)
12582     return StmtError();
12583 
12584   auto *CS = cast<CapturedStmt>(AStmt);
12585   // 1.2.2 OpenMP Language Terminology
12586   // Structured block - An executable statement with a single entry at the
12587   // top and a single exit at the bottom.
12588   // The point of exit cannot be a branch out of the structured block.
12589   // longjmp() and throw() must not violate the entry/exit criteria.
12590   CS->getCapturedDecl()->setNothrow();
12591   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
12592        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12593     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12594     // 1.2.2 OpenMP Language Terminology
12595     // Structured block - An executable statement with a single entry at the
12596     // top and a single exit at the bottom.
12597     // The point of exit cannot be a branch out of the structured block.
12598     // longjmp() and throw() must not violate the entry/exit criteria.
12599     CS->getCapturedDecl()->setNothrow();
12600   }
12601 
12602   setFunctionHasBranchProtectedScope();
12603 
12604   return OMPTargetParallelDirective::Create(
12605       Context, StartLoc, EndLoc, Clauses, AStmt,
12606       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12607 }
12608 
12609 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
12610     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12611     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12612   if (!AStmt)
12613     return StmtError();
12614 
12615   auto *CS = cast<CapturedStmt>(AStmt);
12616   // 1.2.2 OpenMP Language Terminology
12617   // Structured block - An executable statement with a single entry at the
12618   // top and a single exit at the bottom.
12619   // The point of exit cannot be a branch out of the structured block.
12620   // longjmp() and throw() must not violate the entry/exit criteria.
12621   CS->getCapturedDecl()->setNothrow();
12622   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12623        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12624     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12625     // 1.2.2 OpenMP Language Terminology
12626     // Structured block - An executable statement with a single entry at the
12627     // top and a single exit at the bottom.
12628     // The point of exit cannot be a branch out of the structured block.
12629     // longjmp() and throw() must not violate the entry/exit criteria.
12630     CS->getCapturedDecl()->setNothrow();
12631   }
12632 
12633   OMPLoopBasedDirective::HelperExprs B;
12634   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12635   // define the nested loops number.
12636   unsigned NestedLoopCount =
12637       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
12638                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12639                       VarsWithImplicitDSA, B);
12640   if (NestedLoopCount == 0)
12641     return StmtError();
12642 
12643   assert((CurContext->isDependentContext() || B.builtAll()) &&
12644          "omp target parallel for loop exprs were not built");
12645 
12646   if (!CurContext->isDependentContext()) {
12647     // Finalize the clauses that need pre-built expressions for CodeGen.
12648     for (OMPClause *C : Clauses) {
12649       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12650         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12651                                      B.NumIterations, *this, CurScope,
12652                                      DSAStack))
12653           return StmtError();
12654     }
12655   }
12656 
12657   setFunctionHasBranchProtectedScope();
12658   return OMPTargetParallelForDirective::Create(
12659       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12660       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12661 }
12662 
12663 /// Check for existence of a map clause in the list of clauses.
12664 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
12665                        const OpenMPClauseKind K) {
12666   return llvm::any_of(
12667       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
12668 }
12669 
12670 template <typename... Params>
12671 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
12672                        const Params... ClauseTypes) {
12673   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
12674 }
12675 
12676 /// Check if the variables in the mapping clause are externally visible.
12677 static bool isClauseMappable(ArrayRef<OMPClause *> Clauses) {
12678   for (const OMPClause *C : Clauses) {
12679     if (auto *TC = dyn_cast<OMPToClause>(C))
12680       return llvm::all_of(TC->all_decls(), [](ValueDecl *VD) {
12681         return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
12682                (VD->isExternallyVisible() &&
12683                 VD->getVisibility() != HiddenVisibility);
12684       });
12685     else if (auto *FC = dyn_cast<OMPFromClause>(C))
12686       return llvm::all_of(FC->all_decls(), [](ValueDecl *VD) {
12687         return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
12688                (VD->isExternallyVisible() &&
12689                 VD->getVisibility() != HiddenVisibility);
12690       });
12691   }
12692 
12693   return true;
12694 }
12695 
12696 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
12697                                                 Stmt *AStmt,
12698                                                 SourceLocation StartLoc,
12699                                                 SourceLocation EndLoc) {
12700   if (!AStmt)
12701     return StmtError();
12702 
12703   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12704 
12705   // OpenMP [2.12.2, target data Construct, Restrictions]
12706   // At least one map, use_device_addr or use_device_ptr clause must appear on
12707   // the directive.
12708   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
12709       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
12710     StringRef Expected;
12711     if (LangOpts.OpenMP < 50)
12712       Expected = "'map' or 'use_device_ptr'";
12713     else
12714       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
12715     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12716         << Expected << getOpenMPDirectiveName(OMPD_target_data);
12717     return StmtError();
12718   }
12719 
12720   setFunctionHasBranchProtectedScope();
12721 
12722   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12723                                         AStmt);
12724 }
12725 
12726 StmtResult
12727 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
12728                                           SourceLocation StartLoc,
12729                                           SourceLocation EndLoc, Stmt *AStmt) {
12730   if (!AStmt)
12731     return StmtError();
12732 
12733   auto *CS = cast<CapturedStmt>(AStmt);
12734   // 1.2.2 OpenMP Language Terminology
12735   // Structured block - An executable statement with a single entry at the
12736   // top and a single exit at the bottom.
12737   // The point of exit cannot be a branch out of the structured block.
12738   // longjmp() and throw() must not violate the entry/exit criteria.
12739   CS->getCapturedDecl()->setNothrow();
12740   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
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   // OpenMP [2.10.2, Restrictions, p. 99]
12752   // At least one map clause must appear on the directive.
12753   if (!hasClauses(Clauses, OMPC_map)) {
12754     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12755         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
12756     return StmtError();
12757   }
12758 
12759   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12760                                              AStmt);
12761 }
12762 
12763 StmtResult
12764 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
12765                                          SourceLocation StartLoc,
12766                                          SourceLocation EndLoc, Stmt *AStmt) {
12767   if (!AStmt)
12768     return StmtError();
12769 
12770   auto *CS = cast<CapturedStmt>(AStmt);
12771   // 1.2.2 OpenMP Language Terminology
12772   // Structured block - An executable statement with a single entry at the
12773   // top and a single exit at the bottom.
12774   // The point of exit cannot be a branch out of the structured block.
12775   // longjmp() and throw() must not violate the entry/exit criteria.
12776   CS->getCapturedDecl()->setNothrow();
12777   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
12778        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12779     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12780     // 1.2.2 OpenMP Language Terminology
12781     // Structured block - An executable statement with a single entry at the
12782     // top and a single exit at the bottom.
12783     // The point of exit cannot be a branch out of the structured block.
12784     // longjmp() and throw() must not violate the entry/exit criteria.
12785     CS->getCapturedDecl()->setNothrow();
12786   }
12787 
12788   // OpenMP [2.10.3, Restrictions, p. 102]
12789   // At least one map clause must appear on the directive.
12790   if (!hasClauses(Clauses, OMPC_map)) {
12791     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12792         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
12793     return StmtError();
12794   }
12795 
12796   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12797                                             AStmt);
12798 }
12799 
12800 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
12801                                                   SourceLocation StartLoc,
12802                                                   SourceLocation EndLoc,
12803                                                   Stmt *AStmt) {
12804   if (!AStmt)
12805     return StmtError();
12806 
12807   auto *CS = cast<CapturedStmt>(AStmt);
12808   // 1.2.2 OpenMP Language Terminology
12809   // Structured block - An executable statement with a single entry at the
12810   // top and a single exit at the bottom.
12811   // The point of exit cannot be a branch out of the structured block.
12812   // longjmp() and throw() must not violate the entry/exit criteria.
12813   CS->getCapturedDecl()->setNothrow();
12814   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
12815        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12816     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12817     // 1.2.2 OpenMP Language Terminology
12818     // Structured block - An executable statement with a single entry at the
12819     // top and a single exit at the bottom.
12820     // The point of exit cannot be a branch out of the structured block.
12821     // longjmp() and throw() must not violate the entry/exit criteria.
12822     CS->getCapturedDecl()->setNothrow();
12823   }
12824 
12825   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
12826     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
12827     return StmtError();
12828   }
12829 
12830   if (!isClauseMappable(Clauses)) {
12831     Diag(StartLoc, diag::err_omp_cannot_update_with_internal_linkage);
12832     return StmtError();
12833   }
12834 
12835   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
12836                                           AStmt);
12837 }
12838 
12839 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
12840                                            Stmt *AStmt, SourceLocation StartLoc,
12841                                            SourceLocation EndLoc) {
12842   if (!AStmt)
12843     return StmtError();
12844 
12845   auto *CS = cast<CapturedStmt>(AStmt);
12846   // 1.2.2 OpenMP Language Terminology
12847   // Structured block - An executable statement with a single entry at the
12848   // top and a single exit at the bottom.
12849   // The point of exit cannot be a branch out of the structured block.
12850   // longjmp() and throw() must not violate the entry/exit criteria.
12851   CS->getCapturedDecl()->setNothrow();
12852 
12853   setFunctionHasBranchProtectedScope();
12854 
12855   DSAStack->setParentTeamsRegionLoc(StartLoc);
12856 
12857   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
12858 }
12859 
12860 StmtResult
12861 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
12862                                             SourceLocation EndLoc,
12863                                             OpenMPDirectiveKind CancelRegion) {
12864   if (DSAStack->isParentNowaitRegion()) {
12865     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
12866     return StmtError();
12867   }
12868   if (DSAStack->isParentOrderedRegion()) {
12869     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
12870     return StmtError();
12871   }
12872   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
12873                                                CancelRegion);
12874 }
12875 
12876 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
12877                                             SourceLocation StartLoc,
12878                                             SourceLocation EndLoc,
12879                                             OpenMPDirectiveKind CancelRegion) {
12880   if (DSAStack->isParentNowaitRegion()) {
12881     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
12882     return StmtError();
12883   }
12884   if (DSAStack->isParentOrderedRegion()) {
12885     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
12886     return StmtError();
12887   }
12888   DSAStack->setParentCancelRegion(/*Cancel=*/true);
12889   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
12890                                     CancelRegion);
12891 }
12892 
12893 static bool checkReductionClauseWithNogroup(Sema &S,
12894                                             ArrayRef<OMPClause *> Clauses) {
12895   const OMPClause *ReductionClause = nullptr;
12896   const OMPClause *NogroupClause = nullptr;
12897   for (const OMPClause *C : Clauses) {
12898     if (C->getClauseKind() == OMPC_reduction) {
12899       ReductionClause = C;
12900       if (NogroupClause)
12901         break;
12902       continue;
12903     }
12904     if (C->getClauseKind() == OMPC_nogroup) {
12905       NogroupClause = C;
12906       if (ReductionClause)
12907         break;
12908       continue;
12909     }
12910   }
12911   if (ReductionClause && NogroupClause) {
12912     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
12913         << SourceRange(NogroupClause->getBeginLoc(),
12914                        NogroupClause->getEndLoc());
12915     return true;
12916   }
12917   return false;
12918 }
12919 
12920 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
12921     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12922     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12923   if (!AStmt)
12924     return StmtError();
12925 
12926   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12927   OMPLoopBasedDirective::HelperExprs B;
12928   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12929   // define the nested loops number.
12930   unsigned NestedLoopCount =
12931       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
12932                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12933                       VarsWithImplicitDSA, B);
12934   if (NestedLoopCount == 0)
12935     return StmtError();
12936 
12937   assert((CurContext->isDependentContext() || B.builtAll()) &&
12938          "omp for loop exprs were not built");
12939 
12940   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12941   // The grainsize clause and num_tasks clause are mutually exclusive and may
12942   // not appear on the same taskloop directive.
12943   if (checkMutuallyExclusiveClauses(*this, Clauses,
12944                                     {OMPC_grainsize, OMPC_num_tasks}))
12945     return StmtError();
12946   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12947   // If a reduction clause is present on the taskloop directive, the nogroup
12948   // clause must not be specified.
12949   if (checkReductionClauseWithNogroup(*this, Clauses))
12950     return StmtError();
12951 
12952   setFunctionHasBranchProtectedScope();
12953   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
12954                                       NestedLoopCount, Clauses, AStmt, B,
12955                                       DSAStack->isCancelRegion());
12956 }
12957 
12958 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
12959     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12960     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12961   if (!AStmt)
12962     return StmtError();
12963 
12964   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12965   OMPLoopBasedDirective::HelperExprs B;
12966   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12967   // define the nested loops number.
12968   unsigned NestedLoopCount =
12969       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
12970                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12971                       VarsWithImplicitDSA, B);
12972   if (NestedLoopCount == 0)
12973     return StmtError();
12974 
12975   assert((CurContext->isDependentContext() || B.builtAll()) &&
12976          "omp for loop exprs were not built");
12977 
12978   if (!CurContext->isDependentContext()) {
12979     // Finalize the clauses that need pre-built expressions for CodeGen.
12980     for (OMPClause *C : Clauses) {
12981       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12982         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12983                                      B.NumIterations, *this, CurScope,
12984                                      DSAStack))
12985           return StmtError();
12986     }
12987   }
12988 
12989   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12990   // The grainsize clause and num_tasks clause are mutually exclusive and may
12991   // not appear on the same taskloop directive.
12992   if (checkMutuallyExclusiveClauses(*this, Clauses,
12993                                     {OMPC_grainsize, OMPC_num_tasks}))
12994     return StmtError();
12995   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12996   // If a reduction clause is present on the taskloop directive, the nogroup
12997   // clause must not be specified.
12998   if (checkReductionClauseWithNogroup(*this, Clauses))
12999     return StmtError();
13000   if (checkSimdlenSafelenSpecified(*this, Clauses))
13001     return StmtError();
13002 
13003   setFunctionHasBranchProtectedScope();
13004   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
13005                                           NestedLoopCount, Clauses, AStmt, B);
13006 }
13007 
13008 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
13009     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13010     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13011   if (!AStmt)
13012     return StmtError();
13013 
13014   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13015   OMPLoopBasedDirective::HelperExprs B;
13016   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13017   // define the nested loops number.
13018   unsigned NestedLoopCount =
13019       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
13020                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
13021                       VarsWithImplicitDSA, B);
13022   if (NestedLoopCount == 0)
13023     return StmtError();
13024 
13025   assert((CurContext->isDependentContext() || B.builtAll()) &&
13026          "omp for loop exprs were not built");
13027 
13028   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13029   // The grainsize clause and num_tasks clause are mutually exclusive and may
13030   // not appear on the same taskloop directive.
13031   if (checkMutuallyExclusiveClauses(*this, Clauses,
13032                                     {OMPC_grainsize, OMPC_num_tasks}))
13033     return StmtError();
13034   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13035   // If a reduction clause is present on the taskloop directive, the nogroup
13036   // clause must not be specified.
13037   if (checkReductionClauseWithNogroup(*this, Clauses))
13038     return StmtError();
13039 
13040   setFunctionHasBranchProtectedScope();
13041   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
13042                                             NestedLoopCount, Clauses, AStmt, B,
13043                                             DSAStack->isCancelRegion());
13044 }
13045 
13046 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
13047     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13048     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13049   if (!AStmt)
13050     return StmtError();
13051 
13052   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13053   OMPLoopBasedDirective::HelperExprs B;
13054   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13055   // define the nested loops number.
13056   unsigned NestedLoopCount =
13057       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
13058                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
13059                       VarsWithImplicitDSA, B);
13060   if (NestedLoopCount == 0)
13061     return StmtError();
13062 
13063   assert((CurContext->isDependentContext() || B.builtAll()) &&
13064          "omp for loop exprs were not built");
13065 
13066   if (!CurContext->isDependentContext()) {
13067     // Finalize the clauses that need pre-built expressions for CodeGen.
13068     for (OMPClause *C : Clauses) {
13069       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13070         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13071                                      B.NumIterations, *this, CurScope,
13072                                      DSAStack))
13073           return StmtError();
13074     }
13075   }
13076 
13077   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13078   // The grainsize clause and num_tasks clause are mutually exclusive and may
13079   // not appear on the same taskloop directive.
13080   if (checkMutuallyExclusiveClauses(*this, Clauses,
13081                                     {OMPC_grainsize, OMPC_num_tasks}))
13082     return StmtError();
13083   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13084   // If a reduction clause is present on the taskloop directive, the nogroup
13085   // clause must not be specified.
13086   if (checkReductionClauseWithNogroup(*this, Clauses))
13087     return StmtError();
13088   if (checkSimdlenSafelenSpecified(*this, Clauses))
13089     return StmtError();
13090 
13091   setFunctionHasBranchProtectedScope();
13092   return OMPMasterTaskLoopSimdDirective::Create(
13093       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13094 }
13095 
13096 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
13097     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13098     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13099   if (!AStmt)
13100     return StmtError();
13101 
13102   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13103   auto *CS = cast<CapturedStmt>(AStmt);
13104   // 1.2.2 OpenMP Language Terminology
13105   // Structured block - An executable statement with a single entry at the
13106   // top and a single exit at the bottom.
13107   // The point of exit cannot be a branch out of the structured block.
13108   // longjmp() and throw() must not violate the entry/exit criteria.
13109   CS->getCapturedDecl()->setNothrow();
13110   for (int ThisCaptureLevel =
13111            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
13112        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13113     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13114     // 1.2.2 OpenMP Language Terminology
13115     // Structured block - An executable statement with a single entry at the
13116     // top and a single exit at the bottom.
13117     // The point of exit cannot be a branch out of the structured block.
13118     // longjmp() and throw() must not violate the entry/exit criteria.
13119     CS->getCapturedDecl()->setNothrow();
13120   }
13121 
13122   OMPLoopBasedDirective::HelperExprs B;
13123   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13124   // define the nested loops number.
13125   unsigned NestedLoopCount = checkOpenMPLoop(
13126       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
13127       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
13128       VarsWithImplicitDSA, B);
13129   if (NestedLoopCount == 0)
13130     return StmtError();
13131 
13132   assert((CurContext->isDependentContext() || B.builtAll()) &&
13133          "omp for loop exprs were not built");
13134 
13135   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13136   // The grainsize clause and num_tasks clause are mutually exclusive and may
13137   // not appear on the same taskloop directive.
13138   if (checkMutuallyExclusiveClauses(*this, Clauses,
13139                                     {OMPC_grainsize, OMPC_num_tasks}))
13140     return StmtError();
13141   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13142   // If a reduction clause is present on the taskloop directive, the nogroup
13143   // clause must not be specified.
13144   if (checkReductionClauseWithNogroup(*this, Clauses))
13145     return StmtError();
13146 
13147   setFunctionHasBranchProtectedScope();
13148   return OMPParallelMasterTaskLoopDirective::Create(
13149       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13150       DSAStack->isCancelRegion());
13151 }
13152 
13153 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
13154     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13155     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13156   if (!AStmt)
13157     return StmtError();
13158 
13159   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13160   auto *CS = cast<CapturedStmt>(AStmt);
13161   // 1.2.2 OpenMP Language Terminology
13162   // Structured block - An executable statement with a single entry at the
13163   // top and a single exit at the bottom.
13164   // The point of exit cannot be a branch out of the structured block.
13165   // longjmp() and throw() must not violate the entry/exit criteria.
13166   CS->getCapturedDecl()->setNothrow();
13167   for (int ThisCaptureLevel =
13168            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
13169        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13170     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13171     // 1.2.2 OpenMP Language Terminology
13172     // Structured block - An executable statement with a single entry at the
13173     // top and a single exit at the bottom.
13174     // The point of exit cannot be a branch out of the structured block.
13175     // longjmp() and throw() must not violate the entry/exit criteria.
13176     CS->getCapturedDecl()->setNothrow();
13177   }
13178 
13179   OMPLoopBasedDirective::HelperExprs B;
13180   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13181   // define the nested loops number.
13182   unsigned NestedLoopCount = checkOpenMPLoop(
13183       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
13184       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
13185       VarsWithImplicitDSA, B);
13186   if (NestedLoopCount == 0)
13187     return StmtError();
13188 
13189   assert((CurContext->isDependentContext() || B.builtAll()) &&
13190          "omp for loop exprs were not built");
13191 
13192   if (!CurContext->isDependentContext()) {
13193     // Finalize the clauses that need pre-built expressions for CodeGen.
13194     for (OMPClause *C : Clauses) {
13195       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13196         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13197                                      B.NumIterations, *this, CurScope,
13198                                      DSAStack))
13199           return StmtError();
13200     }
13201   }
13202 
13203   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13204   // The grainsize clause and num_tasks clause are mutually exclusive and may
13205   // not appear on the same taskloop directive.
13206   if (checkMutuallyExclusiveClauses(*this, Clauses,
13207                                     {OMPC_grainsize, OMPC_num_tasks}))
13208     return StmtError();
13209   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13210   // If a reduction clause is present on the taskloop directive, the nogroup
13211   // clause must not be specified.
13212   if (checkReductionClauseWithNogroup(*this, Clauses))
13213     return StmtError();
13214   if (checkSimdlenSafelenSpecified(*this, Clauses))
13215     return StmtError();
13216 
13217   setFunctionHasBranchProtectedScope();
13218   return OMPParallelMasterTaskLoopSimdDirective::Create(
13219       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13220 }
13221 
13222 StmtResult Sema::ActOnOpenMPDistributeDirective(
13223     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13224     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13225   if (!AStmt)
13226     return StmtError();
13227 
13228   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13229   OMPLoopBasedDirective::HelperExprs B;
13230   // In presence of clause 'collapse' with number of loops, it will
13231   // define the nested loops number.
13232   unsigned NestedLoopCount =
13233       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
13234                       nullptr /*ordered not a clause on distribute*/, AStmt,
13235                       *this, *DSAStack, VarsWithImplicitDSA, B);
13236   if (NestedLoopCount == 0)
13237     return StmtError();
13238 
13239   assert((CurContext->isDependentContext() || B.builtAll()) &&
13240          "omp for loop exprs were not built");
13241 
13242   setFunctionHasBranchProtectedScope();
13243   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
13244                                         NestedLoopCount, Clauses, AStmt, B);
13245 }
13246 
13247 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
13248     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13249     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13250   if (!AStmt)
13251     return StmtError();
13252 
13253   auto *CS = cast<CapturedStmt>(AStmt);
13254   // 1.2.2 OpenMP Language Terminology
13255   // Structured block - An executable statement with a single entry at the
13256   // top and a single exit at the bottom.
13257   // The point of exit cannot be a branch out of the structured block.
13258   // longjmp() and throw() must not violate the entry/exit criteria.
13259   CS->getCapturedDecl()->setNothrow();
13260   for (int ThisCaptureLevel =
13261            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
13262        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13263     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13264     // 1.2.2 OpenMP Language Terminology
13265     // Structured block - An executable statement with a single entry at the
13266     // top and a single exit at the bottom.
13267     // The point of exit cannot be a branch out of the structured block.
13268     // longjmp() and throw() must not violate the entry/exit criteria.
13269     CS->getCapturedDecl()->setNothrow();
13270   }
13271 
13272   OMPLoopBasedDirective::HelperExprs B;
13273   // In presence of clause 'collapse' with number of loops, it will
13274   // define the nested loops number.
13275   unsigned NestedLoopCount = checkOpenMPLoop(
13276       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13277       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13278       VarsWithImplicitDSA, B);
13279   if (NestedLoopCount == 0)
13280     return StmtError();
13281 
13282   assert((CurContext->isDependentContext() || B.builtAll()) &&
13283          "omp for loop exprs were not built");
13284 
13285   setFunctionHasBranchProtectedScope();
13286   return OMPDistributeParallelForDirective::Create(
13287       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13288       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13289 }
13290 
13291 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
13292     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13293     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13294   if (!AStmt)
13295     return StmtError();
13296 
13297   auto *CS = cast<CapturedStmt>(AStmt);
13298   // 1.2.2 OpenMP Language Terminology
13299   // Structured block - An executable statement with a single entry at the
13300   // top and a single exit at the bottom.
13301   // The point of exit cannot be a branch out of the structured block.
13302   // longjmp() and throw() must not violate the entry/exit criteria.
13303   CS->getCapturedDecl()->setNothrow();
13304   for (int ThisCaptureLevel =
13305            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
13306        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13307     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13308     // 1.2.2 OpenMP Language Terminology
13309     // Structured block - An executable statement with a single entry at the
13310     // top and a single exit at the bottom.
13311     // The point of exit cannot be a branch out of the structured block.
13312     // longjmp() and throw() must not violate the entry/exit criteria.
13313     CS->getCapturedDecl()->setNothrow();
13314   }
13315 
13316   OMPLoopBasedDirective::HelperExprs B;
13317   // In presence of clause 'collapse' with number of loops, it will
13318   // define the nested loops number.
13319   unsigned NestedLoopCount = checkOpenMPLoop(
13320       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
13321       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13322       VarsWithImplicitDSA, B);
13323   if (NestedLoopCount == 0)
13324     return StmtError();
13325 
13326   assert((CurContext->isDependentContext() || B.builtAll()) &&
13327          "omp for loop exprs were not built");
13328 
13329   if (!CurContext->isDependentContext()) {
13330     // Finalize the clauses that need pre-built expressions for CodeGen.
13331     for (OMPClause *C : Clauses) {
13332       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13333         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13334                                      B.NumIterations, *this, CurScope,
13335                                      DSAStack))
13336           return StmtError();
13337     }
13338   }
13339 
13340   if (checkSimdlenSafelenSpecified(*this, Clauses))
13341     return StmtError();
13342 
13343   setFunctionHasBranchProtectedScope();
13344   return OMPDistributeParallelForSimdDirective::Create(
13345       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13346 }
13347 
13348 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
13349     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13350     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13351   if (!AStmt)
13352     return StmtError();
13353 
13354   auto *CS = cast<CapturedStmt>(AStmt);
13355   // 1.2.2 OpenMP Language Terminology
13356   // Structured block - An executable statement with a single entry at the
13357   // top and a single exit at the bottom.
13358   // The point of exit cannot be a branch out of the structured block.
13359   // longjmp() and throw() must not violate the entry/exit criteria.
13360   CS->getCapturedDecl()->setNothrow();
13361   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
13362        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13363     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13364     // 1.2.2 OpenMP Language Terminology
13365     // Structured block - An executable statement with a single entry at the
13366     // top and a single exit at the bottom.
13367     // The point of exit cannot be a branch out of the structured block.
13368     // longjmp() and throw() must not violate the entry/exit criteria.
13369     CS->getCapturedDecl()->setNothrow();
13370   }
13371 
13372   OMPLoopBasedDirective::HelperExprs B;
13373   // In presence of clause 'collapse' with number of loops, it will
13374   // define the nested loops number.
13375   unsigned NestedLoopCount =
13376       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
13377                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13378                       *DSAStack, VarsWithImplicitDSA, B);
13379   if (NestedLoopCount == 0)
13380     return StmtError();
13381 
13382   assert((CurContext->isDependentContext() || B.builtAll()) &&
13383          "omp for loop exprs were not built");
13384 
13385   if (!CurContext->isDependentContext()) {
13386     // Finalize the clauses that need pre-built expressions for CodeGen.
13387     for (OMPClause *C : Clauses) {
13388       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13389         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13390                                      B.NumIterations, *this, CurScope,
13391                                      DSAStack))
13392           return StmtError();
13393     }
13394   }
13395 
13396   if (checkSimdlenSafelenSpecified(*this, Clauses))
13397     return StmtError();
13398 
13399   setFunctionHasBranchProtectedScope();
13400   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
13401                                             NestedLoopCount, Clauses, AStmt, B);
13402 }
13403 
13404 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
13405     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13406     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13407   if (!AStmt)
13408     return StmtError();
13409 
13410   auto *CS = cast<CapturedStmt>(AStmt);
13411   // 1.2.2 OpenMP Language Terminology
13412   // Structured block - An executable statement with a single entry at the
13413   // top and a single exit at the bottom.
13414   // The point of exit cannot be a branch out of the structured block.
13415   // longjmp() and throw() must not violate the entry/exit criteria.
13416   CS->getCapturedDecl()->setNothrow();
13417   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
13418        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13419     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13420     // 1.2.2 OpenMP Language Terminology
13421     // Structured block - An executable statement with a single entry at the
13422     // top and a single exit at the bottom.
13423     // The point of exit cannot be a branch out of the structured block.
13424     // longjmp() and throw() must not violate the entry/exit criteria.
13425     CS->getCapturedDecl()->setNothrow();
13426   }
13427 
13428   OMPLoopBasedDirective::HelperExprs B;
13429   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13430   // define the nested loops number.
13431   unsigned NestedLoopCount = checkOpenMPLoop(
13432       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
13433       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
13434       B);
13435   if (NestedLoopCount == 0)
13436     return StmtError();
13437 
13438   assert((CurContext->isDependentContext() || B.builtAll()) &&
13439          "omp target parallel for simd loop exprs were not built");
13440 
13441   if (!CurContext->isDependentContext()) {
13442     // Finalize the clauses that need pre-built expressions for CodeGen.
13443     for (OMPClause *C : Clauses) {
13444       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13445         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13446                                      B.NumIterations, *this, CurScope,
13447                                      DSAStack))
13448           return StmtError();
13449     }
13450   }
13451   if (checkSimdlenSafelenSpecified(*this, Clauses))
13452     return StmtError();
13453 
13454   setFunctionHasBranchProtectedScope();
13455   return OMPTargetParallelForSimdDirective::Create(
13456       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13457 }
13458 
13459 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
13460     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13461     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13462   if (!AStmt)
13463     return StmtError();
13464 
13465   auto *CS = cast<CapturedStmt>(AStmt);
13466   // 1.2.2 OpenMP Language Terminology
13467   // Structured block - An executable statement with a single entry at the
13468   // top and a single exit at the bottom.
13469   // The point of exit cannot be a branch out of the structured block.
13470   // longjmp() and throw() must not violate the entry/exit criteria.
13471   CS->getCapturedDecl()->setNothrow();
13472   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
13473        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13474     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13475     // 1.2.2 OpenMP Language Terminology
13476     // Structured block - An executable statement with a single entry at the
13477     // top and a single exit at the bottom.
13478     // The point of exit cannot be a branch out of the structured block.
13479     // longjmp() and throw() must not violate the entry/exit criteria.
13480     CS->getCapturedDecl()->setNothrow();
13481   }
13482 
13483   OMPLoopBasedDirective::HelperExprs B;
13484   // In presence of clause 'collapse' with number of loops, it will define the
13485   // nested loops number.
13486   unsigned NestedLoopCount =
13487       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
13488                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
13489                       VarsWithImplicitDSA, B);
13490   if (NestedLoopCount == 0)
13491     return StmtError();
13492 
13493   assert((CurContext->isDependentContext() || B.builtAll()) &&
13494          "omp target simd loop exprs were not built");
13495 
13496   if (!CurContext->isDependentContext()) {
13497     // Finalize the clauses that need pre-built expressions for CodeGen.
13498     for (OMPClause *C : Clauses) {
13499       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13500         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13501                                      B.NumIterations, *this, CurScope,
13502                                      DSAStack))
13503           return StmtError();
13504     }
13505   }
13506 
13507   if (checkSimdlenSafelenSpecified(*this, Clauses))
13508     return StmtError();
13509 
13510   setFunctionHasBranchProtectedScope();
13511   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
13512                                         NestedLoopCount, Clauses, AStmt, B);
13513 }
13514 
13515 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
13516     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13517     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13518   if (!AStmt)
13519     return StmtError();
13520 
13521   auto *CS = cast<CapturedStmt>(AStmt);
13522   // 1.2.2 OpenMP Language Terminology
13523   // Structured block - An executable statement with a single entry at the
13524   // top and a single exit at the bottom.
13525   // The point of exit cannot be a branch out of the structured block.
13526   // longjmp() and throw() must not violate the entry/exit criteria.
13527   CS->getCapturedDecl()->setNothrow();
13528   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
13529        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13530     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13531     // 1.2.2 OpenMP Language Terminology
13532     // Structured block - An executable statement with a single entry at the
13533     // top and a single exit at the bottom.
13534     // The point of exit cannot be a branch out of the structured block.
13535     // longjmp() and throw() must not violate the entry/exit criteria.
13536     CS->getCapturedDecl()->setNothrow();
13537   }
13538 
13539   OMPLoopBasedDirective::HelperExprs B;
13540   // In presence of clause 'collapse' with number of loops, it will
13541   // define the nested loops number.
13542   unsigned NestedLoopCount =
13543       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
13544                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13545                       *DSAStack, VarsWithImplicitDSA, B);
13546   if (NestedLoopCount == 0)
13547     return StmtError();
13548 
13549   assert((CurContext->isDependentContext() || B.builtAll()) &&
13550          "omp teams distribute loop exprs were not built");
13551 
13552   setFunctionHasBranchProtectedScope();
13553 
13554   DSAStack->setParentTeamsRegionLoc(StartLoc);
13555 
13556   return OMPTeamsDistributeDirective::Create(
13557       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13558 }
13559 
13560 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
13561     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13562     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13563   if (!AStmt)
13564     return StmtError();
13565 
13566   auto *CS = cast<CapturedStmt>(AStmt);
13567   // 1.2.2 OpenMP Language Terminology
13568   // Structured block - An executable statement with a single entry at the
13569   // top and a single exit at the bottom.
13570   // The point of exit cannot be a branch out of the structured block.
13571   // longjmp() and throw() must not violate the entry/exit criteria.
13572   CS->getCapturedDecl()->setNothrow();
13573   for (int ThisCaptureLevel =
13574            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
13575        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13576     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13577     // 1.2.2 OpenMP Language Terminology
13578     // Structured block - An executable statement with a single entry at the
13579     // top and a single exit at the bottom.
13580     // The point of exit cannot be a branch out of the structured block.
13581     // longjmp() and throw() must not violate the entry/exit criteria.
13582     CS->getCapturedDecl()->setNothrow();
13583   }
13584 
13585   OMPLoopBasedDirective::HelperExprs B;
13586   // In presence of clause 'collapse' with number of loops, it will
13587   // define the nested loops number.
13588   unsigned NestedLoopCount = checkOpenMPLoop(
13589       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
13590       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13591       VarsWithImplicitDSA, B);
13592 
13593   if (NestedLoopCount == 0)
13594     return StmtError();
13595 
13596   assert((CurContext->isDependentContext() || B.builtAll()) &&
13597          "omp teams distribute simd loop exprs were not built");
13598 
13599   if (!CurContext->isDependentContext()) {
13600     // Finalize the clauses that need pre-built expressions for CodeGen.
13601     for (OMPClause *C : Clauses) {
13602       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13603         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13604                                      B.NumIterations, *this, CurScope,
13605                                      DSAStack))
13606           return StmtError();
13607     }
13608   }
13609 
13610   if (checkSimdlenSafelenSpecified(*this, Clauses))
13611     return StmtError();
13612 
13613   setFunctionHasBranchProtectedScope();
13614 
13615   DSAStack->setParentTeamsRegionLoc(StartLoc);
13616 
13617   return OMPTeamsDistributeSimdDirective::Create(
13618       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13619 }
13620 
13621 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
13622     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13623     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13624   if (!AStmt)
13625     return StmtError();
13626 
13627   auto *CS = cast<CapturedStmt>(AStmt);
13628   // 1.2.2 OpenMP Language Terminology
13629   // Structured block - An executable statement with a single entry at the
13630   // top and a single exit at the bottom.
13631   // The point of exit cannot be a branch out of the structured block.
13632   // longjmp() and throw() must not violate the entry/exit criteria.
13633   CS->getCapturedDecl()->setNothrow();
13634 
13635   for (int ThisCaptureLevel =
13636            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
13637        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13638     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13639     // 1.2.2 OpenMP Language Terminology
13640     // Structured block - An executable statement with a single entry at the
13641     // top and a single exit at the bottom.
13642     // The point of exit cannot be a branch out of the structured block.
13643     // longjmp() and throw() must not violate the entry/exit criteria.
13644     CS->getCapturedDecl()->setNothrow();
13645   }
13646 
13647   OMPLoopBasedDirective::HelperExprs B;
13648   // In presence of clause 'collapse' with number of loops, it will
13649   // define the nested loops number.
13650   unsigned NestedLoopCount = checkOpenMPLoop(
13651       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
13652       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13653       VarsWithImplicitDSA, B);
13654 
13655   if (NestedLoopCount == 0)
13656     return StmtError();
13657 
13658   assert((CurContext->isDependentContext() || B.builtAll()) &&
13659          "omp for loop exprs were not built");
13660 
13661   if (!CurContext->isDependentContext()) {
13662     // Finalize the clauses that need pre-built expressions for CodeGen.
13663     for (OMPClause *C : Clauses) {
13664       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13665         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13666                                      B.NumIterations, *this, CurScope,
13667                                      DSAStack))
13668           return StmtError();
13669     }
13670   }
13671 
13672   if (checkSimdlenSafelenSpecified(*this, Clauses))
13673     return StmtError();
13674 
13675   setFunctionHasBranchProtectedScope();
13676 
13677   DSAStack->setParentTeamsRegionLoc(StartLoc);
13678 
13679   return OMPTeamsDistributeParallelForSimdDirective::Create(
13680       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13681 }
13682 
13683 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
13684     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13685     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13686   if (!AStmt)
13687     return StmtError();
13688 
13689   auto *CS = cast<CapturedStmt>(AStmt);
13690   // 1.2.2 OpenMP Language Terminology
13691   // Structured block - An executable statement with a single entry at the
13692   // top and a single exit at the bottom.
13693   // The point of exit cannot be a branch out of the structured block.
13694   // longjmp() and throw() must not violate the entry/exit criteria.
13695   CS->getCapturedDecl()->setNothrow();
13696 
13697   for (int ThisCaptureLevel =
13698            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
13699        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13700     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13701     // 1.2.2 OpenMP Language Terminology
13702     // Structured block - An executable statement with a single entry at the
13703     // top and a single exit at the bottom.
13704     // The point of exit cannot be a branch out of the structured block.
13705     // longjmp() and throw() must not violate the entry/exit criteria.
13706     CS->getCapturedDecl()->setNothrow();
13707   }
13708 
13709   OMPLoopBasedDirective::HelperExprs B;
13710   // In presence of clause 'collapse' with number of loops, it will
13711   // define the nested loops number.
13712   unsigned NestedLoopCount = checkOpenMPLoop(
13713       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13714       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13715       VarsWithImplicitDSA, B);
13716 
13717   if (NestedLoopCount == 0)
13718     return StmtError();
13719 
13720   assert((CurContext->isDependentContext() || B.builtAll()) &&
13721          "omp for loop exprs were not built");
13722 
13723   setFunctionHasBranchProtectedScope();
13724 
13725   DSAStack->setParentTeamsRegionLoc(StartLoc);
13726 
13727   return OMPTeamsDistributeParallelForDirective::Create(
13728       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13729       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13730 }
13731 
13732 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
13733                                                  Stmt *AStmt,
13734                                                  SourceLocation StartLoc,
13735                                                  SourceLocation EndLoc) {
13736   if (!AStmt)
13737     return StmtError();
13738 
13739   auto *CS = cast<CapturedStmt>(AStmt);
13740   // 1.2.2 OpenMP Language Terminology
13741   // Structured block - An executable statement with a single entry at the
13742   // top and a single exit at the bottom.
13743   // The point of exit cannot be a branch out of the structured block.
13744   // longjmp() and throw() must not violate the entry/exit criteria.
13745   CS->getCapturedDecl()->setNothrow();
13746 
13747   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
13748        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13749     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13750     // 1.2.2 OpenMP Language Terminology
13751     // Structured block - An executable statement with a single entry at the
13752     // top and a single exit at the bottom.
13753     // The point of exit cannot be a branch out of the structured block.
13754     // longjmp() and throw() must not violate the entry/exit criteria.
13755     CS->getCapturedDecl()->setNothrow();
13756   }
13757   setFunctionHasBranchProtectedScope();
13758 
13759   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
13760                                          AStmt);
13761 }
13762 
13763 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
13764     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13765     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13766   if (!AStmt)
13767     return StmtError();
13768 
13769   auto *CS = cast<CapturedStmt>(AStmt);
13770   // 1.2.2 OpenMP Language Terminology
13771   // Structured block - An executable statement with a single entry at the
13772   // top and a single exit at the bottom.
13773   // The point of exit cannot be a branch out of the structured block.
13774   // longjmp() and throw() must not violate the entry/exit criteria.
13775   CS->getCapturedDecl()->setNothrow();
13776   for (int ThisCaptureLevel =
13777            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
13778        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13779     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13780     // 1.2.2 OpenMP Language Terminology
13781     // Structured block - An executable statement with a single entry at the
13782     // top and a single exit at the bottom.
13783     // The point of exit cannot be a branch out of the structured block.
13784     // longjmp() and throw() must not violate the entry/exit criteria.
13785     CS->getCapturedDecl()->setNothrow();
13786   }
13787 
13788   OMPLoopBasedDirective::HelperExprs B;
13789   // In presence of clause 'collapse' with number of loops, it will
13790   // define the nested loops number.
13791   unsigned NestedLoopCount = checkOpenMPLoop(
13792       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
13793       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13794       VarsWithImplicitDSA, B);
13795   if (NestedLoopCount == 0)
13796     return StmtError();
13797 
13798   assert((CurContext->isDependentContext() || B.builtAll()) &&
13799          "omp target teams distribute loop exprs were not built");
13800 
13801   setFunctionHasBranchProtectedScope();
13802   return OMPTargetTeamsDistributeDirective::Create(
13803       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13804 }
13805 
13806 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
13807     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13808     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13809   if (!AStmt)
13810     return StmtError();
13811 
13812   auto *CS = cast<CapturedStmt>(AStmt);
13813   // 1.2.2 OpenMP Language Terminology
13814   // Structured block - An executable statement with a single entry at the
13815   // top and a single exit at the bottom.
13816   // The point of exit cannot be a branch out of the structured block.
13817   // longjmp() and throw() must not violate the entry/exit criteria.
13818   CS->getCapturedDecl()->setNothrow();
13819   for (int ThisCaptureLevel =
13820            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
13821        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13822     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13823     // 1.2.2 OpenMP Language Terminology
13824     // Structured block - An executable statement with a single entry at the
13825     // top and a single exit at the bottom.
13826     // The point of exit cannot be a branch out of the structured block.
13827     // longjmp() and throw() must not violate the entry/exit criteria.
13828     CS->getCapturedDecl()->setNothrow();
13829   }
13830 
13831   OMPLoopBasedDirective::HelperExprs B;
13832   // In presence of clause 'collapse' with number of loops, it will
13833   // define the nested loops number.
13834   unsigned NestedLoopCount = checkOpenMPLoop(
13835       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13836       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13837       VarsWithImplicitDSA, B);
13838   if (NestedLoopCount == 0)
13839     return StmtError();
13840 
13841   assert((CurContext->isDependentContext() || B.builtAll()) &&
13842          "omp target teams distribute parallel for loop exprs were not built");
13843 
13844   if (!CurContext->isDependentContext()) {
13845     // Finalize the clauses that need pre-built expressions for CodeGen.
13846     for (OMPClause *C : Clauses) {
13847       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13848         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13849                                      B.NumIterations, *this, CurScope,
13850                                      DSAStack))
13851           return StmtError();
13852     }
13853   }
13854 
13855   setFunctionHasBranchProtectedScope();
13856   return OMPTargetTeamsDistributeParallelForDirective::Create(
13857       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13858       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13859 }
13860 
13861 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
13862     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13863     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13864   if (!AStmt)
13865     return StmtError();
13866 
13867   auto *CS = cast<CapturedStmt>(AStmt);
13868   // 1.2.2 OpenMP Language Terminology
13869   // Structured block - An executable statement with a single entry at the
13870   // top and a single exit at the bottom.
13871   // The point of exit cannot be a branch out of the structured block.
13872   // longjmp() and throw() must not violate the entry/exit criteria.
13873   CS->getCapturedDecl()->setNothrow();
13874   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
13875            OMPD_target_teams_distribute_parallel_for_simd);
13876        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13877     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13878     // 1.2.2 OpenMP Language Terminology
13879     // Structured block - An executable statement with a single entry at the
13880     // top and a single exit at the bottom.
13881     // The point of exit cannot be a branch out of the structured block.
13882     // longjmp() and throw() must not violate the entry/exit criteria.
13883     CS->getCapturedDecl()->setNothrow();
13884   }
13885 
13886   OMPLoopBasedDirective::HelperExprs B;
13887   // In presence of clause 'collapse' with number of loops, it will
13888   // define the nested loops number.
13889   unsigned NestedLoopCount =
13890       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
13891                       getCollapseNumberExpr(Clauses),
13892                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13893                       *DSAStack, VarsWithImplicitDSA, B);
13894   if (NestedLoopCount == 0)
13895     return StmtError();
13896 
13897   assert((CurContext->isDependentContext() || B.builtAll()) &&
13898          "omp target teams distribute parallel for simd loop exprs were not "
13899          "built");
13900 
13901   if (!CurContext->isDependentContext()) {
13902     // Finalize the clauses that need pre-built expressions for CodeGen.
13903     for (OMPClause *C : Clauses) {
13904       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13905         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13906                                      B.NumIterations, *this, CurScope,
13907                                      DSAStack))
13908           return StmtError();
13909     }
13910   }
13911 
13912   if (checkSimdlenSafelenSpecified(*this, Clauses))
13913     return StmtError();
13914 
13915   setFunctionHasBranchProtectedScope();
13916   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
13917       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13918 }
13919 
13920 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
13921     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13922     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13923   if (!AStmt)
13924     return StmtError();
13925 
13926   auto *CS = cast<CapturedStmt>(AStmt);
13927   // 1.2.2 OpenMP Language Terminology
13928   // Structured block - An executable statement with a single entry at the
13929   // top and a single exit at the bottom.
13930   // The point of exit cannot be a branch out of the structured block.
13931   // longjmp() and throw() must not violate the entry/exit criteria.
13932   CS->getCapturedDecl()->setNothrow();
13933   for (int ThisCaptureLevel =
13934            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
13935        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13936     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13937     // 1.2.2 OpenMP Language Terminology
13938     // Structured block - An executable statement with a single entry at the
13939     // top and a single exit at the bottom.
13940     // The point of exit cannot be a branch out of the structured block.
13941     // longjmp() and throw() must not violate the entry/exit criteria.
13942     CS->getCapturedDecl()->setNothrow();
13943   }
13944 
13945   OMPLoopBasedDirective::HelperExprs B;
13946   // In presence of clause 'collapse' with number of loops, it will
13947   // define the nested loops number.
13948   unsigned NestedLoopCount = checkOpenMPLoop(
13949       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
13950       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13951       VarsWithImplicitDSA, B);
13952   if (NestedLoopCount == 0)
13953     return StmtError();
13954 
13955   assert((CurContext->isDependentContext() || B.builtAll()) &&
13956          "omp target teams distribute simd loop exprs were not built");
13957 
13958   if (!CurContext->isDependentContext()) {
13959     // Finalize the clauses that need pre-built expressions for CodeGen.
13960     for (OMPClause *C : Clauses) {
13961       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13962         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13963                                      B.NumIterations, *this, CurScope,
13964                                      DSAStack))
13965           return StmtError();
13966     }
13967   }
13968 
13969   if (checkSimdlenSafelenSpecified(*this, Clauses))
13970     return StmtError();
13971 
13972   setFunctionHasBranchProtectedScope();
13973   return OMPTargetTeamsDistributeSimdDirective::Create(
13974       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13975 }
13976 
13977 bool Sema::checkTransformableLoopNest(
13978     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
13979     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
13980     Stmt *&Body,
13981     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
13982         &OriginalInits) {
13983   OriginalInits.emplace_back();
13984   bool Result = OMPLoopBasedDirective::doForAllLoops(
13985       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
13986       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
13987                                                         Stmt *CurStmt) {
13988         VarsWithInheritedDSAType TmpDSA;
13989         unsigned SingleNumLoops =
13990             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
13991                             TmpDSA, LoopHelpers[Cnt]);
13992         if (SingleNumLoops == 0)
13993           return true;
13994         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
13995         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
13996           OriginalInits.back().push_back(For->getInit());
13997           Body = For->getBody();
13998         } else {
13999           assert(isa<CXXForRangeStmt>(CurStmt) &&
14000                  "Expected canonical for or range-based for loops.");
14001           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
14002           OriginalInits.back().push_back(CXXFor->getBeginStmt());
14003           Body = CXXFor->getBody();
14004         }
14005         OriginalInits.emplace_back();
14006         return false;
14007       },
14008       [&OriginalInits](OMPLoopBasedDirective *Transform) {
14009         Stmt *DependentPreInits;
14010         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
14011           DependentPreInits = Dir->getPreInits();
14012         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
14013           DependentPreInits = Dir->getPreInits();
14014         else
14015           llvm_unreachable("Unhandled loop transformation");
14016         if (!DependentPreInits)
14017           return;
14018         llvm::append_range(OriginalInits.back(),
14019                            cast<DeclStmt>(DependentPreInits)->getDeclGroup());
14020       });
14021   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
14022   OriginalInits.pop_back();
14023   return Result;
14024 }
14025 
14026 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
14027                                           Stmt *AStmt, SourceLocation StartLoc,
14028                                           SourceLocation EndLoc) {
14029   auto SizesClauses =
14030       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
14031   if (SizesClauses.empty()) {
14032     // A missing 'sizes' clause is already reported by the parser.
14033     return StmtError();
14034   }
14035   const OMPSizesClause *SizesClause = *SizesClauses.begin();
14036   unsigned NumLoops = SizesClause->getNumSizes();
14037 
14038   // Empty statement should only be possible if there already was an error.
14039   if (!AStmt)
14040     return StmtError();
14041 
14042   // Verify and diagnose loop nest.
14043   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
14044   Stmt *Body = nullptr;
14045   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
14046       OriginalInits;
14047   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
14048                                   OriginalInits))
14049     return StmtError();
14050 
14051   // Delay tiling to when template is completely instantiated.
14052   if (CurContext->isDependentContext())
14053     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
14054                                     NumLoops, AStmt, nullptr, nullptr);
14055 
14056   SmallVector<Decl *, 4> PreInits;
14057 
14058   // Create iteration variables for the generated loops.
14059   SmallVector<VarDecl *, 4> FloorIndVars;
14060   SmallVector<VarDecl *, 4> TileIndVars;
14061   FloorIndVars.resize(NumLoops);
14062   TileIndVars.resize(NumLoops);
14063   for (unsigned I = 0; I < NumLoops; ++I) {
14064     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
14065 
14066     assert(LoopHelper.Counters.size() == 1 &&
14067            "Expect single-dimensional loop iteration space");
14068     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
14069     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
14070     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
14071     QualType CntTy = IterVarRef->getType();
14072 
14073     // Iteration variable for the floor (i.e. outer) loop.
14074     {
14075       std::string FloorCntName =
14076           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
14077       VarDecl *FloorCntDecl =
14078           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
14079       FloorIndVars[I] = FloorCntDecl;
14080     }
14081 
14082     // Iteration variable for the tile (i.e. inner) loop.
14083     {
14084       std::string TileCntName =
14085           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
14086 
14087       // Reuse the iteration variable created by checkOpenMPLoop. It is also
14088       // used by the expressions to derive the original iteration variable's
14089       // value from the logical iteration number.
14090       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
14091       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
14092       TileIndVars[I] = TileCntDecl;
14093     }
14094     for (auto &P : OriginalInits[I]) {
14095       if (auto *D = P.dyn_cast<Decl *>())
14096         PreInits.push_back(D);
14097       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
14098         PreInits.append(PI->decl_begin(), PI->decl_end());
14099     }
14100     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
14101       PreInits.append(PI->decl_begin(), PI->decl_end());
14102     // Gather declarations for the data members used as counters.
14103     for (Expr *CounterRef : LoopHelper.Counters) {
14104       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
14105       if (isa<OMPCapturedExprDecl>(CounterDecl))
14106         PreInits.push_back(CounterDecl);
14107     }
14108   }
14109 
14110   // Once the original iteration values are set, append the innermost body.
14111   Stmt *Inner = Body;
14112 
14113   // Create tile loops from the inside to the outside.
14114   for (int I = NumLoops - 1; I >= 0; --I) {
14115     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
14116     Expr *NumIterations = LoopHelper.NumIterations;
14117     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
14118     QualType CntTy = OrigCntVar->getType();
14119     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
14120     Scope *CurScope = getCurScope();
14121 
14122     // Commonly used variables.
14123     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
14124                                            OrigCntVar->getExprLoc());
14125     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
14126                                             OrigCntVar->getExprLoc());
14127 
14128     // For init-statement: auto .tile.iv = .floor.iv
14129     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
14130                          /*DirectInit=*/false);
14131     Decl *CounterDecl = TileIndVars[I];
14132     StmtResult InitStmt = new (Context)
14133         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
14134                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
14135     if (!InitStmt.isUsable())
14136       return StmtError();
14137 
14138     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
14139     // NumIterations)
14140     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14141                                       BO_Add, FloorIV, DimTileSize);
14142     if (!EndOfTile.isUsable())
14143       return StmtError();
14144     ExprResult IsPartialTile =
14145         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
14146                    NumIterations, EndOfTile.get());
14147     if (!IsPartialTile.isUsable())
14148       return StmtError();
14149     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
14150         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
14151         IsPartialTile.get(), NumIterations, EndOfTile.get());
14152     if (!MinTileAndIterSpace.isUsable())
14153       return StmtError();
14154     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14155                                      BO_LT, TileIV, MinTileAndIterSpace.get());
14156     if (!CondExpr.isUsable())
14157       return StmtError();
14158 
14159     // For incr-statement: ++.tile.iv
14160     ExprResult IncrStmt =
14161         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
14162     if (!IncrStmt.isUsable())
14163       return StmtError();
14164 
14165     // Statements to set the original iteration variable's value from the
14166     // logical iteration number.
14167     // Generated for loop is:
14168     // Original_for_init;
14169     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
14170     // NumIterations); ++.tile.iv) {
14171     //   Original_Body;
14172     //   Original_counter_update;
14173     // }
14174     // FIXME: If the innermost body is an loop itself, inserting these
14175     // statements stops it being recognized  as a perfectly nested loop (e.g.
14176     // for applying tiling again). If this is the case, sink the expressions
14177     // further into the inner loop.
14178     SmallVector<Stmt *, 4> BodyParts;
14179     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
14180     BodyParts.push_back(Inner);
14181     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
14182                                  Inner->getEndLoc());
14183     Inner = new (Context)
14184         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
14185                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
14186                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14187   }
14188 
14189   // Create floor loops from the inside to the outside.
14190   for (int I = NumLoops - 1; I >= 0; --I) {
14191     auto &LoopHelper = LoopHelpers[I];
14192     Expr *NumIterations = LoopHelper.NumIterations;
14193     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
14194     QualType CntTy = OrigCntVar->getType();
14195     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
14196     Scope *CurScope = getCurScope();
14197 
14198     // Commonly used variables.
14199     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
14200                                             OrigCntVar->getExprLoc());
14201 
14202     // For init-statement: auto .floor.iv = 0
14203     AddInitializerToDecl(
14204         FloorIndVars[I],
14205         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
14206         /*DirectInit=*/false);
14207     Decl *CounterDecl = FloorIndVars[I];
14208     StmtResult InitStmt = new (Context)
14209         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
14210                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
14211     if (!InitStmt.isUsable())
14212       return StmtError();
14213 
14214     // For cond-expression: .floor.iv < NumIterations
14215     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14216                                      BO_LT, FloorIV, NumIterations);
14217     if (!CondExpr.isUsable())
14218       return StmtError();
14219 
14220     // For incr-statement: .floor.iv += DimTileSize
14221     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
14222                                      BO_AddAssign, FloorIV, DimTileSize);
14223     if (!IncrStmt.isUsable())
14224       return StmtError();
14225 
14226     Inner = new (Context)
14227         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
14228                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
14229                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14230   }
14231 
14232   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
14233                                   AStmt, Inner,
14234                                   buildPreInits(Context, PreInits));
14235 }
14236 
14237 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
14238                                             Stmt *AStmt,
14239                                             SourceLocation StartLoc,
14240                                             SourceLocation EndLoc) {
14241   // Empty statement should only be possible if there already was an error.
14242   if (!AStmt)
14243     return StmtError();
14244 
14245   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
14246     return StmtError();
14247 
14248   const OMPFullClause *FullClause =
14249       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
14250   const OMPPartialClause *PartialClause =
14251       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
14252   assert(!(FullClause && PartialClause) &&
14253          "mutual exclusivity must have been checked before");
14254 
14255   constexpr unsigned NumLoops = 1;
14256   Stmt *Body = nullptr;
14257   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
14258       NumLoops);
14259   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
14260       OriginalInits;
14261   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
14262                                   Body, OriginalInits))
14263     return StmtError();
14264 
14265   unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
14266 
14267   // Delay unrolling to when template is completely instantiated.
14268   if (CurContext->isDependentContext())
14269     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
14270                                       NumGeneratedLoops, nullptr, nullptr);
14271 
14272   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
14273 
14274   if (FullClause) {
14275     if (!VerifyPositiveIntegerConstantInClause(
14276              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
14277              /*SuppressExprDiags=*/true)
14278              .isUsable()) {
14279       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
14280       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
14281           << "#pragma omp unroll full";
14282       return StmtError();
14283     }
14284   }
14285 
14286   // The generated loop may only be passed to other loop-associated directive
14287   // when a partial clause is specified. Without the requirement it is
14288   // sufficient to generate loop unroll metadata at code-generation.
14289   if (NumGeneratedLoops == 0)
14290     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
14291                                       NumGeneratedLoops, nullptr, nullptr);
14292 
14293   // Otherwise, we need to provide a de-sugared/transformed AST that can be
14294   // associated with another loop directive.
14295   //
14296   // The canonical loop analysis return by checkTransformableLoopNest assumes
14297   // the following structure to be the same loop without transformations or
14298   // directives applied: \code OriginalInits; LoopHelper.PreInits;
14299   // LoopHelper.Counters;
14300   // for (; IV < LoopHelper.NumIterations; ++IV) {
14301   //   LoopHelper.Updates;
14302   //   Body;
14303   // }
14304   // \endcode
14305   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
14306   // and referenced by LoopHelper.IterationVarRef.
14307   //
14308   // The unrolling directive transforms this into the following loop:
14309   // \code
14310   // OriginalInits;         \
14311   // LoopHelper.PreInits;    > NewPreInits
14312   // LoopHelper.Counters;   /
14313   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
14314   //   #pragma clang loop unroll_count(Factor)
14315   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
14316   //   {
14317   //     LoopHelper.Updates;
14318   //     Body;
14319   //   }
14320   // }
14321   // \endcode
14322   // where UIV is a new logical iteration counter. IV must be the same VarDecl
14323   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
14324   // references it. If the partially unrolled loop is associated with another
14325   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
14326   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
14327   // OpenMP canonical loop. The inner loop is not an associable canonical loop
14328   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
14329   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
14330   // property of the OMPLoopBasedDirective instead of statements in
14331   // CompoundStatement. This is to allow the loop to become a non-outermost loop
14332   // of a canonical loop nest where these PreInits are emitted before the
14333   // outermost directive.
14334 
14335   // Determine the PreInit declarations.
14336   SmallVector<Decl *, 4> PreInits;
14337   assert(OriginalInits.size() == 1 &&
14338          "Expecting a single-dimensional loop iteration space");
14339   for (auto &P : OriginalInits[0]) {
14340     if (auto *D = P.dyn_cast<Decl *>())
14341       PreInits.push_back(D);
14342     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
14343       PreInits.append(PI->decl_begin(), PI->decl_end());
14344   }
14345   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
14346     PreInits.append(PI->decl_begin(), PI->decl_end());
14347   // Gather declarations for the data members used as counters.
14348   for (Expr *CounterRef : LoopHelper.Counters) {
14349     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
14350     if (isa<OMPCapturedExprDecl>(CounterDecl))
14351       PreInits.push_back(CounterDecl);
14352   }
14353 
14354   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
14355   QualType IVTy = IterationVarRef->getType();
14356   assert(LoopHelper.Counters.size() == 1 &&
14357          "Expecting a single-dimensional loop iteration space");
14358   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
14359 
14360   // Determine the unroll factor.
14361   uint64_t Factor;
14362   SourceLocation FactorLoc;
14363   if (Expr *FactorVal = PartialClause->getFactor()) {
14364     Factor =
14365         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
14366     FactorLoc = FactorVal->getExprLoc();
14367   } else {
14368     // TODO: Use a better profitability model.
14369     Factor = 2;
14370   }
14371   assert(Factor > 0 && "Expected positive unroll factor");
14372   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
14373     return IntegerLiteral::Create(
14374         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
14375         FactorLoc);
14376   };
14377 
14378   // Iteration variable SourceLocations.
14379   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
14380   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
14381   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
14382 
14383   // Internal variable names.
14384   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
14385   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
14386   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
14387   std::string InnerTripCountName =
14388       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
14389 
14390   // Create the iteration variable for the unrolled loop.
14391   VarDecl *OuterIVDecl =
14392       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
14393   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
14394     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
14395   };
14396 
14397   // Iteration variable for the inner loop: Reuse the iteration variable created
14398   // by checkOpenMPLoop.
14399   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
14400   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
14401   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
14402     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
14403   };
14404 
14405   // Make a copy of the NumIterations expression for each use: By the AST
14406   // constraints, every expression object in a DeclContext must be unique.
14407   CaptureVars CopyTransformer(*this);
14408   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
14409     return AssertSuccess(
14410         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
14411   };
14412 
14413   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
14414   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
14415   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
14416   StmtResult InnerInit = new (Context)
14417       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
14418   if (!InnerInit.isUsable())
14419     return StmtError();
14420 
14421   // Inner For cond-expression:
14422   // \code
14423   //   .unroll_inner.iv < .unrolled.iv + Factor &&
14424   //   .unroll_inner.iv < NumIterations
14425   // \endcode
14426   // This conjunction of two conditions allows ScalarEvolution to derive the
14427   // maximum trip count of the inner loop.
14428   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14429                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
14430   if (!EndOfTile.isUsable())
14431     return StmtError();
14432   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14433                                      BO_LE, MakeInnerRef(), EndOfTile.get());
14434   if (!InnerCond1.isUsable())
14435     return StmtError();
14436   ExprResult InnerCond2 =
14437       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
14438                  MakeNumIterations());
14439   if (!InnerCond2.isUsable())
14440     return StmtError();
14441   ExprResult InnerCond =
14442       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
14443                  InnerCond1.get(), InnerCond2.get());
14444   if (!InnerCond.isUsable())
14445     return StmtError();
14446 
14447   // Inner For incr-statement: ++.unroll_inner.iv
14448   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
14449                                       UO_PreInc, MakeInnerRef());
14450   if (!InnerIncr.isUsable())
14451     return StmtError();
14452 
14453   // Inner For statement.
14454   SmallVector<Stmt *> InnerBodyStmts;
14455   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
14456   InnerBodyStmts.push_back(Body);
14457   CompoundStmt *InnerBody = CompoundStmt::Create(
14458       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
14459   ForStmt *InnerFor = new (Context)
14460       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
14461               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
14462               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14463 
14464   // Unroll metadata for the inner loop.
14465   // This needs to take into account the remainder portion of the unrolled loop,
14466   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
14467   // supports multiple loop exits. Instead, unroll using a factor equivalent to
14468   // the maximum trip count, which will also generate a remainder loop. Just
14469   // `unroll(enable)` (which could have been useful if the user has not
14470   // specified a concrete factor; even though the outer loop cannot be
14471   // influenced anymore, would avoid more code bloat than necessary) will refuse
14472   // the loop because "Won't unroll; remainder loop could not be generated when
14473   // assuming runtime trip count". Even if it did work, it must not choose a
14474   // larger unroll factor than the maximum loop length, or it would always just
14475   // execute the remainder loop.
14476   LoopHintAttr *UnrollHintAttr =
14477       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
14478                                    LoopHintAttr::Numeric, MakeFactorExpr());
14479   AttributedStmt *InnerUnrolled =
14480       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
14481 
14482   // Outer For init-statement: auto .unrolled.iv = 0
14483   AddInitializerToDecl(
14484       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
14485       /*DirectInit=*/false);
14486   StmtResult OuterInit = new (Context)
14487       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
14488   if (!OuterInit.isUsable())
14489     return StmtError();
14490 
14491   // Outer For cond-expression: .unrolled.iv < NumIterations
14492   ExprResult OuterConde =
14493       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
14494                  MakeNumIterations());
14495   if (!OuterConde.isUsable())
14496     return StmtError();
14497 
14498   // Outer For incr-statement: .unrolled.iv += Factor
14499   ExprResult OuterIncr =
14500       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
14501                  MakeOuterRef(), MakeFactorExpr());
14502   if (!OuterIncr.isUsable())
14503     return StmtError();
14504 
14505   // Outer For statement.
14506   ForStmt *OuterFor = new (Context)
14507       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
14508               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
14509               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14510 
14511   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
14512                                     NumGeneratedLoops, OuterFor,
14513                                     buildPreInits(Context, PreInits));
14514 }
14515 
14516 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
14517                                              SourceLocation StartLoc,
14518                                              SourceLocation LParenLoc,
14519                                              SourceLocation EndLoc) {
14520   OMPClause *Res = nullptr;
14521   switch (Kind) {
14522   case OMPC_final:
14523     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
14524     break;
14525   case OMPC_num_threads:
14526     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
14527     break;
14528   case OMPC_safelen:
14529     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
14530     break;
14531   case OMPC_simdlen:
14532     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
14533     break;
14534   case OMPC_allocator:
14535     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
14536     break;
14537   case OMPC_collapse:
14538     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
14539     break;
14540   case OMPC_ordered:
14541     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
14542     break;
14543   case OMPC_num_teams:
14544     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
14545     break;
14546   case OMPC_thread_limit:
14547     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
14548     break;
14549   case OMPC_priority:
14550     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
14551     break;
14552   case OMPC_grainsize:
14553     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
14554     break;
14555   case OMPC_num_tasks:
14556     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
14557     break;
14558   case OMPC_hint:
14559     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
14560     break;
14561   case OMPC_depobj:
14562     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
14563     break;
14564   case OMPC_detach:
14565     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
14566     break;
14567   case OMPC_novariants:
14568     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
14569     break;
14570   case OMPC_nocontext:
14571     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
14572     break;
14573   case OMPC_filter:
14574     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
14575     break;
14576   case OMPC_partial:
14577     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
14578     break;
14579   case OMPC_align:
14580     Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
14581     break;
14582   case OMPC_device:
14583   case OMPC_if:
14584   case OMPC_default:
14585   case OMPC_proc_bind:
14586   case OMPC_schedule:
14587   case OMPC_private:
14588   case OMPC_firstprivate:
14589   case OMPC_lastprivate:
14590   case OMPC_shared:
14591   case OMPC_reduction:
14592   case OMPC_task_reduction:
14593   case OMPC_in_reduction:
14594   case OMPC_linear:
14595   case OMPC_aligned:
14596   case OMPC_copyin:
14597   case OMPC_copyprivate:
14598   case OMPC_nowait:
14599   case OMPC_untied:
14600   case OMPC_mergeable:
14601   case OMPC_threadprivate:
14602   case OMPC_sizes:
14603   case OMPC_allocate:
14604   case OMPC_flush:
14605   case OMPC_read:
14606   case OMPC_write:
14607   case OMPC_update:
14608   case OMPC_capture:
14609   case OMPC_compare:
14610   case OMPC_seq_cst:
14611   case OMPC_acq_rel:
14612   case OMPC_acquire:
14613   case OMPC_release:
14614   case OMPC_relaxed:
14615   case OMPC_depend:
14616   case OMPC_threads:
14617   case OMPC_simd:
14618   case OMPC_map:
14619   case OMPC_nogroup:
14620   case OMPC_dist_schedule:
14621   case OMPC_defaultmap:
14622   case OMPC_unknown:
14623   case OMPC_uniform:
14624   case OMPC_to:
14625   case OMPC_from:
14626   case OMPC_use_device_ptr:
14627   case OMPC_use_device_addr:
14628   case OMPC_is_device_ptr:
14629   case OMPC_unified_address:
14630   case OMPC_unified_shared_memory:
14631   case OMPC_reverse_offload:
14632   case OMPC_dynamic_allocators:
14633   case OMPC_atomic_default_mem_order:
14634   case OMPC_device_type:
14635   case OMPC_match:
14636   case OMPC_nontemporal:
14637   case OMPC_order:
14638   case OMPC_destroy:
14639   case OMPC_inclusive:
14640   case OMPC_exclusive:
14641   case OMPC_uses_allocators:
14642   case OMPC_affinity:
14643   case OMPC_when:
14644   case OMPC_bind:
14645   default:
14646     llvm_unreachable("Clause is not allowed.");
14647   }
14648   return Res;
14649 }
14650 
14651 // An OpenMP directive such as 'target parallel' has two captured regions:
14652 // for the 'target' and 'parallel' respectively.  This function returns
14653 // the region in which to capture expressions associated with a clause.
14654 // A return value of OMPD_unknown signifies that the expression should not
14655 // be captured.
14656 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
14657     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
14658     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
14659   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14660   switch (CKind) {
14661   case OMPC_if:
14662     switch (DKind) {
14663     case OMPD_target_parallel_for_simd:
14664       if (OpenMPVersion >= 50 &&
14665           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
14666         CaptureRegion = OMPD_parallel;
14667         break;
14668       }
14669       LLVM_FALLTHROUGH;
14670     case OMPD_target_parallel:
14671     case OMPD_target_parallel_for:
14672     case OMPD_target_parallel_loop:
14673       // If this clause applies to the nested 'parallel' region, capture within
14674       // the 'target' region, otherwise do not capture.
14675       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
14676         CaptureRegion = OMPD_target;
14677       break;
14678     case OMPD_target_teams_distribute_parallel_for_simd:
14679       if (OpenMPVersion >= 50 &&
14680           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
14681         CaptureRegion = OMPD_parallel;
14682         break;
14683       }
14684       LLVM_FALLTHROUGH;
14685     case OMPD_target_teams_distribute_parallel_for:
14686       // If this clause applies to the nested 'parallel' region, capture within
14687       // the 'teams' region, otherwise do not capture.
14688       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
14689         CaptureRegion = OMPD_teams;
14690       break;
14691     case OMPD_teams_distribute_parallel_for_simd:
14692       if (OpenMPVersion >= 50 &&
14693           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
14694         CaptureRegion = OMPD_parallel;
14695         break;
14696       }
14697       LLVM_FALLTHROUGH;
14698     case OMPD_teams_distribute_parallel_for:
14699       CaptureRegion = OMPD_teams;
14700       break;
14701     case OMPD_target_update:
14702     case OMPD_target_enter_data:
14703     case OMPD_target_exit_data:
14704       CaptureRegion = OMPD_task;
14705       break;
14706     case OMPD_parallel_master_taskloop:
14707       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
14708         CaptureRegion = OMPD_parallel;
14709       break;
14710     case OMPD_parallel_master_taskloop_simd:
14711       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
14712           NameModifier == OMPD_taskloop) {
14713         CaptureRegion = OMPD_parallel;
14714         break;
14715       }
14716       if (OpenMPVersion <= 45)
14717         break;
14718       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14719         CaptureRegion = OMPD_taskloop;
14720       break;
14721     case OMPD_parallel_for_simd:
14722       if (OpenMPVersion <= 45)
14723         break;
14724       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14725         CaptureRegion = OMPD_parallel;
14726       break;
14727     case OMPD_taskloop_simd:
14728     case OMPD_master_taskloop_simd:
14729       if (OpenMPVersion <= 45)
14730         break;
14731       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14732         CaptureRegion = OMPD_taskloop;
14733       break;
14734     case OMPD_distribute_parallel_for_simd:
14735       if (OpenMPVersion <= 45)
14736         break;
14737       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14738         CaptureRegion = OMPD_parallel;
14739       break;
14740     case OMPD_target_simd:
14741       if (OpenMPVersion >= 50 &&
14742           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
14743         CaptureRegion = OMPD_target;
14744       break;
14745     case OMPD_teams_distribute_simd:
14746     case OMPD_target_teams_distribute_simd:
14747       if (OpenMPVersion >= 50 &&
14748           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
14749         CaptureRegion = OMPD_teams;
14750       break;
14751     case OMPD_cancel:
14752     case OMPD_parallel:
14753     case OMPD_parallel_master:
14754     case OMPD_parallel_sections:
14755     case OMPD_parallel_for:
14756     case OMPD_parallel_loop:
14757     case OMPD_target:
14758     case OMPD_target_teams:
14759     case OMPD_target_teams_distribute:
14760     case OMPD_target_teams_loop:
14761     case OMPD_distribute_parallel_for:
14762     case OMPD_task:
14763     case OMPD_taskloop:
14764     case OMPD_master_taskloop:
14765     case OMPD_target_data:
14766     case OMPD_simd:
14767     case OMPD_for_simd:
14768     case OMPD_distribute_simd:
14769       // Do not capture if-clause expressions.
14770       break;
14771     case OMPD_threadprivate:
14772     case OMPD_allocate:
14773     case OMPD_taskyield:
14774     case OMPD_barrier:
14775     case OMPD_taskwait:
14776     case OMPD_cancellation_point:
14777     case OMPD_flush:
14778     case OMPD_depobj:
14779     case OMPD_scan:
14780     case OMPD_declare_reduction:
14781     case OMPD_declare_mapper:
14782     case OMPD_declare_simd:
14783     case OMPD_declare_variant:
14784     case OMPD_begin_declare_variant:
14785     case OMPD_end_declare_variant:
14786     case OMPD_declare_target:
14787     case OMPD_end_declare_target:
14788     case OMPD_loop:
14789     case OMPD_teams_loop:
14790     case OMPD_teams:
14791     case OMPD_tile:
14792     case OMPD_unroll:
14793     case OMPD_for:
14794     case OMPD_sections:
14795     case OMPD_section:
14796     case OMPD_single:
14797     case OMPD_master:
14798     case OMPD_masked:
14799     case OMPD_critical:
14800     case OMPD_taskgroup:
14801     case OMPD_distribute:
14802     case OMPD_ordered:
14803     case OMPD_atomic:
14804     case OMPD_teams_distribute:
14805     case OMPD_requires:
14806     case OMPD_metadirective:
14807       llvm_unreachable("Unexpected OpenMP directive with if-clause");
14808     case OMPD_unknown:
14809     default:
14810       llvm_unreachable("Unknown OpenMP directive");
14811     }
14812     break;
14813   case OMPC_num_threads:
14814     switch (DKind) {
14815     case OMPD_target_parallel:
14816     case OMPD_target_parallel_for:
14817     case OMPD_target_parallel_for_simd:
14818     case OMPD_target_parallel_loop:
14819       CaptureRegion = OMPD_target;
14820       break;
14821     case OMPD_teams_distribute_parallel_for:
14822     case OMPD_teams_distribute_parallel_for_simd:
14823     case OMPD_target_teams_distribute_parallel_for:
14824     case OMPD_target_teams_distribute_parallel_for_simd:
14825       CaptureRegion = OMPD_teams;
14826       break;
14827     case OMPD_parallel:
14828     case OMPD_parallel_master:
14829     case OMPD_parallel_sections:
14830     case OMPD_parallel_for:
14831     case OMPD_parallel_for_simd:
14832     case OMPD_parallel_loop:
14833     case OMPD_distribute_parallel_for:
14834     case OMPD_distribute_parallel_for_simd:
14835     case OMPD_parallel_master_taskloop:
14836     case OMPD_parallel_master_taskloop_simd:
14837       // Do not capture num_threads-clause expressions.
14838       break;
14839     case OMPD_target_data:
14840     case OMPD_target_enter_data:
14841     case OMPD_target_exit_data:
14842     case OMPD_target_update:
14843     case OMPD_target:
14844     case OMPD_target_simd:
14845     case OMPD_target_teams:
14846     case OMPD_target_teams_distribute:
14847     case OMPD_target_teams_distribute_simd:
14848     case OMPD_cancel:
14849     case OMPD_task:
14850     case OMPD_taskloop:
14851     case OMPD_taskloop_simd:
14852     case OMPD_master_taskloop:
14853     case OMPD_master_taskloop_simd:
14854     case OMPD_threadprivate:
14855     case OMPD_allocate:
14856     case OMPD_taskyield:
14857     case OMPD_barrier:
14858     case OMPD_taskwait:
14859     case OMPD_cancellation_point:
14860     case OMPD_flush:
14861     case OMPD_depobj:
14862     case OMPD_scan:
14863     case OMPD_declare_reduction:
14864     case OMPD_declare_mapper:
14865     case OMPD_declare_simd:
14866     case OMPD_declare_variant:
14867     case OMPD_begin_declare_variant:
14868     case OMPD_end_declare_variant:
14869     case OMPD_declare_target:
14870     case OMPD_end_declare_target:
14871     case OMPD_loop:
14872     case OMPD_teams_loop:
14873     case OMPD_target_teams_loop:
14874     case OMPD_teams:
14875     case OMPD_simd:
14876     case OMPD_tile:
14877     case OMPD_unroll:
14878     case OMPD_for:
14879     case OMPD_for_simd:
14880     case OMPD_sections:
14881     case OMPD_section:
14882     case OMPD_single:
14883     case OMPD_master:
14884     case OMPD_masked:
14885     case OMPD_critical:
14886     case OMPD_taskgroup:
14887     case OMPD_distribute:
14888     case OMPD_ordered:
14889     case OMPD_atomic:
14890     case OMPD_distribute_simd:
14891     case OMPD_teams_distribute:
14892     case OMPD_teams_distribute_simd:
14893     case OMPD_requires:
14894     case OMPD_metadirective:
14895       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
14896     case OMPD_unknown:
14897     default:
14898       llvm_unreachable("Unknown OpenMP directive");
14899     }
14900     break;
14901   case OMPC_num_teams:
14902     switch (DKind) {
14903     case OMPD_target_teams:
14904     case OMPD_target_teams_distribute:
14905     case OMPD_target_teams_distribute_simd:
14906     case OMPD_target_teams_distribute_parallel_for:
14907     case OMPD_target_teams_distribute_parallel_for_simd:
14908     case OMPD_target_teams_loop:
14909       CaptureRegion = OMPD_target;
14910       break;
14911     case OMPD_teams_distribute_parallel_for:
14912     case OMPD_teams_distribute_parallel_for_simd:
14913     case OMPD_teams:
14914     case OMPD_teams_distribute:
14915     case OMPD_teams_distribute_simd:
14916     case OMPD_teams_loop:
14917       // Do not capture num_teams-clause expressions.
14918       break;
14919     case OMPD_distribute_parallel_for:
14920     case OMPD_distribute_parallel_for_simd:
14921     case OMPD_task:
14922     case OMPD_taskloop:
14923     case OMPD_taskloop_simd:
14924     case OMPD_master_taskloop:
14925     case OMPD_master_taskloop_simd:
14926     case OMPD_parallel_master_taskloop:
14927     case OMPD_parallel_master_taskloop_simd:
14928     case OMPD_target_data:
14929     case OMPD_target_enter_data:
14930     case OMPD_target_exit_data:
14931     case OMPD_target_update:
14932     case OMPD_cancel:
14933     case OMPD_parallel:
14934     case OMPD_parallel_master:
14935     case OMPD_parallel_sections:
14936     case OMPD_parallel_for:
14937     case OMPD_parallel_for_simd:
14938     case OMPD_parallel_loop:
14939     case OMPD_target:
14940     case OMPD_target_simd:
14941     case OMPD_target_parallel:
14942     case OMPD_target_parallel_for:
14943     case OMPD_target_parallel_for_simd:
14944     case OMPD_target_parallel_loop:
14945     case OMPD_threadprivate:
14946     case OMPD_allocate:
14947     case OMPD_taskyield:
14948     case OMPD_barrier:
14949     case OMPD_taskwait:
14950     case OMPD_cancellation_point:
14951     case OMPD_flush:
14952     case OMPD_depobj:
14953     case OMPD_scan:
14954     case OMPD_declare_reduction:
14955     case OMPD_declare_mapper:
14956     case OMPD_declare_simd:
14957     case OMPD_declare_variant:
14958     case OMPD_begin_declare_variant:
14959     case OMPD_end_declare_variant:
14960     case OMPD_declare_target:
14961     case OMPD_end_declare_target:
14962     case OMPD_loop:
14963     case OMPD_simd:
14964     case OMPD_tile:
14965     case OMPD_unroll:
14966     case OMPD_for:
14967     case OMPD_for_simd:
14968     case OMPD_sections:
14969     case OMPD_section:
14970     case OMPD_single:
14971     case OMPD_master:
14972     case OMPD_masked:
14973     case OMPD_critical:
14974     case OMPD_taskgroup:
14975     case OMPD_distribute:
14976     case OMPD_ordered:
14977     case OMPD_atomic:
14978     case OMPD_distribute_simd:
14979     case OMPD_requires:
14980     case OMPD_metadirective:
14981       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
14982     case OMPD_unknown:
14983     default:
14984       llvm_unreachable("Unknown OpenMP directive");
14985     }
14986     break;
14987   case OMPC_thread_limit:
14988     switch (DKind) {
14989     case OMPD_target_teams:
14990     case OMPD_target_teams_distribute:
14991     case OMPD_target_teams_distribute_simd:
14992     case OMPD_target_teams_distribute_parallel_for:
14993     case OMPD_target_teams_distribute_parallel_for_simd:
14994     case OMPD_target_teams_loop:
14995       CaptureRegion = OMPD_target;
14996       break;
14997     case OMPD_teams_distribute_parallel_for:
14998     case OMPD_teams_distribute_parallel_for_simd:
14999     case OMPD_teams:
15000     case OMPD_teams_distribute:
15001     case OMPD_teams_distribute_simd:
15002     case OMPD_teams_loop:
15003       // Do not capture thread_limit-clause expressions.
15004       break;
15005     case OMPD_distribute_parallel_for:
15006     case OMPD_distribute_parallel_for_simd:
15007     case OMPD_task:
15008     case OMPD_taskloop:
15009     case OMPD_taskloop_simd:
15010     case OMPD_master_taskloop:
15011     case OMPD_master_taskloop_simd:
15012     case OMPD_parallel_master_taskloop:
15013     case OMPD_parallel_master_taskloop_simd:
15014     case OMPD_target_data:
15015     case OMPD_target_enter_data:
15016     case OMPD_target_exit_data:
15017     case OMPD_target_update:
15018     case OMPD_cancel:
15019     case OMPD_parallel:
15020     case OMPD_parallel_master:
15021     case OMPD_parallel_sections:
15022     case OMPD_parallel_for:
15023     case OMPD_parallel_for_simd:
15024     case OMPD_parallel_loop:
15025     case OMPD_target:
15026     case OMPD_target_simd:
15027     case OMPD_target_parallel:
15028     case OMPD_target_parallel_for:
15029     case OMPD_target_parallel_for_simd:
15030     case OMPD_target_parallel_loop:
15031     case OMPD_threadprivate:
15032     case OMPD_allocate:
15033     case OMPD_taskyield:
15034     case OMPD_barrier:
15035     case OMPD_taskwait:
15036     case OMPD_cancellation_point:
15037     case OMPD_flush:
15038     case OMPD_depobj:
15039     case OMPD_scan:
15040     case OMPD_declare_reduction:
15041     case OMPD_declare_mapper:
15042     case OMPD_declare_simd:
15043     case OMPD_declare_variant:
15044     case OMPD_begin_declare_variant:
15045     case OMPD_end_declare_variant:
15046     case OMPD_declare_target:
15047     case OMPD_end_declare_target:
15048     case OMPD_loop:
15049     case OMPD_simd:
15050     case OMPD_tile:
15051     case OMPD_unroll:
15052     case OMPD_for:
15053     case OMPD_for_simd:
15054     case OMPD_sections:
15055     case OMPD_section:
15056     case OMPD_single:
15057     case OMPD_master:
15058     case OMPD_masked:
15059     case OMPD_critical:
15060     case OMPD_taskgroup:
15061     case OMPD_distribute:
15062     case OMPD_ordered:
15063     case OMPD_atomic:
15064     case OMPD_distribute_simd:
15065     case OMPD_requires:
15066     case OMPD_metadirective:
15067       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
15068     case OMPD_unknown:
15069     default:
15070       llvm_unreachable("Unknown OpenMP directive");
15071     }
15072     break;
15073   case OMPC_schedule:
15074     switch (DKind) {
15075     case OMPD_parallel_for:
15076     case OMPD_parallel_for_simd:
15077     case OMPD_distribute_parallel_for:
15078     case OMPD_distribute_parallel_for_simd:
15079     case OMPD_teams_distribute_parallel_for:
15080     case OMPD_teams_distribute_parallel_for_simd:
15081     case OMPD_target_parallel_for:
15082     case OMPD_target_parallel_for_simd:
15083     case OMPD_target_teams_distribute_parallel_for:
15084     case OMPD_target_teams_distribute_parallel_for_simd:
15085       CaptureRegion = OMPD_parallel;
15086       break;
15087     case OMPD_for:
15088     case OMPD_for_simd:
15089       // Do not capture schedule-clause expressions.
15090       break;
15091     case OMPD_task:
15092     case OMPD_taskloop:
15093     case OMPD_taskloop_simd:
15094     case OMPD_master_taskloop:
15095     case OMPD_master_taskloop_simd:
15096     case OMPD_parallel_master_taskloop:
15097     case OMPD_parallel_master_taskloop_simd:
15098     case OMPD_target_data:
15099     case OMPD_target_enter_data:
15100     case OMPD_target_exit_data:
15101     case OMPD_target_update:
15102     case OMPD_teams:
15103     case OMPD_teams_distribute:
15104     case OMPD_teams_distribute_simd:
15105     case OMPD_target_teams_distribute:
15106     case OMPD_target_teams_distribute_simd:
15107     case OMPD_target:
15108     case OMPD_target_simd:
15109     case OMPD_target_parallel:
15110     case OMPD_cancel:
15111     case OMPD_parallel:
15112     case OMPD_parallel_master:
15113     case OMPD_parallel_sections:
15114     case OMPD_threadprivate:
15115     case OMPD_allocate:
15116     case OMPD_taskyield:
15117     case OMPD_barrier:
15118     case OMPD_taskwait:
15119     case OMPD_cancellation_point:
15120     case OMPD_flush:
15121     case OMPD_depobj:
15122     case OMPD_scan:
15123     case OMPD_declare_reduction:
15124     case OMPD_declare_mapper:
15125     case OMPD_declare_simd:
15126     case OMPD_declare_variant:
15127     case OMPD_begin_declare_variant:
15128     case OMPD_end_declare_variant:
15129     case OMPD_declare_target:
15130     case OMPD_end_declare_target:
15131     case OMPD_loop:
15132     case OMPD_teams_loop:
15133     case OMPD_target_teams_loop:
15134     case OMPD_parallel_loop:
15135     case OMPD_target_parallel_loop:
15136     case OMPD_simd:
15137     case OMPD_tile:
15138     case OMPD_unroll:
15139     case OMPD_sections:
15140     case OMPD_section:
15141     case OMPD_single:
15142     case OMPD_master:
15143     case OMPD_masked:
15144     case OMPD_critical:
15145     case OMPD_taskgroup:
15146     case OMPD_distribute:
15147     case OMPD_ordered:
15148     case OMPD_atomic:
15149     case OMPD_distribute_simd:
15150     case OMPD_target_teams:
15151     case OMPD_requires:
15152     case OMPD_metadirective:
15153       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
15154     case OMPD_unknown:
15155     default:
15156       llvm_unreachable("Unknown OpenMP directive");
15157     }
15158     break;
15159   case OMPC_dist_schedule:
15160     switch (DKind) {
15161     case OMPD_teams_distribute_parallel_for:
15162     case OMPD_teams_distribute_parallel_for_simd:
15163     case OMPD_teams_distribute:
15164     case OMPD_teams_distribute_simd:
15165     case OMPD_target_teams_distribute_parallel_for:
15166     case OMPD_target_teams_distribute_parallel_for_simd:
15167     case OMPD_target_teams_distribute:
15168     case OMPD_target_teams_distribute_simd:
15169       CaptureRegion = OMPD_teams;
15170       break;
15171     case OMPD_distribute_parallel_for:
15172     case OMPD_distribute_parallel_for_simd:
15173     case OMPD_distribute:
15174     case OMPD_distribute_simd:
15175       // Do not capture dist_schedule-clause expressions.
15176       break;
15177     case OMPD_parallel_for:
15178     case OMPD_parallel_for_simd:
15179     case OMPD_target_parallel_for_simd:
15180     case OMPD_target_parallel_for:
15181     case OMPD_task:
15182     case OMPD_taskloop:
15183     case OMPD_taskloop_simd:
15184     case OMPD_master_taskloop:
15185     case OMPD_master_taskloop_simd:
15186     case OMPD_parallel_master_taskloop:
15187     case OMPD_parallel_master_taskloop_simd:
15188     case OMPD_target_data:
15189     case OMPD_target_enter_data:
15190     case OMPD_target_exit_data:
15191     case OMPD_target_update:
15192     case OMPD_teams:
15193     case OMPD_target:
15194     case OMPD_target_simd:
15195     case OMPD_target_parallel:
15196     case OMPD_cancel:
15197     case OMPD_parallel:
15198     case OMPD_parallel_master:
15199     case OMPD_parallel_sections:
15200     case OMPD_threadprivate:
15201     case OMPD_allocate:
15202     case OMPD_taskyield:
15203     case OMPD_barrier:
15204     case OMPD_taskwait:
15205     case OMPD_cancellation_point:
15206     case OMPD_flush:
15207     case OMPD_depobj:
15208     case OMPD_scan:
15209     case OMPD_declare_reduction:
15210     case OMPD_declare_mapper:
15211     case OMPD_declare_simd:
15212     case OMPD_declare_variant:
15213     case OMPD_begin_declare_variant:
15214     case OMPD_end_declare_variant:
15215     case OMPD_declare_target:
15216     case OMPD_end_declare_target:
15217     case OMPD_loop:
15218     case OMPD_teams_loop:
15219     case OMPD_target_teams_loop:
15220     case OMPD_parallel_loop:
15221     case OMPD_target_parallel_loop:
15222     case OMPD_simd:
15223     case OMPD_tile:
15224     case OMPD_unroll:
15225     case OMPD_for:
15226     case OMPD_for_simd:
15227     case OMPD_sections:
15228     case OMPD_section:
15229     case OMPD_single:
15230     case OMPD_master:
15231     case OMPD_masked:
15232     case OMPD_critical:
15233     case OMPD_taskgroup:
15234     case OMPD_ordered:
15235     case OMPD_atomic:
15236     case OMPD_target_teams:
15237     case OMPD_requires:
15238     case OMPD_metadirective:
15239       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
15240     case OMPD_unknown:
15241     default:
15242       llvm_unreachable("Unknown OpenMP directive");
15243     }
15244     break;
15245   case OMPC_device:
15246     switch (DKind) {
15247     case OMPD_target_update:
15248     case OMPD_target_enter_data:
15249     case OMPD_target_exit_data:
15250     case OMPD_target:
15251     case OMPD_target_simd:
15252     case OMPD_target_teams:
15253     case OMPD_target_parallel:
15254     case OMPD_target_teams_distribute:
15255     case OMPD_target_teams_distribute_simd:
15256     case OMPD_target_parallel_for:
15257     case OMPD_target_parallel_for_simd:
15258     case OMPD_target_parallel_loop:
15259     case OMPD_target_teams_distribute_parallel_for:
15260     case OMPD_target_teams_distribute_parallel_for_simd:
15261     case OMPD_target_teams_loop:
15262     case OMPD_dispatch:
15263       CaptureRegion = OMPD_task;
15264       break;
15265     case OMPD_target_data:
15266     case OMPD_interop:
15267       // Do not capture device-clause expressions.
15268       break;
15269     case OMPD_teams_distribute_parallel_for:
15270     case OMPD_teams_distribute_parallel_for_simd:
15271     case OMPD_teams:
15272     case OMPD_teams_distribute:
15273     case OMPD_teams_distribute_simd:
15274     case OMPD_distribute_parallel_for:
15275     case OMPD_distribute_parallel_for_simd:
15276     case OMPD_task:
15277     case OMPD_taskloop:
15278     case OMPD_taskloop_simd:
15279     case OMPD_master_taskloop:
15280     case OMPD_master_taskloop_simd:
15281     case OMPD_parallel_master_taskloop:
15282     case OMPD_parallel_master_taskloop_simd:
15283     case OMPD_cancel:
15284     case OMPD_parallel:
15285     case OMPD_parallel_master:
15286     case OMPD_parallel_sections:
15287     case OMPD_parallel_for:
15288     case OMPD_parallel_for_simd:
15289     case OMPD_threadprivate:
15290     case OMPD_allocate:
15291     case OMPD_taskyield:
15292     case OMPD_barrier:
15293     case OMPD_taskwait:
15294     case OMPD_cancellation_point:
15295     case OMPD_flush:
15296     case OMPD_depobj:
15297     case OMPD_scan:
15298     case OMPD_declare_reduction:
15299     case OMPD_declare_mapper:
15300     case OMPD_declare_simd:
15301     case OMPD_declare_variant:
15302     case OMPD_begin_declare_variant:
15303     case OMPD_end_declare_variant:
15304     case OMPD_declare_target:
15305     case OMPD_end_declare_target:
15306     case OMPD_loop:
15307     case OMPD_teams_loop:
15308     case OMPD_parallel_loop:
15309     case OMPD_simd:
15310     case OMPD_tile:
15311     case OMPD_unroll:
15312     case OMPD_for:
15313     case OMPD_for_simd:
15314     case OMPD_sections:
15315     case OMPD_section:
15316     case OMPD_single:
15317     case OMPD_master:
15318     case OMPD_masked:
15319     case OMPD_critical:
15320     case OMPD_taskgroup:
15321     case OMPD_distribute:
15322     case OMPD_ordered:
15323     case OMPD_atomic:
15324     case OMPD_distribute_simd:
15325     case OMPD_requires:
15326     case OMPD_metadirective:
15327       llvm_unreachable("Unexpected OpenMP directive with device-clause");
15328     case OMPD_unknown:
15329     default:
15330       llvm_unreachable("Unknown OpenMP directive");
15331     }
15332     break;
15333   case OMPC_grainsize:
15334   case OMPC_num_tasks:
15335   case OMPC_final:
15336   case OMPC_priority:
15337     switch (DKind) {
15338     case OMPD_task:
15339     case OMPD_taskloop:
15340     case OMPD_taskloop_simd:
15341     case OMPD_master_taskloop:
15342     case OMPD_master_taskloop_simd:
15343       break;
15344     case OMPD_parallel_master_taskloop:
15345     case OMPD_parallel_master_taskloop_simd:
15346       CaptureRegion = OMPD_parallel;
15347       break;
15348     case OMPD_target_update:
15349     case OMPD_target_enter_data:
15350     case OMPD_target_exit_data:
15351     case OMPD_target:
15352     case OMPD_target_simd:
15353     case OMPD_target_teams:
15354     case OMPD_target_parallel:
15355     case OMPD_target_teams_distribute:
15356     case OMPD_target_teams_distribute_simd:
15357     case OMPD_target_parallel_for:
15358     case OMPD_target_parallel_for_simd:
15359     case OMPD_target_teams_distribute_parallel_for:
15360     case OMPD_target_teams_distribute_parallel_for_simd:
15361     case OMPD_target_data:
15362     case OMPD_teams_distribute_parallel_for:
15363     case OMPD_teams_distribute_parallel_for_simd:
15364     case OMPD_teams:
15365     case OMPD_teams_distribute:
15366     case OMPD_teams_distribute_simd:
15367     case OMPD_distribute_parallel_for:
15368     case OMPD_distribute_parallel_for_simd:
15369     case OMPD_cancel:
15370     case OMPD_parallel:
15371     case OMPD_parallel_master:
15372     case OMPD_parallel_sections:
15373     case OMPD_parallel_for:
15374     case OMPD_parallel_for_simd:
15375     case OMPD_threadprivate:
15376     case OMPD_allocate:
15377     case OMPD_taskyield:
15378     case OMPD_barrier:
15379     case OMPD_taskwait:
15380     case OMPD_cancellation_point:
15381     case OMPD_flush:
15382     case OMPD_depobj:
15383     case OMPD_scan:
15384     case OMPD_declare_reduction:
15385     case OMPD_declare_mapper:
15386     case OMPD_declare_simd:
15387     case OMPD_declare_variant:
15388     case OMPD_begin_declare_variant:
15389     case OMPD_end_declare_variant:
15390     case OMPD_declare_target:
15391     case OMPD_end_declare_target:
15392     case OMPD_loop:
15393     case OMPD_teams_loop:
15394     case OMPD_target_teams_loop:
15395     case OMPD_parallel_loop:
15396     case OMPD_target_parallel_loop:
15397     case OMPD_simd:
15398     case OMPD_tile:
15399     case OMPD_unroll:
15400     case OMPD_for:
15401     case OMPD_for_simd:
15402     case OMPD_sections:
15403     case OMPD_section:
15404     case OMPD_single:
15405     case OMPD_master:
15406     case OMPD_masked:
15407     case OMPD_critical:
15408     case OMPD_taskgroup:
15409     case OMPD_distribute:
15410     case OMPD_ordered:
15411     case OMPD_atomic:
15412     case OMPD_distribute_simd:
15413     case OMPD_requires:
15414     case OMPD_metadirective:
15415       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
15416     case OMPD_unknown:
15417     default:
15418       llvm_unreachable("Unknown OpenMP directive");
15419     }
15420     break;
15421   case OMPC_novariants:
15422   case OMPC_nocontext:
15423     switch (DKind) {
15424     case OMPD_dispatch:
15425       CaptureRegion = OMPD_task;
15426       break;
15427     default:
15428       llvm_unreachable("Unexpected OpenMP directive");
15429     }
15430     break;
15431   case OMPC_filter:
15432     // Do not capture filter-clause expressions.
15433     break;
15434   case OMPC_when:
15435     if (DKind == OMPD_metadirective) {
15436       CaptureRegion = OMPD_metadirective;
15437     } else if (DKind == OMPD_unknown) {
15438       llvm_unreachable("Unknown OpenMP directive");
15439     } else {
15440       llvm_unreachable("Unexpected OpenMP directive with when clause");
15441     }
15442     break;
15443   case OMPC_firstprivate:
15444   case OMPC_lastprivate:
15445   case OMPC_reduction:
15446   case OMPC_task_reduction:
15447   case OMPC_in_reduction:
15448   case OMPC_linear:
15449   case OMPC_default:
15450   case OMPC_proc_bind:
15451   case OMPC_safelen:
15452   case OMPC_simdlen:
15453   case OMPC_sizes:
15454   case OMPC_allocator:
15455   case OMPC_collapse:
15456   case OMPC_private:
15457   case OMPC_shared:
15458   case OMPC_aligned:
15459   case OMPC_copyin:
15460   case OMPC_copyprivate:
15461   case OMPC_ordered:
15462   case OMPC_nowait:
15463   case OMPC_untied:
15464   case OMPC_mergeable:
15465   case OMPC_threadprivate:
15466   case OMPC_allocate:
15467   case OMPC_flush:
15468   case OMPC_depobj:
15469   case OMPC_read:
15470   case OMPC_write:
15471   case OMPC_update:
15472   case OMPC_capture:
15473   case OMPC_compare:
15474   case OMPC_seq_cst:
15475   case OMPC_acq_rel:
15476   case OMPC_acquire:
15477   case OMPC_release:
15478   case OMPC_relaxed:
15479   case OMPC_depend:
15480   case OMPC_threads:
15481   case OMPC_simd:
15482   case OMPC_map:
15483   case OMPC_nogroup:
15484   case OMPC_hint:
15485   case OMPC_defaultmap:
15486   case OMPC_unknown:
15487   case OMPC_uniform:
15488   case OMPC_to:
15489   case OMPC_from:
15490   case OMPC_use_device_ptr:
15491   case OMPC_use_device_addr:
15492   case OMPC_is_device_ptr:
15493   case OMPC_unified_address:
15494   case OMPC_unified_shared_memory:
15495   case OMPC_reverse_offload:
15496   case OMPC_dynamic_allocators:
15497   case OMPC_atomic_default_mem_order:
15498   case OMPC_device_type:
15499   case OMPC_match:
15500   case OMPC_nontemporal:
15501   case OMPC_order:
15502   case OMPC_destroy:
15503   case OMPC_detach:
15504   case OMPC_inclusive:
15505   case OMPC_exclusive:
15506   case OMPC_uses_allocators:
15507   case OMPC_affinity:
15508   case OMPC_bind:
15509   default:
15510     llvm_unreachable("Unexpected OpenMP clause.");
15511   }
15512   return CaptureRegion;
15513 }
15514 
15515 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
15516                                      Expr *Condition, SourceLocation StartLoc,
15517                                      SourceLocation LParenLoc,
15518                                      SourceLocation NameModifierLoc,
15519                                      SourceLocation ColonLoc,
15520                                      SourceLocation EndLoc) {
15521   Expr *ValExpr = Condition;
15522   Stmt *HelperValStmt = nullptr;
15523   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15524   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15525       !Condition->isInstantiationDependent() &&
15526       !Condition->containsUnexpandedParameterPack()) {
15527     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15528     if (Val.isInvalid())
15529       return nullptr;
15530 
15531     ValExpr = Val.get();
15532 
15533     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15534     CaptureRegion = getOpenMPCaptureRegionForClause(
15535         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
15536     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15537       ValExpr = MakeFullExpr(ValExpr).get();
15538       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15539       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15540       HelperValStmt = buildPreInits(Context, Captures);
15541     }
15542   }
15543 
15544   return new (Context)
15545       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
15546                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
15547 }
15548 
15549 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
15550                                         SourceLocation StartLoc,
15551                                         SourceLocation LParenLoc,
15552                                         SourceLocation EndLoc) {
15553   Expr *ValExpr = Condition;
15554   Stmt *HelperValStmt = nullptr;
15555   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15556   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15557       !Condition->isInstantiationDependent() &&
15558       !Condition->containsUnexpandedParameterPack()) {
15559     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15560     if (Val.isInvalid())
15561       return nullptr;
15562 
15563     ValExpr = MakeFullExpr(Val.get()).get();
15564 
15565     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15566     CaptureRegion =
15567         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
15568     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15569       ValExpr = MakeFullExpr(ValExpr).get();
15570       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15571       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15572       HelperValStmt = buildPreInits(Context, Captures);
15573     }
15574   }
15575 
15576   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
15577                                       StartLoc, LParenLoc, EndLoc);
15578 }
15579 
15580 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
15581                                                         Expr *Op) {
15582   if (!Op)
15583     return ExprError();
15584 
15585   class IntConvertDiagnoser : public ICEConvertDiagnoser {
15586   public:
15587     IntConvertDiagnoser()
15588         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
15589     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15590                                          QualType T) override {
15591       return S.Diag(Loc, diag::err_omp_not_integral) << T;
15592     }
15593     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
15594                                              QualType T) override {
15595       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
15596     }
15597     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
15598                                                QualType T,
15599                                                QualType ConvTy) override {
15600       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
15601     }
15602     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
15603                                            QualType ConvTy) override {
15604       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
15605              << ConvTy->isEnumeralType() << ConvTy;
15606     }
15607     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
15608                                             QualType T) override {
15609       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
15610     }
15611     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
15612                                         QualType ConvTy) override {
15613       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
15614              << ConvTy->isEnumeralType() << ConvTy;
15615     }
15616     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
15617                                              QualType) override {
15618       llvm_unreachable("conversion functions are permitted");
15619     }
15620   } ConvertDiagnoser;
15621   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
15622 }
15623 
15624 static bool
15625 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
15626                           bool StrictlyPositive, bool BuildCapture = false,
15627                           OpenMPDirectiveKind DKind = OMPD_unknown,
15628                           OpenMPDirectiveKind *CaptureRegion = nullptr,
15629                           Stmt **HelperValStmt = nullptr) {
15630   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
15631       !ValExpr->isInstantiationDependent()) {
15632     SourceLocation Loc = ValExpr->getExprLoc();
15633     ExprResult Value =
15634         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
15635     if (Value.isInvalid())
15636       return false;
15637 
15638     ValExpr = Value.get();
15639     // The expression must evaluate to a non-negative integer value.
15640     if (Optional<llvm::APSInt> Result =
15641             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
15642       if (Result->isSigned() &&
15643           !((!StrictlyPositive && Result->isNonNegative()) ||
15644             (StrictlyPositive && Result->isStrictlyPositive()))) {
15645         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
15646             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
15647             << ValExpr->getSourceRange();
15648         return false;
15649       }
15650     }
15651     if (!BuildCapture)
15652       return true;
15653     *CaptureRegion =
15654         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
15655     if (*CaptureRegion != OMPD_unknown &&
15656         !SemaRef.CurContext->isDependentContext()) {
15657       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
15658       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15659       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
15660       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
15661     }
15662   }
15663   return true;
15664 }
15665 
15666 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
15667                                              SourceLocation StartLoc,
15668                                              SourceLocation LParenLoc,
15669                                              SourceLocation EndLoc) {
15670   Expr *ValExpr = NumThreads;
15671   Stmt *HelperValStmt = nullptr;
15672 
15673   // OpenMP [2.5, Restrictions]
15674   //  The num_threads expression must evaluate to a positive integer value.
15675   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
15676                                  /*StrictlyPositive=*/true))
15677     return nullptr;
15678 
15679   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15680   OpenMPDirectiveKind CaptureRegion =
15681       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
15682   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15683     ValExpr = MakeFullExpr(ValExpr).get();
15684     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15685     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15686     HelperValStmt = buildPreInits(Context, Captures);
15687   }
15688 
15689   return new (Context) OMPNumThreadsClause(
15690       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15691 }
15692 
15693 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
15694                                                        OpenMPClauseKind CKind,
15695                                                        bool StrictlyPositive,
15696                                                        bool SuppressExprDiags) {
15697   if (!E)
15698     return ExprError();
15699   if (E->isValueDependent() || E->isTypeDependent() ||
15700       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15701     return E;
15702 
15703   llvm::APSInt Result;
15704   ExprResult ICE;
15705   if (SuppressExprDiags) {
15706     // Use a custom diagnoser that suppresses 'note' diagnostics about the
15707     // expression.
15708     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
15709       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
15710       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
15711                                                  SourceLocation Loc) override {
15712         llvm_unreachable("Diagnostic suppressed");
15713       }
15714     } Diagnoser;
15715     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
15716   } else {
15717     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
15718   }
15719   if (ICE.isInvalid())
15720     return ExprError();
15721 
15722   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
15723       (!StrictlyPositive && !Result.isNonNegative())) {
15724     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
15725         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
15726         << E->getSourceRange();
15727     return ExprError();
15728   }
15729   if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
15730     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
15731         << E->getSourceRange();
15732     return ExprError();
15733   }
15734   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
15735     DSAStack->setAssociatedLoops(Result.getExtValue());
15736   else if (CKind == OMPC_ordered)
15737     DSAStack->setAssociatedLoops(Result.getExtValue());
15738   return ICE;
15739 }
15740 
15741 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
15742                                           SourceLocation LParenLoc,
15743                                           SourceLocation EndLoc) {
15744   // OpenMP [2.8.1, simd construct, Description]
15745   // The parameter of the safelen clause must be a constant
15746   // positive integer expression.
15747   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
15748   if (Safelen.isInvalid())
15749     return nullptr;
15750   return new (Context)
15751       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
15752 }
15753 
15754 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
15755                                           SourceLocation LParenLoc,
15756                                           SourceLocation EndLoc) {
15757   // OpenMP [2.8.1, simd construct, Description]
15758   // The parameter of the simdlen clause must be a constant
15759   // positive integer expression.
15760   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
15761   if (Simdlen.isInvalid())
15762     return nullptr;
15763   return new (Context)
15764       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
15765 }
15766 
15767 /// Tries to find omp_allocator_handle_t type.
15768 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
15769                                     DSAStackTy *Stack) {
15770   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
15771   if (!OMPAllocatorHandleT.isNull())
15772     return true;
15773   // Build the predefined allocator expressions.
15774   bool ErrorFound = false;
15775   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
15776     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
15777     StringRef Allocator =
15778         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
15779     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
15780     auto *VD = dyn_cast_or_null<ValueDecl>(
15781         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
15782     if (!VD) {
15783       ErrorFound = true;
15784       break;
15785     }
15786     QualType AllocatorType =
15787         VD->getType().getNonLValueExprType(S.getASTContext());
15788     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
15789     if (!Res.isUsable()) {
15790       ErrorFound = true;
15791       break;
15792     }
15793     if (OMPAllocatorHandleT.isNull())
15794       OMPAllocatorHandleT = AllocatorType;
15795     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
15796       ErrorFound = true;
15797       break;
15798     }
15799     Stack->setAllocator(AllocatorKind, Res.get());
15800   }
15801   if (ErrorFound) {
15802     S.Diag(Loc, diag::err_omp_implied_type_not_found)
15803         << "omp_allocator_handle_t";
15804     return false;
15805   }
15806   OMPAllocatorHandleT.addConst();
15807   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
15808   return true;
15809 }
15810 
15811 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
15812                                             SourceLocation LParenLoc,
15813                                             SourceLocation EndLoc) {
15814   // OpenMP [2.11.3, allocate Directive, Description]
15815   // allocator is an expression of omp_allocator_handle_t type.
15816   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
15817     return nullptr;
15818 
15819   ExprResult Allocator = DefaultLvalueConversion(A);
15820   if (Allocator.isInvalid())
15821     return nullptr;
15822   Allocator = PerformImplicitConversion(Allocator.get(),
15823                                         DSAStack->getOMPAllocatorHandleT(),
15824                                         Sema::AA_Initializing,
15825                                         /*AllowExplicit=*/true);
15826   if (Allocator.isInvalid())
15827     return nullptr;
15828   return new (Context)
15829       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
15830 }
15831 
15832 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
15833                                            SourceLocation StartLoc,
15834                                            SourceLocation LParenLoc,
15835                                            SourceLocation EndLoc) {
15836   // OpenMP [2.7.1, loop construct, Description]
15837   // OpenMP [2.8.1, simd construct, Description]
15838   // OpenMP [2.9.6, distribute construct, Description]
15839   // The parameter of the collapse clause must be a constant
15840   // positive integer expression.
15841   ExprResult NumForLoopsResult =
15842       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
15843   if (NumForLoopsResult.isInvalid())
15844     return nullptr;
15845   return new (Context)
15846       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
15847 }
15848 
15849 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
15850                                           SourceLocation EndLoc,
15851                                           SourceLocation LParenLoc,
15852                                           Expr *NumForLoops) {
15853   // OpenMP [2.7.1, loop construct, Description]
15854   // OpenMP [2.8.1, simd construct, Description]
15855   // OpenMP [2.9.6, distribute construct, Description]
15856   // The parameter of the ordered clause must be a constant
15857   // positive integer expression if any.
15858   if (NumForLoops && LParenLoc.isValid()) {
15859     ExprResult NumForLoopsResult =
15860         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
15861     if (NumForLoopsResult.isInvalid())
15862       return nullptr;
15863     NumForLoops = NumForLoopsResult.get();
15864   } else {
15865     NumForLoops = nullptr;
15866   }
15867   auto *Clause = OMPOrderedClause::Create(
15868       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
15869       StartLoc, LParenLoc, EndLoc);
15870   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
15871   return Clause;
15872 }
15873 
15874 OMPClause *Sema::ActOnOpenMPSimpleClause(
15875     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
15876     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15877   OMPClause *Res = nullptr;
15878   switch (Kind) {
15879   case OMPC_default:
15880     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
15881                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15882     break;
15883   case OMPC_proc_bind:
15884     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
15885                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15886     break;
15887   case OMPC_atomic_default_mem_order:
15888     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
15889         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
15890         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15891     break;
15892   case OMPC_order:
15893     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
15894                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15895     break;
15896   case OMPC_update:
15897     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
15898                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15899     break;
15900   case OMPC_bind:
15901     Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
15902                                 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15903     break;
15904   case OMPC_if:
15905   case OMPC_final:
15906   case OMPC_num_threads:
15907   case OMPC_safelen:
15908   case OMPC_simdlen:
15909   case OMPC_sizes:
15910   case OMPC_allocator:
15911   case OMPC_collapse:
15912   case OMPC_schedule:
15913   case OMPC_private:
15914   case OMPC_firstprivate:
15915   case OMPC_lastprivate:
15916   case OMPC_shared:
15917   case OMPC_reduction:
15918   case OMPC_task_reduction:
15919   case OMPC_in_reduction:
15920   case OMPC_linear:
15921   case OMPC_aligned:
15922   case OMPC_copyin:
15923   case OMPC_copyprivate:
15924   case OMPC_ordered:
15925   case OMPC_nowait:
15926   case OMPC_untied:
15927   case OMPC_mergeable:
15928   case OMPC_threadprivate:
15929   case OMPC_allocate:
15930   case OMPC_flush:
15931   case OMPC_depobj:
15932   case OMPC_read:
15933   case OMPC_write:
15934   case OMPC_capture:
15935   case OMPC_compare:
15936   case OMPC_seq_cst:
15937   case OMPC_acq_rel:
15938   case OMPC_acquire:
15939   case OMPC_release:
15940   case OMPC_relaxed:
15941   case OMPC_depend:
15942   case OMPC_device:
15943   case OMPC_threads:
15944   case OMPC_simd:
15945   case OMPC_map:
15946   case OMPC_num_teams:
15947   case OMPC_thread_limit:
15948   case OMPC_priority:
15949   case OMPC_grainsize:
15950   case OMPC_nogroup:
15951   case OMPC_num_tasks:
15952   case OMPC_hint:
15953   case OMPC_dist_schedule:
15954   case OMPC_defaultmap:
15955   case OMPC_unknown:
15956   case OMPC_uniform:
15957   case OMPC_to:
15958   case OMPC_from:
15959   case OMPC_use_device_ptr:
15960   case OMPC_use_device_addr:
15961   case OMPC_is_device_ptr:
15962   case OMPC_unified_address:
15963   case OMPC_unified_shared_memory:
15964   case OMPC_reverse_offload:
15965   case OMPC_dynamic_allocators:
15966   case OMPC_device_type:
15967   case OMPC_match:
15968   case OMPC_nontemporal:
15969   case OMPC_destroy:
15970   case OMPC_novariants:
15971   case OMPC_nocontext:
15972   case OMPC_detach:
15973   case OMPC_inclusive:
15974   case OMPC_exclusive:
15975   case OMPC_uses_allocators:
15976   case OMPC_affinity:
15977   case OMPC_when:
15978   default:
15979     llvm_unreachable("Clause is not allowed.");
15980   }
15981   return Res;
15982 }
15983 
15984 static std::string
15985 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
15986                         ArrayRef<unsigned> Exclude = llvm::None) {
15987   SmallString<256> Buffer;
15988   llvm::raw_svector_ostream Out(Buffer);
15989   unsigned Skipped = Exclude.size();
15990   auto S = Exclude.begin(), E = Exclude.end();
15991   for (unsigned I = First; I < Last; ++I) {
15992     if (std::find(S, E, I) != E) {
15993       --Skipped;
15994       continue;
15995     }
15996     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
15997     if (I + Skipped + 2 == Last)
15998       Out << " or ";
15999     else if (I + Skipped + 1 != Last)
16000       Out << ", ";
16001   }
16002   return std::string(Out.str());
16003 }
16004 
16005 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
16006                                           SourceLocation KindKwLoc,
16007                                           SourceLocation StartLoc,
16008                                           SourceLocation LParenLoc,
16009                                           SourceLocation EndLoc) {
16010   if (Kind == OMP_DEFAULT_unknown) {
16011     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16012         << getListOfPossibleValues(OMPC_default, /*First=*/0,
16013                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
16014         << getOpenMPClauseName(OMPC_default);
16015     return nullptr;
16016   }
16017 
16018   switch (Kind) {
16019   case OMP_DEFAULT_none:
16020     DSAStack->setDefaultDSANone(KindKwLoc);
16021     break;
16022   case OMP_DEFAULT_shared:
16023     DSAStack->setDefaultDSAShared(KindKwLoc);
16024     break;
16025   case OMP_DEFAULT_firstprivate:
16026     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
16027     break;
16028   default:
16029     llvm_unreachable("DSA unexpected in OpenMP default clause");
16030   }
16031 
16032   return new (Context)
16033       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
16034 }
16035 
16036 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
16037                                            SourceLocation KindKwLoc,
16038                                            SourceLocation StartLoc,
16039                                            SourceLocation LParenLoc,
16040                                            SourceLocation EndLoc) {
16041   if (Kind == OMP_PROC_BIND_unknown) {
16042     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16043         << getListOfPossibleValues(OMPC_proc_bind,
16044                                    /*First=*/unsigned(OMP_PROC_BIND_master),
16045                                    /*Last=*/
16046                                    unsigned(LangOpts.OpenMP > 50
16047                                                 ? OMP_PROC_BIND_primary
16048                                                 : OMP_PROC_BIND_spread) +
16049                                        1)
16050         << getOpenMPClauseName(OMPC_proc_bind);
16051     return nullptr;
16052   }
16053   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
16054     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16055         << getListOfPossibleValues(OMPC_proc_bind,
16056                                    /*First=*/unsigned(OMP_PROC_BIND_master),
16057                                    /*Last=*/
16058                                    unsigned(OMP_PROC_BIND_spread) + 1)
16059         << getOpenMPClauseName(OMPC_proc_bind);
16060   return new (Context)
16061       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
16062 }
16063 
16064 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
16065     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
16066     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16067   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
16068     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16069         << getListOfPossibleValues(
16070                OMPC_atomic_default_mem_order, /*First=*/0,
16071                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
16072         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
16073     return nullptr;
16074   }
16075   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
16076                                                       LParenLoc, EndLoc);
16077 }
16078 
16079 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
16080                                         SourceLocation KindKwLoc,
16081                                         SourceLocation StartLoc,
16082                                         SourceLocation LParenLoc,
16083                                         SourceLocation EndLoc) {
16084   if (Kind == OMPC_ORDER_unknown) {
16085     static_assert(OMPC_ORDER_unknown > 0,
16086                   "OMPC_ORDER_unknown not greater than 0");
16087     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16088         << getListOfPossibleValues(OMPC_order, /*First=*/0,
16089                                    /*Last=*/OMPC_ORDER_unknown)
16090         << getOpenMPClauseName(OMPC_order);
16091     return nullptr;
16092   }
16093   return new (Context)
16094       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
16095 }
16096 
16097 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
16098                                          SourceLocation KindKwLoc,
16099                                          SourceLocation StartLoc,
16100                                          SourceLocation LParenLoc,
16101                                          SourceLocation EndLoc) {
16102   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
16103       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
16104     SmallVector<unsigned> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
16105                                     OMPC_DEPEND_depobj};
16106     if (LangOpts.OpenMP < 51)
16107       Except.push_back(OMPC_DEPEND_inoutset);
16108     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16109         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
16110                                    /*Last=*/OMPC_DEPEND_unknown, Except)
16111         << getOpenMPClauseName(OMPC_update);
16112     return nullptr;
16113   }
16114   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
16115                                  EndLoc);
16116 }
16117 
16118 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
16119                                         SourceLocation StartLoc,
16120                                         SourceLocation LParenLoc,
16121                                         SourceLocation EndLoc) {
16122   for (Expr *SizeExpr : SizeExprs) {
16123     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
16124         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
16125     if (!NumForLoopsResult.isUsable())
16126       return nullptr;
16127   }
16128 
16129   DSAStack->setAssociatedLoops(SizeExprs.size());
16130   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16131                                 SizeExprs);
16132 }
16133 
16134 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
16135                                        SourceLocation EndLoc) {
16136   return OMPFullClause::Create(Context, StartLoc, EndLoc);
16137 }
16138 
16139 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
16140                                           SourceLocation StartLoc,
16141                                           SourceLocation LParenLoc,
16142                                           SourceLocation EndLoc) {
16143   if (FactorExpr) {
16144     // If an argument is specified, it must be a constant (or an unevaluated
16145     // template expression).
16146     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
16147         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
16148     if (FactorResult.isInvalid())
16149       return nullptr;
16150     FactorExpr = FactorResult.get();
16151   }
16152 
16153   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16154                                   FactorExpr);
16155 }
16156 
16157 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
16158                                         SourceLocation LParenLoc,
16159                                         SourceLocation EndLoc) {
16160   ExprResult AlignVal;
16161   AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
16162   if (AlignVal.isInvalid())
16163     return nullptr;
16164   return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
16165                                 EndLoc);
16166 }
16167 
16168 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
16169     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
16170     SourceLocation StartLoc, SourceLocation LParenLoc,
16171     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
16172     SourceLocation EndLoc) {
16173   OMPClause *Res = nullptr;
16174   switch (Kind) {
16175   case OMPC_schedule:
16176     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
16177     assert(Argument.size() == NumberOfElements &&
16178            ArgumentLoc.size() == NumberOfElements);
16179     Res = ActOnOpenMPScheduleClause(
16180         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
16181         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
16182         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
16183         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
16184         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
16185     break;
16186   case OMPC_if:
16187     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
16188     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
16189                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
16190                               DelimLoc, EndLoc);
16191     break;
16192   case OMPC_dist_schedule:
16193     Res = ActOnOpenMPDistScheduleClause(
16194         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
16195         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
16196     break;
16197   case OMPC_defaultmap:
16198     enum { Modifier, DefaultmapKind };
16199     Res = ActOnOpenMPDefaultmapClause(
16200         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
16201         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
16202         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
16203         EndLoc);
16204     break;
16205   case OMPC_device:
16206     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
16207     Res = ActOnOpenMPDeviceClause(
16208         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
16209         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
16210     break;
16211   case OMPC_final:
16212   case OMPC_num_threads:
16213   case OMPC_safelen:
16214   case OMPC_simdlen:
16215   case OMPC_sizes:
16216   case OMPC_allocator:
16217   case OMPC_collapse:
16218   case OMPC_default:
16219   case OMPC_proc_bind:
16220   case OMPC_private:
16221   case OMPC_firstprivate:
16222   case OMPC_lastprivate:
16223   case OMPC_shared:
16224   case OMPC_reduction:
16225   case OMPC_task_reduction:
16226   case OMPC_in_reduction:
16227   case OMPC_linear:
16228   case OMPC_aligned:
16229   case OMPC_copyin:
16230   case OMPC_copyprivate:
16231   case OMPC_ordered:
16232   case OMPC_nowait:
16233   case OMPC_untied:
16234   case OMPC_mergeable:
16235   case OMPC_threadprivate:
16236   case OMPC_allocate:
16237   case OMPC_flush:
16238   case OMPC_depobj:
16239   case OMPC_read:
16240   case OMPC_write:
16241   case OMPC_update:
16242   case OMPC_capture:
16243   case OMPC_compare:
16244   case OMPC_seq_cst:
16245   case OMPC_acq_rel:
16246   case OMPC_acquire:
16247   case OMPC_release:
16248   case OMPC_relaxed:
16249   case OMPC_depend:
16250   case OMPC_threads:
16251   case OMPC_simd:
16252   case OMPC_map:
16253   case OMPC_num_teams:
16254   case OMPC_thread_limit:
16255   case OMPC_priority:
16256   case OMPC_grainsize:
16257   case OMPC_nogroup:
16258   case OMPC_num_tasks:
16259   case OMPC_hint:
16260   case OMPC_unknown:
16261   case OMPC_uniform:
16262   case OMPC_to:
16263   case OMPC_from:
16264   case OMPC_use_device_ptr:
16265   case OMPC_use_device_addr:
16266   case OMPC_is_device_ptr:
16267   case OMPC_unified_address:
16268   case OMPC_unified_shared_memory:
16269   case OMPC_reverse_offload:
16270   case OMPC_dynamic_allocators:
16271   case OMPC_atomic_default_mem_order:
16272   case OMPC_device_type:
16273   case OMPC_match:
16274   case OMPC_nontemporal:
16275   case OMPC_order:
16276   case OMPC_destroy:
16277   case OMPC_novariants:
16278   case OMPC_nocontext:
16279   case OMPC_detach:
16280   case OMPC_inclusive:
16281   case OMPC_exclusive:
16282   case OMPC_uses_allocators:
16283   case OMPC_affinity:
16284   case OMPC_when:
16285   case OMPC_bind:
16286   default:
16287     llvm_unreachable("Clause is not allowed.");
16288   }
16289   return Res;
16290 }
16291 
16292 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
16293                                    OpenMPScheduleClauseModifier M2,
16294                                    SourceLocation M1Loc, SourceLocation M2Loc) {
16295   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
16296     SmallVector<unsigned, 2> Excluded;
16297     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
16298       Excluded.push_back(M2);
16299     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
16300       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
16301     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
16302       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
16303     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
16304         << getListOfPossibleValues(OMPC_schedule,
16305                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
16306                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
16307                                    Excluded)
16308         << getOpenMPClauseName(OMPC_schedule);
16309     return true;
16310   }
16311   return false;
16312 }
16313 
16314 OMPClause *Sema::ActOnOpenMPScheduleClause(
16315     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
16316     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16317     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
16318     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
16319   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
16320       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
16321     return nullptr;
16322   // OpenMP, 2.7.1, Loop Construct, Restrictions
16323   // Either the monotonic modifier or the nonmonotonic modifier can be specified
16324   // but not both.
16325   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
16326       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
16327        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
16328       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
16329        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
16330     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
16331         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
16332         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
16333     return nullptr;
16334   }
16335   if (Kind == OMPC_SCHEDULE_unknown) {
16336     std::string Values;
16337     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
16338       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
16339       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
16340                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
16341                                        Exclude);
16342     } else {
16343       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
16344                                        /*Last=*/OMPC_SCHEDULE_unknown);
16345     }
16346     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16347         << Values << getOpenMPClauseName(OMPC_schedule);
16348     return nullptr;
16349   }
16350   // OpenMP, 2.7.1, Loop Construct, Restrictions
16351   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
16352   // schedule(guided).
16353   // OpenMP 5.0 does not have this restriction.
16354   if (LangOpts.OpenMP < 50 &&
16355       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
16356        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
16357       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
16358     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
16359          diag::err_omp_schedule_nonmonotonic_static);
16360     return nullptr;
16361   }
16362   Expr *ValExpr = ChunkSize;
16363   Stmt *HelperValStmt = nullptr;
16364   if (ChunkSize) {
16365     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16366         !ChunkSize->isInstantiationDependent() &&
16367         !ChunkSize->containsUnexpandedParameterPack()) {
16368       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
16369       ExprResult Val =
16370           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16371       if (Val.isInvalid())
16372         return nullptr;
16373 
16374       ValExpr = Val.get();
16375 
16376       // OpenMP [2.7.1, Restrictions]
16377       //  chunk_size must be a loop invariant integer expression with a positive
16378       //  value.
16379       if (Optional<llvm::APSInt> Result =
16380               ValExpr->getIntegerConstantExpr(Context)) {
16381         if (Result->isSigned() && !Result->isStrictlyPositive()) {
16382           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16383               << "schedule" << 1 << ChunkSize->getSourceRange();
16384           return nullptr;
16385         }
16386       } else if (getOpenMPCaptureRegionForClause(
16387                      DSAStack->getCurrentDirective(), OMPC_schedule,
16388                      LangOpts.OpenMP) != OMPD_unknown &&
16389                  !CurContext->isDependentContext()) {
16390         ValExpr = MakeFullExpr(ValExpr).get();
16391         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16392         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16393         HelperValStmt = buildPreInits(Context, Captures);
16394       }
16395     }
16396   }
16397 
16398   return new (Context)
16399       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
16400                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
16401 }
16402 
16403 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
16404                                    SourceLocation StartLoc,
16405                                    SourceLocation EndLoc) {
16406   OMPClause *Res = nullptr;
16407   switch (Kind) {
16408   case OMPC_ordered:
16409     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
16410     break;
16411   case OMPC_nowait:
16412     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
16413     break;
16414   case OMPC_untied:
16415     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
16416     break;
16417   case OMPC_mergeable:
16418     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
16419     break;
16420   case OMPC_read:
16421     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
16422     break;
16423   case OMPC_write:
16424     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
16425     break;
16426   case OMPC_update:
16427     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
16428     break;
16429   case OMPC_capture:
16430     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
16431     break;
16432   case OMPC_compare:
16433     Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
16434     break;
16435   case OMPC_seq_cst:
16436     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
16437     break;
16438   case OMPC_acq_rel:
16439     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
16440     break;
16441   case OMPC_acquire:
16442     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
16443     break;
16444   case OMPC_release:
16445     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
16446     break;
16447   case OMPC_relaxed:
16448     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
16449     break;
16450   case OMPC_threads:
16451     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
16452     break;
16453   case OMPC_simd:
16454     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
16455     break;
16456   case OMPC_nogroup:
16457     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
16458     break;
16459   case OMPC_unified_address:
16460     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
16461     break;
16462   case OMPC_unified_shared_memory:
16463     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
16464     break;
16465   case OMPC_reverse_offload:
16466     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
16467     break;
16468   case OMPC_dynamic_allocators:
16469     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
16470     break;
16471   case OMPC_destroy:
16472     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
16473                                    /*LParenLoc=*/SourceLocation(),
16474                                    /*VarLoc=*/SourceLocation(), EndLoc);
16475     break;
16476   case OMPC_full:
16477     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
16478     break;
16479   case OMPC_partial:
16480     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
16481     break;
16482   case OMPC_if:
16483   case OMPC_final:
16484   case OMPC_num_threads:
16485   case OMPC_safelen:
16486   case OMPC_simdlen:
16487   case OMPC_sizes:
16488   case OMPC_allocator:
16489   case OMPC_collapse:
16490   case OMPC_schedule:
16491   case OMPC_private:
16492   case OMPC_firstprivate:
16493   case OMPC_lastprivate:
16494   case OMPC_shared:
16495   case OMPC_reduction:
16496   case OMPC_task_reduction:
16497   case OMPC_in_reduction:
16498   case OMPC_linear:
16499   case OMPC_aligned:
16500   case OMPC_copyin:
16501   case OMPC_copyprivate:
16502   case OMPC_default:
16503   case OMPC_proc_bind:
16504   case OMPC_threadprivate:
16505   case OMPC_allocate:
16506   case OMPC_flush:
16507   case OMPC_depobj:
16508   case OMPC_depend:
16509   case OMPC_device:
16510   case OMPC_map:
16511   case OMPC_num_teams:
16512   case OMPC_thread_limit:
16513   case OMPC_priority:
16514   case OMPC_grainsize:
16515   case OMPC_num_tasks:
16516   case OMPC_hint:
16517   case OMPC_dist_schedule:
16518   case OMPC_defaultmap:
16519   case OMPC_unknown:
16520   case OMPC_uniform:
16521   case OMPC_to:
16522   case OMPC_from:
16523   case OMPC_use_device_ptr:
16524   case OMPC_use_device_addr:
16525   case OMPC_is_device_ptr:
16526   case OMPC_atomic_default_mem_order:
16527   case OMPC_device_type:
16528   case OMPC_match:
16529   case OMPC_nontemporal:
16530   case OMPC_order:
16531   case OMPC_novariants:
16532   case OMPC_nocontext:
16533   case OMPC_detach:
16534   case OMPC_inclusive:
16535   case OMPC_exclusive:
16536   case OMPC_uses_allocators:
16537   case OMPC_affinity:
16538   case OMPC_when:
16539   default:
16540     llvm_unreachable("Clause is not allowed.");
16541   }
16542   return Res;
16543 }
16544 
16545 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
16546                                          SourceLocation EndLoc) {
16547   DSAStack->setNowaitRegion();
16548   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
16549 }
16550 
16551 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
16552                                          SourceLocation EndLoc) {
16553   DSAStack->setUntiedRegion();
16554   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
16555 }
16556 
16557 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
16558                                             SourceLocation EndLoc) {
16559   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
16560 }
16561 
16562 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
16563                                        SourceLocation EndLoc) {
16564   return new (Context) OMPReadClause(StartLoc, EndLoc);
16565 }
16566 
16567 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
16568                                         SourceLocation EndLoc) {
16569   return new (Context) OMPWriteClause(StartLoc, EndLoc);
16570 }
16571 
16572 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
16573                                          SourceLocation EndLoc) {
16574   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
16575 }
16576 
16577 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
16578                                           SourceLocation EndLoc) {
16579   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
16580 }
16581 
16582 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc,
16583                                           SourceLocation EndLoc) {
16584   return new (Context) OMPCompareClause(StartLoc, EndLoc);
16585 }
16586 
16587 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
16588                                          SourceLocation EndLoc) {
16589   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
16590 }
16591 
16592 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
16593                                          SourceLocation EndLoc) {
16594   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
16595 }
16596 
16597 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
16598                                           SourceLocation EndLoc) {
16599   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
16600 }
16601 
16602 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
16603                                           SourceLocation EndLoc) {
16604   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
16605 }
16606 
16607 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
16608                                           SourceLocation EndLoc) {
16609   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
16610 }
16611 
16612 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
16613                                           SourceLocation EndLoc) {
16614   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
16615 }
16616 
16617 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
16618                                        SourceLocation EndLoc) {
16619   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
16620 }
16621 
16622 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
16623                                           SourceLocation EndLoc) {
16624   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
16625 }
16626 
16627 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
16628                                                  SourceLocation EndLoc) {
16629   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
16630 }
16631 
16632 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
16633                                                       SourceLocation EndLoc) {
16634   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
16635 }
16636 
16637 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
16638                                                  SourceLocation EndLoc) {
16639   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
16640 }
16641 
16642 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
16643                                                     SourceLocation EndLoc) {
16644   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
16645 }
16646 
16647 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
16648                                              SourceLocation StartLoc,
16649                                              SourceLocation EndLoc) {
16650 
16651   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16652   // At least one action-clause must appear on a directive.
16653   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
16654     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
16655     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
16656         << Expected << getOpenMPDirectiveName(OMPD_interop);
16657     return StmtError();
16658   }
16659 
16660   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16661   // A depend clause can only appear on the directive if a targetsync
16662   // interop-type is present or the interop-var was initialized with
16663   // the targetsync interop-type.
16664 
16665   // If there is any 'init' clause diagnose if there is no 'init' clause with
16666   // interop-type of 'targetsync'. Cases involving other directives cannot be
16667   // diagnosed.
16668   const OMPDependClause *DependClause = nullptr;
16669   bool HasInitClause = false;
16670   bool IsTargetSync = false;
16671   for (const OMPClause *C : Clauses) {
16672     if (IsTargetSync)
16673       break;
16674     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
16675       HasInitClause = true;
16676       if (InitClause->getIsTargetSync())
16677         IsTargetSync = true;
16678     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
16679       DependClause = DC;
16680     }
16681   }
16682   if (DependClause && HasInitClause && !IsTargetSync) {
16683     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
16684     return StmtError();
16685   }
16686 
16687   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16688   // Each interop-var may be specified for at most one action-clause of each
16689   // interop construct.
16690   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
16691   for (const OMPClause *C : Clauses) {
16692     OpenMPClauseKind ClauseKind = C->getClauseKind();
16693     const DeclRefExpr *DRE = nullptr;
16694     SourceLocation VarLoc;
16695 
16696     if (ClauseKind == OMPC_init) {
16697       const auto *IC = cast<OMPInitClause>(C);
16698       VarLoc = IC->getVarLoc();
16699       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
16700     } else if (ClauseKind == OMPC_use) {
16701       const auto *UC = cast<OMPUseClause>(C);
16702       VarLoc = UC->getVarLoc();
16703       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
16704     } else if (ClauseKind == OMPC_destroy) {
16705       const auto *DC = cast<OMPDestroyClause>(C);
16706       VarLoc = DC->getVarLoc();
16707       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
16708     }
16709 
16710     if (!DRE)
16711       continue;
16712 
16713     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
16714       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
16715         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
16716         return StmtError();
16717       }
16718     }
16719   }
16720 
16721   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
16722 }
16723 
16724 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
16725                                    SourceLocation VarLoc,
16726                                    OpenMPClauseKind Kind) {
16727   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
16728       InteropVarExpr->isInstantiationDependent() ||
16729       InteropVarExpr->containsUnexpandedParameterPack())
16730     return true;
16731 
16732   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
16733   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
16734     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
16735     return false;
16736   }
16737 
16738   // Interop variable should be of type omp_interop_t.
16739   bool HasError = false;
16740   QualType InteropType;
16741   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
16742                       VarLoc, Sema::LookupOrdinaryName);
16743   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
16744     NamedDecl *ND = Result.getFoundDecl();
16745     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
16746       InteropType = QualType(TD->getTypeForDecl(), 0);
16747     } else {
16748       HasError = true;
16749     }
16750   } else {
16751     HasError = true;
16752   }
16753 
16754   if (HasError) {
16755     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
16756         << "omp_interop_t";
16757     return false;
16758   }
16759 
16760   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
16761   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
16762     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
16763     return false;
16764   }
16765 
16766   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16767   // The interop-var passed to init or destroy must be non-const.
16768   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
16769       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
16770     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
16771         << /*non-const*/ 1;
16772     return false;
16773   }
16774   return true;
16775 }
16776 
16777 OMPClause *
16778 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
16779                             bool IsTarget, bool IsTargetSync,
16780                             SourceLocation StartLoc, SourceLocation LParenLoc,
16781                             SourceLocation VarLoc, SourceLocation EndLoc) {
16782 
16783   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
16784     return nullptr;
16785 
16786   // Check prefer_type values.  These foreign-runtime-id values are either
16787   // string literals or constant integral expressions.
16788   for (const Expr *E : PrefExprs) {
16789     if (E->isValueDependent() || E->isTypeDependent() ||
16790         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
16791       continue;
16792     if (E->isIntegerConstantExpr(Context))
16793       continue;
16794     if (isa<StringLiteral>(E))
16795       continue;
16796     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
16797     return nullptr;
16798   }
16799 
16800   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
16801                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
16802                                EndLoc);
16803 }
16804 
16805 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
16806                                       SourceLocation LParenLoc,
16807                                       SourceLocation VarLoc,
16808                                       SourceLocation EndLoc) {
16809 
16810   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
16811     return nullptr;
16812 
16813   return new (Context)
16814       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
16815 }
16816 
16817 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
16818                                           SourceLocation StartLoc,
16819                                           SourceLocation LParenLoc,
16820                                           SourceLocation VarLoc,
16821                                           SourceLocation EndLoc) {
16822   if (InteropVar &&
16823       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
16824     return nullptr;
16825 
16826   return new (Context)
16827       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
16828 }
16829 
16830 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
16831                                              SourceLocation StartLoc,
16832                                              SourceLocation LParenLoc,
16833                                              SourceLocation EndLoc) {
16834   Expr *ValExpr = Condition;
16835   Stmt *HelperValStmt = nullptr;
16836   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
16837   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
16838       !Condition->isInstantiationDependent() &&
16839       !Condition->containsUnexpandedParameterPack()) {
16840     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
16841     if (Val.isInvalid())
16842       return nullptr;
16843 
16844     ValExpr = MakeFullExpr(Val.get()).get();
16845 
16846     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16847     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
16848                                                     LangOpts.OpenMP);
16849     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16850       ValExpr = MakeFullExpr(ValExpr).get();
16851       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16852       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16853       HelperValStmt = buildPreInits(Context, Captures);
16854     }
16855   }
16856 
16857   return new (Context) OMPNovariantsClause(
16858       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
16859 }
16860 
16861 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
16862                                             SourceLocation StartLoc,
16863                                             SourceLocation LParenLoc,
16864                                             SourceLocation EndLoc) {
16865   Expr *ValExpr = Condition;
16866   Stmt *HelperValStmt = nullptr;
16867   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
16868   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
16869       !Condition->isInstantiationDependent() &&
16870       !Condition->containsUnexpandedParameterPack()) {
16871     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
16872     if (Val.isInvalid())
16873       return nullptr;
16874 
16875     ValExpr = MakeFullExpr(Val.get()).get();
16876 
16877     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16878     CaptureRegion =
16879         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
16880     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16881       ValExpr = MakeFullExpr(ValExpr).get();
16882       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16883       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16884       HelperValStmt = buildPreInits(Context, Captures);
16885     }
16886   }
16887 
16888   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
16889                                           StartLoc, LParenLoc, EndLoc);
16890 }
16891 
16892 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
16893                                          SourceLocation StartLoc,
16894                                          SourceLocation LParenLoc,
16895                                          SourceLocation EndLoc) {
16896   Expr *ValExpr = ThreadID;
16897   Stmt *HelperValStmt = nullptr;
16898 
16899   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16900   OpenMPDirectiveKind CaptureRegion =
16901       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
16902   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16903     ValExpr = MakeFullExpr(ValExpr).get();
16904     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16905     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16906     HelperValStmt = buildPreInits(Context, Captures);
16907   }
16908 
16909   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
16910                                        StartLoc, LParenLoc, EndLoc);
16911 }
16912 
16913 OMPClause *Sema::ActOnOpenMPVarListClause(
16914     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
16915     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
16916     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
16917     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
16918     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16919     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
16920     SourceLocation ExtraModifierLoc,
16921     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
16922     ArrayRef<SourceLocation> MotionModifiersLoc) {
16923   SourceLocation StartLoc = Locs.StartLoc;
16924   SourceLocation LParenLoc = Locs.LParenLoc;
16925   SourceLocation EndLoc = Locs.EndLoc;
16926   OMPClause *Res = nullptr;
16927   switch (Kind) {
16928   case OMPC_private:
16929     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16930     break;
16931   case OMPC_firstprivate:
16932     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16933     break;
16934   case OMPC_lastprivate:
16935     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
16936            "Unexpected lastprivate modifier.");
16937     Res = ActOnOpenMPLastprivateClause(
16938         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
16939         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
16940     break;
16941   case OMPC_shared:
16942     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
16943     break;
16944   case OMPC_reduction:
16945     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
16946            "Unexpected lastprivate modifier.");
16947     Res = ActOnOpenMPReductionClause(
16948         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
16949         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
16950         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
16951     break;
16952   case OMPC_task_reduction:
16953     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
16954                                          EndLoc, ReductionOrMapperIdScopeSpec,
16955                                          ReductionOrMapperId);
16956     break;
16957   case OMPC_in_reduction:
16958     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
16959                                        EndLoc, ReductionOrMapperIdScopeSpec,
16960                                        ReductionOrMapperId);
16961     break;
16962   case OMPC_linear:
16963     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
16964            "Unexpected linear modifier.");
16965     Res = ActOnOpenMPLinearClause(
16966         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
16967         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
16968         ColonLoc, EndLoc);
16969     break;
16970   case OMPC_aligned:
16971     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
16972                                    LParenLoc, ColonLoc, EndLoc);
16973     break;
16974   case OMPC_copyin:
16975     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
16976     break;
16977   case OMPC_copyprivate:
16978     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16979     break;
16980   case OMPC_flush:
16981     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
16982     break;
16983   case OMPC_depend:
16984     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
16985            "Unexpected depend modifier.");
16986     Res = ActOnOpenMPDependClause(
16987         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
16988         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
16989     break;
16990   case OMPC_map:
16991     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
16992            "Unexpected map modifier.");
16993     Res = ActOnOpenMPMapClause(
16994         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
16995         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
16996         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
16997     break;
16998   case OMPC_to:
16999     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
17000                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
17001                               ColonLoc, VarList, Locs);
17002     break;
17003   case OMPC_from:
17004     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
17005                                 ReductionOrMapperIdScopeSpec,
17006                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
17007     break;
17008   case OMPC_use_device_ptr:
17009     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
17010     break;
17011   case OMPC_use_device_addr:
17012     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
17013     break;
17014   case OMPC_is_device_ptr:
17015     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
17016     break;
17017   case OMPC_allocate:
17018     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
17019                                     LParenLoc, ColonLoc, EndLoc);
17020     break;
17021   case OMPC_nontemporal:
17022     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
17023     break;
17024   case OMPC_inclusive:
17025     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
17026     break;
17027   case OMPC_exclusive:
17028     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
17029     break;
17030   case OMPC_affinity:
17031     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
17032                                     DepModOrTailExpr, VarList);
17033     break;
17034   case OMPC_if:
17035   case OMPC_depobj:
17036   case OMPC_final:
17037   case OMPC_num_threads:
17038   case OMPC_safelen:
17039   case OMPC_simdlen:
17040   case OMPC_sizes:
17041   case OMPC_allocator:
17042   case OMPC_collapse:
17043   case OMPC_default:
17044   case OMPC_proc_bind:
17045   case OMPC_schedule:
17046   case OMPC_ordered:
17047   case OMPC_nowait:
17048   case OMPC_untied:
17049   case OMPC_mergeable:
17050   case OMPC_threadprivate:
17051   case OMPC_read:
17052   case OMPC_write:
17053   case OMPC_update:
17054   case OMPC_capture:
17055   case OMPC_compare:
17056   case OMPC_seq_cst:
17057   case OMPC_acq_rel:
17058   case OMPC_acquire:
17059   case OMPC_release:
17060   case OMPC_relaxed:
17061   case OMPC_device:
17062   case OMPC_threads:
17063   case OMPC_simd:
17064   case OMPC_num_teams:
17065   case OMPC_thread_limit:
17066   case OMPC_priority:
17067   case OMPC_grainsize:
17068   case OMPC_nogroup:
17069   case OMPC_num_tasks:
17070   case OMPC_hint:
17071   case OMPC_dist_schedule:
17072   case OMPC_defaultmap:
17073   case OMPC_unknown:
17074   case OMPC_uniform:
17075   case OMPC_unified_address:
17076   case OMPC_unified_shared_memory:
17077   case OMPC_reverse_offload:
17078   case OMPC_dynamic_allocators:
17079   case OMPC_atomic_default_mem_order:
17080   case OMPC_device_type:
17081   case OMPC_match:
17082   case OMPC_order:
17083   case OMPC_destroy:
17084   case OMPC_novariants:
17085   case OMPC_nocontext:
17086   case OMPC_detach:
17087   case OMPC_uses_allocators:
17088   case OMPC_when:
17089   case OMPC_bind:
17090   default:
17091     llvm_unreachable("Clause is not allowed.");
17092   }
17093   return Res;
17094 }
17095 
17096 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
17097                                        ExprObjectKind OK, SourceLocation Loc) {
17098   ExprResult Res = BuildDeclRefExpr(
17099       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
17100   if (!Res.isUsable())
17101     return ExprError();
17102   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
17103     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
17104     if (!Res.isUsable())
17105       return ExprError();
17106   }
17107   if (VK != VK_LValue && Res.get()->isGLValue()) {
17108     Res = DefaultLvalueConversion(Res.get());
17109     if (!Res.isUsable())
17110       return ExprError();
17111   }
17112   return Res;
17113 }
17114 
17115 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
17116                                           SourceLocation StartLoc,
17117                                           SourceLocation LParenLoc,
17118                                           SourceLocation EndLoc) {
17119   SmallVector<Expr *, 8> Vars;
17120   SmallVector<Expr *, 8> PrivateCopies;
17121   for (Expr *RefExpr : VarList) {
17122     assert(RefExpr && "NULL expr in OpenMP private clause.");
17123     SourceLocation ELoc;
17124     SourceRange ERange;
17125     Expr *SimpleRefExpr = RefExpr;
17126     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17127     if (Res.second) {
17128       // It will be analyzed later.
17129       Vars.push_back(RefExpr);
17130       PrivateCopies.push_back(nullptr);
17131     }
17132     ValueDecl *D = Res.first;
17133     if (!D)
17134       continue;
17135 
17136     QualType Type = D->getType();
17137     auto *VD = dyn_cast<VarDecl>(D);
17138 
17139     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17140     //  A variable that appears in a private clause must not have an incomplete
17141     //  type or a reference type.
17142     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
17143       continue;
17144     Type = Type.getNonReferenceType();
17145 
17146     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17147     // A variable that is privatized must not have a const-qualified type
17148     // unless it is of class type with a mutable member. This restriction does
17149     // not apply to the firstprivate clause.
17150     //
17151     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
17152     // A variable that appears in a private clause must not have a
17153     // const-qualified type unless it is of class type with a mutable member.
17154     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
17155       continue;
17156 
17157     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17158     // in a Construct]
17159     //  Variables with the predetermined data-sharing attributes may not be
17160     //  listed in data-sharing attributes clauses, except for the cases
17161     //  listed below. For these exceptions only, listing a predetermined
17162     //  variable in a data-sharing attribute clause is allowed and overrides
17163     //  the variable's predetermined data-sharing attributes.
17164     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17165     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
17166       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17167                                           << getOpenMPClauseName(OMPC_private);
17168       reportOriginalDsa(*this, DSAStack, D, DVar);
17169       continue;
17170     }
17171 
17172     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
17173     // Variably modified types are not supported for tasks.
17174     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
17175         isOpenMPTaskingDirective(CurrDir)) {
17176       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17177           << getOpenMPClauseName(OMPC_private) << Type
17178           << getOpenMPDirectiveName(CurrDir);
17179       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17180                                VarDecl::DeclarationOnly;
17181       Diag(D->getLocation(),
17182            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17183           << D;
17184       continue;
17185     }
17186 
17187     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17188     // A list item cannot appear in both a map clause and a data-sharing
17189     // attribute clause on the same construct
17190     //
17191     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17192     // A list item cannot appear in both a map clause and a data-sharing
17193     // attribute clause on the same construct unless the construct is a
17194     // combined construct.
17195     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
17196         CurrDir == OMPD_target) {
17197       OpenMPClauseKind ConflictKind;
17198       if (DSAStack->checkMappableExprComponentListsForDecl(
17199               VD, /*CurrentRegionOnly=*/true,
17200               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
17201                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
17202                 ConflictKind = WhereFoundClauseKind;
17203                 return true;
17204               })) {
17205         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17206             << getOpenMPClauseName(OMPC_private)
17207             << getOpenMPClauseName(ConflictKind)
17208             << getOpenMPDirectiveName(CurrDir);
17209         reportOriginalDsa(*this, DSAStack, D, DVar);
17210         continue;
17211       }
17212     }
17213 
17214     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
17215     //  A variable of class type (or array thereof) that appears in a private
17216     //  clause requires an accessible, unambiguous default constructor for the
17217     //  class type.
17218     // Generate helper private variable and initialize it with the default
17219     // value. The address of the original variable is replaced by the address of
17220     // the new private variable in CodeGen. This new variable is not added to
17221     // IdResolver, so the code in the OpenMP region uses original variable for
17222     // proper diagnostics.
17223     Type = Type.getUnqualifiedType();
17224     VarDecl *VDPrivate =
17225         buildVarDecl(*this, ELoc, Type, D->getName(),
17226                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17227                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17228     ActOnUninitializedDecl(VDPrivate);
17229     if (VDPrivate->isInvalidDecl())
17230       continue;
17231     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
17232         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17233 
17234     DeclRefExpr *Ref = nullptr;
17235     if (!VD && !CurContext->isDependentContext())
17236       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17237     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
17238     Vars.push_back((VD || CurContext->isDependentContext())
17239                        ? RefExpr->IgnoreParens()
17240                        : Ref);
17241     PrivateCopies.push_back(VDPrivateRefExpr);
17242   }
17243 
17244   if (Vars.empty())
17245     return nullptr;
17246 
17247   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17248                                   PrivateCopies);
17249 }
17250 
17251 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
17252                                                SourceLocation StartLoc,
17253                                                SourceLocation LParenLoc,
17254                                                SourceLocation EndLoc) {
17255   SmallVector<Expr *, 8> Vars;
17256   SmallVector<Expr *, 8> PrivateCopies;
17257   SmallVector<Expr *, 8> Inits;
17258   SmallVector<Decl *, 4> ExprCaptures;
17259   bool IsImplicitClause =
17260       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
17261   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
17262 
17263   for (Expr *RefExpr : VarList) {
17264     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
17265     SourceLocation ELoc;
17266     SourceRange ERange;
17267     Expr *SimpleRefExpr = RefExpr;
17268     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17269     if (Res.second) {
17270       // It will be analyzed later.
17271       Vars.push_back(RefExpr);
17272       PrivateCopies.push_back(nullptr);
17273       Inits.push_back(nullptr);
17274     }
17275     ValueDecl *D = Res.first;
17276     if (!D)
17277       continue;
17278 
17279     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
17280     QualType Type = D->getType();
17281     auto *VD = dyn_cast<VarDecl>(D);
17282 
17283     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17284     //  A variable that appears in a private clause must not have an incomplete
17285     //  type or a reference type.
17286     if (RequireCompleteType(ELoc, Type,
17287                             diag::err_omp_firstprivate_incomplete_type))
17288       continue;
17289     Type = Type.getNonReferenceType();
17290 
17291     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
17292     //  A variable of class type (or array thereof) that appears in a private
17293     //  clause requires an accessible, unambiguous copy constructor for the
17294     //  class type.
17295     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17296 
17297     // If an implicit firstprivate variable found it was checked already.
17298     DSAStackTy::DSAVarData TopDVar;
17299     if (!IsImplicitClause) {
17300       DSAStackTy::DSAVarData DVar =
17301           DSAStack->getTopDSA(D, /*FromParent=*/false);
17302       TopDVar = DVar;
17303       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
17304       bool IsConstant = ElemType.isConstant(Context);
17305       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
17306       //  A list item that specifies a given variable may not appear in more
17307       // than one clause on the same directive, except that a variable may be
17308       //  specified in both firstprivate and lastprivate clauses.
17309       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
17310       // A list item may appear in a firstprivate or lastprivate clause but not
17311       // both.
17312       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
17313           (isOpenMPDistributeDirective(CurrDir) ||
17314            DVar.CKind != OMPC_lastprivate) &&
17315           DVar.RefExpr) {
17316         Diag(ELoc, diag::err_omp_wrong_dsa)
17317             << getOpenMPClauseName(DVar.CKind)
17318             << getOpenMPClauseName(OMPC_firstprivate);
17319         reportOriginalDsa(*this, DSAStack, D, DVar);
17320         continue;
17321       }
17322 
17323       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17324       // in a Construct]
17325       //  Variables with the predetermined data-sharing attributes may not be
17326       //  listed in data-sharing attributes clauses, except for the cases
17327       //  listed below. For these exceptions only, listing a predetermined
17328       //  variable in a data-sharing attribute clause is allowed and overrides
17329       //  the variable's predetermined data-sharing attributes.
17330       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17331       // in a Construct, C/C++, p.2]
17332       //  Variables with const-qualified type having no mutable member may be
17333       //  listed in a firstprivate clause, even if they are static data members.
17334       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
17335           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
17336         Diag(ELoc, diag::err_omp_wrong_dsa)
17337             << getOpenMPClauseName(DVar.CKind)
17338             << getOpenMPClauseName(OMPC_firstprivate);
17339         reportOriginalDsa(*this, DSAStack, D, DVar);
17340         continue;
17341       }
17342 
17343       // OpenMP [2.9.3.4, Restrictions, p.2]
17344       //  A list item that is private within a parallel region must not appear
17345       //  in a firstprivate clause on a worksharing construct if any of the
17346       //  worksharing regions arising from the worksharing construct ever bind
17347       //  to any of the parallel regions arising from the parallel construct.
17348       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
17349       // A list item that is private within a teams region must not appear in a
17350       // firstprivate clause on a distribute construct if any of the distribute
17351       // regions arising from the distribute construct ever bind to any of the
17352       // teams regions arising from the teams construct.
17353       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
17354       // A list item that appears in a reduction clause of a teams construct
17355       // must not appear in a firstprivate clause on a distribute construct if
17356       // any of the distribute regions arising from the distribute construct
17357       // ever bind to any of the teams regions arising from the teams construct.
17358       if ((isOpenMPWorksharingDirective(CurrDir) ||
17359            isOpenMPDistributeDirective(CurrDir)) &&
17360           !isOpenMPParallelDirective(CurrDir) &&
17361           !isOpenMPTeamsDirective(CurrDir)) {
17362         DVar = DSAStack->getImplicitDSA(D, true);
17363         if (DVar.CKind != OMPC_shared &&
17364             (isOpenMPParallelDirective(DVar.DKind) ||
17365              isOpenMPTeamsDirective(DVar.DKind) ||
17366              DVar.DKind == OMPD_unknown)) {
17367           Diag(ELoc, diag::err_omp_required_access)
17368               << getOpenMPClauseName(OMPC_firstprivate)
17369               << getOpenMPClauseName(OMPC_shared);
17370           reportOriginalDsa(*this, DSAStack, D, DVar);
17371           continue;
17372         }
17373       }
17374       // OpenMP [2.9.3.4, Restrictions, p.3]
17375       //  A list item that appears in a reduction clause of a parallel construct
17376       //  must not appear in a firstprivate clause on a worksharing or task
17377       //  construct if any of the worksharing or task regions arising from the
17378       //  worksharing or task construct ever bind to any of the parallel regions
17379       //  arising from the parallel construct.
17380       // OpenMP [2.9.3.4, Restrictions, p.4]
17381       //  A list item that appears in a reduction clause in worksharing
17382       //  construct must not appear in a firstprivate clause in a task construct
17383       //  encountered during execution of any of the worksharing regions arising
17384       //  from the worksharing construct.
17385       if (isOpenMPTaskingDirective(CurrDir)) {
17386         DVar = DSAStack->hasInnermostDSA(
17387             D,
17388             [](OpenMPClauseKind C, bool AppliedToPointee) {
17389               return C == OMPC_reduction && !AppliedToPointee;
17390             },
17391             [](OpenMPDirectiveKind K) {
17392               return isOpenMPParallelDirective(K) ||
17393                      isOpenMPWorksharingDirective(K) ||
17394                      isOpenMPTeamsDirective(K);
17395             },
17396             /*FromParent=*/true);
17397         if (DVar.CKind == OMPC_reduction &&
17398             (isOpenMPParallelDirective(DVar.DKind) ||
17399              isOpenMPWorksharingDirective(DVar.DKind) ||
17400              isOpenMPTeamsDirective(DVar.DKind))) {
17401           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
17402               << getOpenMPDirectiveName(DVar.DKind);
17403           reportOriginalDsa(*this, DSAStack, D, DVar);
17404           continue;
17405         }
17406       }
17407 
17408       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17409       // A list item cannot appear in both a map clause and a data-sharing
17410       // attribute clause on the same construct
17411       //
17412       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17413       // A list item cannot appear in both a map clause and a data-sharing
17414       // attribute clause on the same construct unless the construct is a
17415       // combined construct.
17416       if ((LangOpts.OpenMP <= 45 &&
17417            isOpenMPTargetExecutionDirective(CurrDir)) ||
17418           CurrDir == OMPD_target) {
17419         OpenMPClauseKind ConflictKind;
17420         if (DSAStack->checkMappableExprComponentListsForDecl(
17421                 VD, /*CurrentRegionOnly=*/true,
17422                 [&ConflictKind](
17423                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
17424                     OpenMPClauseKind WhereFoundClauseKind) {
17425                   ConflictKind = WhereFoundClauseKind;
17426                   return true;
17427                 })) {
17428           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17429               << getOpenMPClauseName(OMPC_firstprivate)
17430               << getOpenMPClauseName(ConflictKind)
17431               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17432           reportOriginalDsa(*this, DSAStack, D, DVar);
17433           continue;
17434         }
17435       }
17436     }
17437 
17438     // Variably modified types are not supported for tasks.
17439     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
17440         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
17441       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17442           << getOpenMPClauseName(OMPC_firstprivate) << Type
17443           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17444       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17445                                VarDecl::DeclarationOnly;
17446       Diag(D->getLocation(),
17447            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17448           << D;
17449       continue;
17450     }
17451 
17452     Type = Type.getUnqualifiedType();
17453     VarDecl *VDPrivate =
17454         buildVarDecl(*this, ELoc, Type, D->getName(),
17455                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17456                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17457     // Generate helper private variable and initialize it with the value of the
17458     // original variable. The address of the original variable is replaced by
17459     // the address of the new private variable in the CodeGen. This new variable
17460     // is not added to IdResolver, so the code in the OpenMP region uses
17461     // original variable for proper diagnostics and variable capturing.
17462     Expr *VDInitRefExpr = nullptr;
17463     // For arrays generate initializer for single element and replace it by the
17464     // original array element in CodeGen.
17465     if (Type->isArrayType()) {
17466       VarDecl *VDInit =
17467           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
17468       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
17469       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
17470       ElemType = ElemType.getUnqualifiedType();
17471       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
17472                                          ".firstprivate.temp");
17473       InitializedEntity Entity =
17474           InitializedEntity::InitializeVariable(VDInitTemp);
17475       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
17476 
17477       InitializationSequence InitSeq(*this, Entity, Kind, Init);
17478       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
17479       if (Result.isInvalid())
17480         VDPrivate->setInvalidDecl();
17481       else
17482         VDPrivate->setInit(Result.getAs<Expr>());
17483       // Remove temp variable declaration.
17484       Context.Deallocate(VDInitTemp);
17485     } else {
17486       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
17487                                      ".firstprivate.temp");
17488       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
17489                                        RefExpr->getExprLoc());
17490       AddInitializerToDecl(VDPrivate,
17491                            DefaultLvalueConversion(VDInitRefExpr).get(),
17492                            /*DirectInit=*/false);
17493     }
17494     if (VDPrivate->isInvalidDecl()) {
17495       if (IsImplicitClause) {
17496         Diag(RefExpr->getExprLoc(),
17497              diag::note_omp_task_predetermined_firstprivate_here);
17498       }
17499       continue;
17500     }
17501     CurContext->addDecl(VDPrivate);
17502     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
17503         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
17504         RefExpr->getExprLoc());
17505     DeclRefExpr *Ref = nullptr;
17506     if (!VD && !CurContext->isDependentContext()) {
17507       if (TopDVar.CKind == OMPC_lastprivate) {
17508         Ref = TopDVar.PrivateCopy;
17509       } else {
17510         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17511         if (!isOpenMPCapturedDecl(D))
17512           ExprCaptures.push_back(Ref->getDecl());
17513       }
17514     }
17515     if (!IsImplicitClause)
17516       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17517     Vars.push_back((VD || CurContext->isDependentContext())
17518                        ? RefExpr->IgnoreParens()
17519                        : Ref);
17520     PrivateCopies.push_back(VDPrivateRefExpr);
17521     Inits.push_back(VDInitRefExpr);
17522   }
17523 
17524   if (Vars.empty())
17525     return nullptr;
17526 
17527   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17528                                        Vars, PrivateCopies, Inits,
17529                                        buildPreInits(Context, ExprCaptures));
17530 }
17531 
17532 OMPClause *Sema::ActOnOpenMPLastprivateClause(
17533     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
17534     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
17535     SourceLocation LParenLoc, SourceLocation EndLoc) {
17536   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
17537     assert(ColonLoc.isValid() && "Colon location must be valid.");
17538     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
17539         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
17540                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
17541         << getOpenMPClauseName(OMPC_lastprivate);
17542     return nullptr;
17543   }
17544 
17545   SmallVector<Expr *, 8> Vars;
17546   SmallVector<Expr *, 8> SrcExprs;
17547   SmallVector<Expr *, 8> DstExprs;
17548   SmallVector<Expr *, 8> AssignmentOps;
17549   SmallVector<Decl *, 4> ExprCaptures;
17550   SmallVector<Expr *, 4> ExprPostUpdates;
17551   for (Expr *RefExpr : VarList) {
17552     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
17553     SourceLocation ELoc;
17554     SourceRange ERange;
17555     Expr *SimpleRefExpr = RefExpr;
17556     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17557     if (Res.second) {
17558       // It will be analyzed later.
17559       Vars.push_back(RefExpr);
17560       SrcExprs.push_back(nullptr);
17561       DstExprs.push_back(nullptr);
17562       AssignmentOps.push_back(nullptr);
17563     }
17564     ValueDecl *D = Res.first;
17565     if (!D)
17566       continue;
17567 
17568     QualType Type = D->getType();
17569     auto *VD = dyn_cast<VarDecl>(D);
17570 
17571     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
17572     //  A variable that appears in a lastprivate clause must not have an
17573     //  incomplete type or a reference type.
17574     if (RequireCompleteType(ELoc, Type,
17575                             diag::err_omp_lastprivate_incomplete_type))
17576       continue;
17577     Type = Type.getNonReferenceType();
17578 
17579     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17580     // A variable that is privatized must not have a const-qualified type
17581     // unless it is of class type with a mutable member. This restriction does
17582     // not apply to the firstprivate clause.
17583     //
17584     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
17585     // A variable that appears in a lastprivate clause must not have a
17586     // const-qualified type unless it is of class type with a mutable member.
17587     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
17588       continue;
17589 
17590     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
17591     // A list item that appears in a lastprivate clause with the conditional
17592     // modifier must be a scalar variable.
17593     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
17594       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
17595       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17596                                VarDecl::DeclarationOnly;
17597       Diag(D->getLocation(),
17598            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17599           << D;
17600       continue;
17601     }
17602 
17603     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
17604     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
17605     // in a Construct]
17606     //  Variables with the predetermined data-sharing attributes may not be
17607     //  listed in data-sharing attributes clauses, except for the cases
17608     //  listed below.
17609     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
17610     // A list item may appear in a firstprivate or lastprivate clause but not
17611     // both.
17612     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17613     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
17614         (isOpenMPDistributeDirective(CurrDir) ||
17615          DVar.CKind != OMPC_firstprivate) &&
17616         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
17617       Diag(ELoc, diag::err_omp_wrong_dsa)
17618           << getOpenMPClauseName(DVar.CKind)
17619           << getOpenMPClauseName(OMPC_lastprivate);
17620       reportOriginalDsa(*this, DSAStack, D, DVar);
17621       continue;
17622     }
17623 
17624     // OpenMP [2.14.3.5, Restrictions, p.2]
17625     // A list item that is private within a parallel region, or that appears in
17626     // the reduction clause of a parallel construct, must not appear in a
17627     // lastprivate clause on a worksharing construct if any of the corresponding
17628     // worksharing regions ever binds to any of the corresponding parallel
17629     // regions.
17630     DSAStackTy::DSAVarData TopDVar = DVar;
17631     if (isOpenMPWorksharingDirective(CurrDir) &&
17632         !isOpenMPParallelDirective(CurrDir) &&
17633         !isOpenMPTeamsDirective(CurrDir)) {
17634       DVar = DSAStack->getImplicitDSA(D, true);
17635       if (DVar.CKind != OMPC_shared) {
17636         Diag(ELoc, diag::err_omp_required_access)
17637             << getOpenMPClauseName(OMPC_lastprivate)
17638             << getOpenMPClauseName(OMPC_shared);
17639         reportOriginalDsa(*this, DSAStack, D, DVar);
17640         continue;
17641       }
17642     }
17643 
17644     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
17645     //  A variable of class type (or array thereof) that appears in a
17646     //  lastprivate clause requires an accessible, unambiguous default
17647     //  constructor for the class type, unless the list item is also specified
17648     //  in a firstprivate clause.
17649     //  A variable of class type (or array thereof) that appears in a
17650     //  lastprivate clause requires an accessible, unambiguous copy assignment
17651     //  operator for the class type.
17652     Type = Context.getBaseElementType(Type).getNonReferenceType();
17653     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
17654                                   Type.getUnqualifiedType(), ".lastprivate.src",
17655                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17656     DeclRefExpr *PseudoSrcExpr =
17657         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
17658     VarDecl *DstVD =
17659         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
17660                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17661     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
17662     // For arrays generate assignment operation for single element and replace
17663     // it by the original array element in CodeGen.
17664     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
17665                                          PseudoDstExpr, PseudoSrcExpr);
17666     if (AssignmentOp.isInvalid())
17667       continue;
17668     AssignmentOp =
17669         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
17670     if (AssignmentOp.isInvalid())
17671       continue;
17672 
17673     DeclRefExpr *Ref = nullptr;
17674     if (!VD && !CurContext->isDependentContext()) {
17675       if (TopDVar.CKind == OMPC_firstprivate) {
17676         Ref = TopDVar.PrivateCopy;
17677       } else {
17678         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17679         if (!isOpenMPCapturedDecl(D))
17680           ExprCaptures.push_back(Ref->getDecl());
17681       }
17682       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
17683           (!isOpenMPCapturedDecl(D) &&
17684            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
17685         ExprResult RefRes = DefaultLvalueConversion(Ref);
17686         if (!RefRes.isUsable())
17687           continue;
17688         ExprResult PostUpdateRes =
17689             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17690                        RefRes.get());
17691         if (!PostUpdateRes.isUsable())
17692           continue;
17693         ExprPostUpdates.push_back(
17694             IgnoredValueConversions(PostUpdateRes.get()).get());
17695       }
17696     }
17697     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
17698     Vars.push_back((VD || CurContext->isDependentContext())
17699                        ? RefExpr->IgnoreParens()
17700                        : Ref);
17701     SrcExprs.push_back(PseudoSrcExpr);
17702     DstExprs.push_back(PseudoDstExpr);
17703     AssignmentOps.push_back(AssignmentOp.get());
17704   }
17705 
17706   if (Vars.empty())
17707     return nullptr;
17708 
17709   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17710                                       Vars, SrcExprs, DstExprs, AssignmentOps,
17711                                       LPKind, LPKindLoc, ColonLoc,
17712                                       buildPreInits(Context, ExprCaptures),
17713                                       buildPostUpdate(*this, ExprPostUpdates));
17714 }
17715 
17716 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
17717                                          SourceLocation StartLoc,
17718                                          SourceLocation LParenLoc,
17719                                          SourceLocation EndLoc) {
17720   SmallVector<Expr *, 8> Vars;
17721   for (Expr *RefExpr : VarList) {
17722     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
17723     SourceLocation ELoc;
17724     SourceRange ERange;
17725     Expr *SimpleRefExpr = RefExpr;
17726     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17727     if (Res.second) {
17728       // It will be analyzed later.
17729       Vars.push_back(RefExpr);
17730     }
17731     ValueDecl *D = Res.first;
17732     if (!D)
17733       continue;
17734 
17735     auto *VD = dyn_cast<VarDecl>(D);
17736     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17737     // in a Construct]
17738     //  Variables with the predetermined data-sharing attributes may not be
17739     //  listed in data-sharing attributes clauses, except for the cases
17740     //  listed below. For these exceptions only, listing a predetermined
17741     //  variable in a data-sharing attribute clause is allowed and overrides
17742     //  the variable's predetermined data-sharing attributes.
17743     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17744     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
17745         DVar.RefExpr) {
17746       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17747                                           << getOpenMPClauseName(OMPC_shared);
17748       reportOriginalDsa(*this, DSAStack, D, DVar);
17749       continue;
17750     }
17751 
17752     DeclRefExpr *Ref = nullptr;
17753     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
17754       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17755     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
17756     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
17757                        ? RefExpr->IgnoreParens()
17758                        : Ref);
17759   }
17760 
17761   if (Vars.empty())
17762     return nullptr;
17763 
17764   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
17765 }
17766 
17767 namespace {
17768 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
17769   DSAStackTy *Stack;
17770 
17771 public:
17772   bool VisitDeclRefExpr(DeclRefExpr *E) {
17773     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
17774       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
17775       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
17776         return false;
17777       if (DVar.CKind != OMPC_unknown)
17778         return true;
17779       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
17780           VD,
17781           [](OpenMPClauseKind C, bool AppliedToPointee) {
17782             return isOpenMPPrivate(C) && !AppliedToPointee;
17783           },
17784           [](OpenMPDirectiveKind) { return true; },
17785           /*FromParent=*/true);
17786       return DVarPrivate.CKind != OMPC_unknown;
17787     }
17788     return false;
17789   }
17790   bool VisitStmt(Stmt *S) {
17791     for (Stmt *Child : S->children()) {
17792       if (Child && Visit(Child))
17793         return true;
17794     }
17795     return false;
17796   }
17797   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
17798 };
17799 } // namespace
17800 
17801 namespace {
17802 // Transform MemberExpression for specified FieldDecl of current class to
17803 // DeclRefExpr to specified OMPCapturedExprDecl.
17804 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
17805   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
17806   ValueDecl *Field = nullptr;
17807   DeclRefExpr *CapturedExpr = nullptr;
17808 
17809 public:
17810   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
17811       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
17812 
17813   ExprResult TransformMemberExpr(MemberExpr *E) {
17814     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
17815         E->getMemberDecl() == Field) {
17816       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
17817       return CapturedExpr;
17818     }
17819     return BaseTransform::TransformMemberExpr(E);
17820   }
17821   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
17822 };
17823 } // namespace
17824 
17825 template <typename T, typename U>
17826 static T filterLookupForUDReductionAndMapper(
17827     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
17828   for (U &Set : Lookups) {
17829     for (auto *D : Set) {
17830       if (T Res = Gen(cast<ValueDecl>(D)))
17831         return Res;
17832     }
17833   }
17834   return T();
17835 }
17836 
17837 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
17838   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
17839 
17840   for (auto RD : D->redecls()) {
17841     // Don't bother with extra checks if we already know this one isn't visible.
17842     if (RD == D)
17843       continue;
17844 
17845     auto ND = cast<NamedDecl>(RD);
17846     if (LookupResult::isVisible(SemaRef, ND))
17847       return ND;
17848   }
17849 
17850   return nullptr;
17851 }
17852 
17853 static void
17854 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
17855                         SourceLocation Loc, QualType Ty,
17856                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
17857   // Find all of the associated namespaces and classes based on the
17858   // arguments we have.
17859   Sema::AssociatedNamespaceSet AssociatedNamespaces;
17860   Sema::AssociatedClassSet AssociatedClasses;
17861   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
17862   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
17863                                              AssociatedClasses);
17864 
17865   // C++ [basic.lookup.argdep]p3:
17866   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
17867   //   and let Y be the lookup set produced by argument dependent
17868   //   lookup (defined as follows). If X contains [...] then Y is
17869   //   empty. Otherwise Y is the set of declarations found in the
17870   //   namespaces associated with the argument types as described
17871   //   below. The set of declarations found by the lookup of the name
17872   //   is the union of X and Y.
17873   //
17874   // Here, we compute Y and add its members to the overloaded
17875   // candidate set.
17876   for (auto *NS : AssociatedNamespaces) {
17877     //   When considering an associated namespace, the lookup is the
17878     //   same as the lookup performed when the associated namespace is
17879     //   used as a qualifier (3.4.3.2) except that:
17880     //
17881     //     -- Any using-directives in the associated namespace are
17882     //        ignored.
17883     //
17884     //     -- Any namespace-scope friend functions declared in
17885     //        associated classes are visible within their respective
17886     //        namespaces even if they are not visible during an ordinary
17887     //        lookup (11.4).
17888     DeclContext::lookup_result R = NS->lookup(Id.getName());
17889     for (auto *D : R) {
17890       auto *Underlying = D;
17891       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
17892         Underlying = USD->getTargetDecl();
17893 
17894       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
17895           !isa<OMPDeclareMapperDecl>(Underlying))
17896         continue;
17897 
17898       if (!SemaRef.isVisible(D)) {
17899         D = findAcceptableDecl(SemaRef, D);
17900         if (!D)
17901           continue;
17902         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
17903           Underlying = USD->getTargetDecl();
17904       }
17905       Lookups.emplace_back();
17906       Lookups.back().addDecl(Underlying);
17907     }
17908   }
17909 }
17910 
17911 static ExprResult
17912 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
17913                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
17914                          const DeclarationNameInfo &ReductionId, QualType Ty,
17915                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
17916   if (ReductionIdScopeSpec.isInvalid())
17917     return ExprError();
17918   SmallVector<UnresolvedSet<8>, 4> Lookups;
17919   if (S) {
17920     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
17921     Lookup.suppressDiagnostics();
17922     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
17923       NamedDecl *D = Lookup.getRepresentativeDecl();
17924       do {
17925         S = S->getParent();
17926       } while (S && !S->isDeclScope(D));
17927       if (S)
17928         S = S->getParent();
17929       Lookups.emplace_back();
17930       Lookups.back().append(Lookup.begin(), Lookup.end());
17931       Lookup.clear();
17932     }
17933   } else if (auto *ULE =
17934                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
17935     Lookups.push_back(UnresolvedSet<8>());
17936     Decl *PrevD = nullptr;
17937     for (NamedDecl *D : ULE->decls()) {
17938       if (D == PrevD)
17939         Lookups.push_back(UnresolvedSet<8>());
17940       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
17941         Lookups.back().addDecl(DRD);
17942       PrevD = D;
17943     }
17944   }
17945   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
17946       Ty->isInstantiationDependentType() ||
17947       Ty->containsUnexpandedParameterPack() ||
17948       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
17949         return !D->isInvalidDecl() &&
17950                (D->getType()->isDependentType() ||
17951                 D->getType()->isInstantiationDependentType() ||
17952                 D->getType()->containsUnexpandedParameterPack());
17953       })) {
17954     UnresolvedSet<8> ResSet;
17955     for (const UnresolvedSet<8> &Set : Lookups) {
17956       if (Set.empty())
17957         continue;
17958       ResSet.append(Set.begin(), Set.end());
17959       // The last item marks the end of all declarations at the specified scope.
17960       ResSet.addDecl(Set[Set.size() - 1]);
17961     }
17962     return UnresolvedLookupExpr::Create(
17963         SemaRef.Context, /*NamingClass=*/nullptr,
17964         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
17965         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
17966   }
17967   // Lookup inside the classes.
17968   // C++ [over.match.oper]p3:
17969   //   For a unary operator @ with an operand of a type whose
17970   //   cv-unqualified version is T1, and for a binary operator @ with
17971   //   a left operand of a type whose cv-unqualified version is T1 and
17972   //   a right operand of a type whose cv-unqualified version is T2,
17973   //   three sets of candidate functions, designated member
17974   //   candidates, non-member candidates and built-in candidates, are
17975   //   constructed as follows:
17976   //     -- If T1 is a complete class type or a class currently being
17977   //        defined, the set of member candidates is the result of the
17978   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
17979   //        the set of member candidates is empty.
17980   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
17981   Lookup.suppressDiagnostics();
17982   if (const auto *TyRec = Ty->getAs<RecordType>()) {
17983     // Complete the type if it can be completed.
17984     // If the type is neither complete nor being defined, bail out now.
17985     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
17986         TyRec->getDecl()->getDefinition()) {
17987       Lookup.clear();
17988       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
17989       if (Lookup.empty()) {
17990         Lookups.emplace_back();
17991         Lookups.back().append(Lookup.begin(), Lookup.end());
17992       }
17993     }
17994   }
17995   // Perform ADL.
17996   if (SemaRef.getLangOpts().CPlusPlus)
17997     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
17998   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17999           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
18000             if (!D->isInvalidDecl() &&
18001                 SemaRef.Context.hasSameType(D->getType(), Ty))
18002               return D;
18003             return nullptr;
18004           }))
18005     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
18006                                     VK_LValue, Loc);
18007   if (SemaRef.getLangOpts().CPlusPlus) {
18008     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18009             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
18010               if (!D->isInvalidDecl() &&
18011                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
18012                   !Ty.isMoreQualifiedThan(D->getType()))
18013                 return D;
18014               return nullptr;
18015             })) {
18016       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
18017                          /*DetectVirtual=*/false);
18018       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
18019         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
18020                 VD->getType().getUnqualifiedType()))) {
18021           if (SemaRef.CheckBaseClassAccess(
18022                   Loc, VD->getType(), Ty, Paths.front(),
18023                   /*DiagID=*/0) != Sema::AR_inaccessible) {
18024             SemaRef.BuildBasePathArray(Paths, BasePath);
18025             return SemaRef.BuildDeclRefExpr(
18026                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
18027           }
18028         }
18029       }
18030     }
18031   }
18032   if (ReductionIdScopeSpec.isSet()) {
18033     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
18034         << Ty << Range;
18035     return ExprError();
18036   }
18037   return ExprEmpty();
18038 }
18039 
18040 namespace {
18041 /// Data for the reduction-based clauses.
18042 struct ReductionData {
18043   /// List of original reduction items.
18044   SmallVector<Expr *, 8> Vars;
18045   /// List of private copies of the reduction items.
18046   SmallVector<Expr *, 8> Privates;
18047   /// LHS expressions for the reduction_op expressions.
18048   SmallVector<Expr *, 8> LHSs;
18049   /// RHS expressions for the reduction_op expressions.
18050   SmallVector<Expr *, 8> RHSs;
18051   /// Reduction operation expression.
18052   SmallVector<Expr *, 8> ReductionOps;
18053   /// inscan copy operation expressions.
18054   SmallVector<Expr *, 8> InscanCopyOps;
18055   /// inscan copy temp array expressions for prefix sums.
18056   SmallVector<Expr *, 8> InscanCopyArrayTemps;
18057   /// inscan copy temp array element expressions for prefix sums.
18058   SmallVector<Expr *, 8> InscanCopyArrayElems;
18059   /// Taskgroup descriptors for the corresponding reduction items in
18060   /// in_reduction clauses.
18061   SmallVector<Expr *, 8> TaskgroupDescriptors;
18062   /// List of captures for clause.
18063   SmallVector<Decl *, 4> ExprCaptures;
18064   /// List of postupdate expressions.
18065   SmallVector<Expr *, 4> ExprPostUpdates;
18066   /// Reduction modifier.
18067   unsigned RedModifier = 0;
18068   ReductionData() = delete;
18069   /// Reserves required memory for the reduction data.
18070   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
18071     Vars.reserve(Size);
18072     Privates.reserve(Size);
18073     LHSs.reserve(Size);
18074     RHSs.reserve(Size);
18075     ReductionOps.reserve(Size);
18076     if (RedModifier == OMPC_REDUCTION_inscan) {
18077       InscanCopyOps.reserve(Size);
18078       InscanCopyArrayTemps.reserve(Size);
18079       InscanCopyArrayElems.reserve(Size);
18080     }
18081     TaskgroupDescriptors.reserve(Size);
18082     ExprCaptures.reserve(Size);
18083     ExprPostUpdates.reserve(Size);
18084   }
18085   /// Stores reduction item and reduction operation only (required for dependent
18086   /// reduction item).
18087   void push(Expr *Item, Expr *ReductionOp) {
18088     Vars.emplace_back(Item);
18089     Privates.emplace_back(nullptr);
18090     LHSs.emplace_back(nullptr);
18091     RHSs.emplace_back(nullptr);
18092     ReductionOps.emplace_back(ReductionOp);
18093     TaskgroupDescriptors.emplace_back(nullptr);
18094     if (RedModifier == OMPC_REDUCTION_inscan) {
18095       InscanCopyOps.push_back(nullptr);
18096       InscanCopyArrayTemps.push_back(nullptr);
18097       InscanCopyArrayElems.push_back(nullptr);
18098     }
18099   }
18100   /// Stores reduction data.
18101   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
18102             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
18103             Expr *CopyArrayElem) {
18104     Vars.emplace_back(Item);
18105     Privates.emplace_back(Private);
18106     LHSs.emplace_back(LHS);
18107     RHSs.emplace_back(RHS);
18108     ReductionOps.emplace_back(ReductionOp);
18109     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
18110     if (RedModifier == OMPC_REDUCTION_inscan) {
18111       InscanCopyOps.push_back(CopyOp);
18112       InscanCopyArrayTemps.push_back(CopyArrayTemp);
18113       InscanCopyArrayElems.push_back(CopyArrayElem);
18114     } else {
18115       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
18116              CopyArrayElem == nullptr &&
18117              "Copy operation must be used for inscan reductions only.");
18118     }
18119   }
18120 };
18121 } // namespace
18122 
18123 static bool checkOMPArraySectionConstantForReduction(
18124     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
18125     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
18126   const Expr *Length = OASE->getLength();
18127   if (Length == nullptr) {
18128     // For array sections of the form [1:] or [:], we would need to analyze
18129     // the lower bound...
18130     if (OASE->getColonLocFirst().isValid())
18131       return false;
18132 
18133     // This is an array subscript which has implicit length 1!
18134     SingleElement = true;
18135     ArraySizes.push_back(llvm::APSInt::get(1));
18136   } else {
18137     Expr::EvalResult Result;
18138     if (!Length->EvaluateAsInt(Result, Context))
18139       return false;
18140 
18141     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
18142     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
18143     ArraySizes.push_back(ConstantLengthValue);
18144   }
18145 
18146   // Get the base of this array section and walk up from there.
18147   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
18148 
18149   // We require length = 1 for all array sections except the right-most to
18150   // guarantee that the memory region is contiguous and has no holes in it.
18151   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
18152     Length = TempOASE->getLength();
18153     if (Length == nullptr) {
18154       // For array sections of the form [1:] or [:], we would need to analyze
18155       // the lower bound...
18156       if (OASE->getColonLocFirst().isValid())
18157         return false;
18158 
18159       // This is an array subscript which has implicit length 1!
18160       ArraySizes.push_back(llvm::APSInt::get(1));
18161     } else {
18162       Expr::EvalResult Result;
18163       if (!Length->EvaluateAsInt(Result, Context))
18164         return false;
18165 
18166       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
18167       if (ConstantLengthValue.getSExtValue() != 1)
18168         return false;
18169 
18170       ArraySizes.push_back(ConstantLengthValue);
18171     }
18172     Base = TempOASE->getBase()->IgnoreParenImpCasts();
18173   }
18174 
18175   // If we have a single element, we don't need to add the implicit lengths.
18176   if (!SingleElement) {
18177     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
18178       // Has implicit length 1!
18179       ArraySizes.push_back(llvm::APSInt::get(1));
18180       Base = TempASE->getBase()->IgnoreParenImpCasts();
18181     }
18182   }
18183 
18184   // This array section can be privatized as a single value or as a constant
18185   // sized array.
18186   return true;
18187 }
18188 
18189 static BinaryOperatorKind
18190 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
18191   if (BOK == BO_Add)
18192     return BO_AddAssign;
18193   if (BOK == BO_Mul)
18194     return BO_MulAssign;
18195   if (BOK == BO_And)
18196     return BO_AndAssign;
18197   if (BOK == BO_Or)
18198     return BO_OrAssign;
18199   if (BOK == BO_Xor)
18200     return BO_XorAssign;
18201   return BOK;
18202 }
18203 
18204 static bool actOnOMPReductionKindClause(
18205     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
18206     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
18207     SourceLocation ColonLoc, SourceLocation EndLoc,
18208     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18209     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
18210   DeclarationName DN = ReductionId.getName();
18211   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
18212   BinaryOperatorKind BOK = BO_Comma;
18213 
18214   ASTContext &Context = S.Context;
18215   // OpenMP [2.14.3.6, reduction clause]
18216   // C
18217   // reduction-identifier is either an identifier or one of the following
18218   // operators: +, -, *,  &, |, ^, && and ||
18219   // C++
18220   // reduction-identifier is either an id-expression or one of the following
18221   // operators: +, -, *, &, |, ^, && and ||
18222   switch (OOK) {
18223   case OO_Plus:
18224   case OO_Minus:
18225     BOK = BO_Add;
18226     break;
18227   case OO_Star:
18228     BOK = BO_Mul;
18229     break;
18230   case OO_Amp:
18231     BOK = BO_And;
18232     break;
18233   case OO_Pipe:
18234     BOK = BO_Or;
18235     break;
18236   case OO_Caret:
18237     BOK = BO_Xor;
18238     break;
18239   case OO_AmpAmp:
18240     BOK = BO_LAnd;
18241     break;
18242   case OO_PipePipe:
18243     BOK = BO_LOr;
18244     break;
18245   case OO_New:
18246   case OO_Delete:
18247   case OO_Array_New:
18248   case OO_Array_Delete:
18249   case OO_Slash:
18250   case OO_Percent:
18251   case OO_Tilde:
18252   case OO_Exclaim:
18253   case OO_Equal:
18254   case OO_Less:
18255   case OO_Greater:
18256   case OO_LessEqual:
18257   case OO_GreaterEqual:
18258   case OO_PlusEqual:
18259   case OO_MinusEqual:
18260   case OO_StarEqual:
18261   case OO_SlashEqual:
18262   case OO_PercentEqual:
18263   case OO_CaretEqual:
18264   case OO_AmpEqual:
18265   case OO_PipeEqual:
18266   case OO_LessLess:
18267   case OO_GreaterGreater:
18268   case OO_LessLessEqual:
18269   case OO_GreaterGreaterEqual:
18270   case OO_EqualEqual:
18271   case OO_ExclaimEqual:
18272   case OO_Spaceship:
18273   case OO_PlusPlus:
18274   case OO_MinusMinus:
18275   case OO_Comma:
18276   case OO_ArrowStar:
18277   case OO_Arrow:
18278   case OO_Call:
18279   case OO_Subscript:
18280   case OO_Conditional:
18281   case OO_Coawait:
18282   case NUM_OVERLOADED_OPERATORS:
18283     llvm_unreachable("Unexpected reduction identifier");
18284   case OO_None:
18285     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
18286       if (II->isStr("max"))
18287         BOK = BO_GT;
18288       else if (II->isStr("min"))
18289         BOK = BO_LT;
18290     }
18291     break;
18292   }
18293   SourceRange ReductionIdRange;
18294   if (ReductionIdScopeSpec.isValid())
18295     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
18296   else
18297     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
18298   ReductionIdRange.setEnd(ReductionId.getEndLoc());
18299 
18300   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
18301   bool FirstIter = true;
18302   for (Expr *RefExpr : VarList) {
18303     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
18304     // OpenMP [2.1, C/C++]
18305     //  A list item is a variable or array section, subject to the restrictions
18306     //  specified in Section 2.4 on page 42 and in each of the sections
18307     // describing clauses and directives for which a list appears.
18308     // OpenMP  [2.14.3.3, Restrictions, p.1]
18309     //  A variable that is part of another variable (as an array or
18310     //  structure element) cannot appear in a private clause.
18311     if (!FirstIter && IR != ER)
18312       ++IR;
18313     FirstIter = false;
18314     SourceLocation ELoc;
18315     SourceRange ERange;
18316     Expr *SimpleRefExpr = RefExpr;
18317     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
18318                               /*AllowArraySection=*/true);
18319     if (Res.second) {
18320       // Try to find 'declare reduction' corresponding construct before using
18321       // builtin/overloaded operators.
18322       QualType Type = Context.DependentTy;
18323       CXXCastPath BasePath;
18324       ExprResult DeclareReductionRef = buildDeclareReductionRef(
18325           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
18326           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
18327       Expr *ReductionOp = nullptr;
18328       if (S.CurContext->isDependentContext() &&
18329           (DeclareReductionRef.isUnset() ||
18330            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
18331         ReductionOp = DeclareReductionRef.get();
18332       // It will be analyzed later.
18333       RD.push(RefExpr, ReductionOp);
18334     }
18335     ValueDecl *D = Res.first;
18336     if (!D)
18337       continue;
18338 
18339     Expr *TaskgroupDescriptor = nullptr;
18340     QualType Type;
18341     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
18342     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
18343     if (ASE) {
18344       Type = ASE->getType().getNonReferenceType();
18345     } else if (OASE) {
18346       QualType BaseType =
18347           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18348       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18349         Type = ATy->getElementType();
18350       else
18351         Type = BaseType->getPointeeType();
18352       Type = Type.getNonReferenceType();
18353     } else {
18354       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
18355     }
18356     auto *VD = dyn_cast<VarDecl>(D);
18357 
18358     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
18359     //  A variable that appears in a private clause must not have an incomplete
18360     //  type or a reference type.
18361     if (S.RequireCompleteType(ELoc, D->getType(),
18362                               diag::err_omp_reduction_incomplete_type))
18363       continue;
18364     // OpenMP [2.14.3.6, reduction clause, Restrictions]
18365     // A list item that appears in a reduction clause must not be
18366     // const-qualified.
18367     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
18368                                   /*AcceptIfMutable*/ false, ASE || OASE))
18369       continue;
18370 
18371     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
18372     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
18373     //  If a list-item is a reference type then it must bind to the same object
18374     //  for all threads of the team.
18375     if (!ASE && !OASE) {
18376       if (VD) {
18377         VarDecl *VDDef = VD->getDefinition();
18378         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
18379           DSARefChecker Check(Stack);
18380           if (Check.Visit(VDDef->getInit())) {
18381             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
18382                 << getOpenMPClauseName(ClauseKind) << ERange;
18383             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
18384             continue;
18385           }
18386         }
18387       }
18388 
18389       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
18390       // in a Construct]
18391       //  Variables with the predetermined data-sharing attributes may not be
18392       //  listed in data-sharing attributes clauses, except for the cases
18393       //  listed below. For these exceptions only, listing a predetermined
18394       //  variable in a data-sharing attribute clause is allowed and overrides
18395       //  the variable's predetermined data-sharing attributes.
18396       // OpenMP [2.14.3.6, Restrictions, p.3]
18397       //  Any number of reduction clauses can be specified on the directive,
18398       //  but a list item can appear only once in the reduction clauses for that
18399       //  directive.
18400       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
18401       if (DVar.CKind == OMPC_reduction) {
18402         S.Diag(ELoc, diag::err_omp_once_referenced)
18403             << getOpenMPClauseName(ClauseKind);
18404         if (DVar.RefExpr)
18405           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
18406         continue;
18407       }
18408       if (DVar.CKind != OMPC_unknown) {
18409         S.Diag(ELoc, diag::err_omp_wrong_dsa)
18410             << getOpenMPClauseName(DVar.CKind)
18411             << getOpenMPClauseName(OMPC_reduction);
18412         reportOriginalDsa(S, Stack, D, DVar);
18413         continue;
18414       }
18415 
18416       // OpenMP [2.14.3.6, Restrictions, p.1]
18417       //  A list item that appears in a reduction clause of a worksharing
18418       //  construct must be shared in the parallel regions to which any of the
18419       //  worksharing regions arising from the worksharing construct bind.
18420       if (isOpenMPWorksharingDirective(CurrDir) &&
18421           !isOpenMPParallelDirective(CurrDir) &&
18422           !isOpenMPTeamsDirective(CurrDir)) {
18423         DVar = Stack->getImplicitDSA(D, true);
18424         if (DVar.CKind != OMPC_shared) {
18425           S.Diag(ELoc, diag::err_omp_required_access)
18426               << getOpenMPClauseName(OMPC_reduction)
18427               << getOpenMPClauseName(OMPC_shared);
18428           reportOriginalDsa(S, Stack, D, DVar);
18429           continue;
18430         }
18431       }
18432     } else {
18433       // Threadprivates cannot be shared between threads, so dignose if the base
18434       // is a threadprivate variable.
18435       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
18436       if (DVar.CKind == OMPC_threadprivate) {
18437         S.Diag(ELoc, diag::err_omp_wrong_dsa)
18438             << getOpenMPClauseName(DVar.CKind)
18439             << getOpenMPClauseName(OMPC_reduction);
18440         reportOriginalDsa(S, Stack, D, DVar);
18441         continue;
18442       }
18443     }
18444 
18445     // Try to find 'declare reduction' corresponding construct before using
18446     // builtin/overloaded operators.
18447     CXXCastPath BasePath;
18448     ExprResult DeclareReductionRef = buildDeclareReductionRef(
18449         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
18450         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
18451     if (DeclareReductionRef.isInvalid())
18452       continue;
18453     if (S.CurContext->isDependentContext() &&
18454         (DeclareReductionRef.isUnset() ||
18455          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
18456       RD.push(RefExpr, DeclareReductionRef.get());
18457       continue;
18458     }
18459     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
18460       // Not allowed reduction identifier is found.
18461       S.Diag(ReductionId.getBeginLoc(),
18462              diag::err_omp_unknown_reduction_identifier)
18463           << Type << ReductionIdRange;
18464       continue;
18465     }
18466 
18467     // OpenMP [2.14.3.6, reduction clause, Restrictions]
18468     // The type of a list item that appears in a reduction clause must be valid
18469     // for the reduction-identifier. For a max or min reduction in C, the type
18470     // of the list item must be an allowed arithmetic data type: char, int,
18471     // float, double, or _Bool, possibly modified with long, short, signed, or
18472     // unsigned. For a max or min reduction in C++, the type of the list item
18473     // must be an allowed arithmetic data type: char, wchar_t, int, float,
18474     // double, or bool, possibly modified with long, short, signed, or unsigned.
18475     if (DeclareReductionRef.isUnset()) {
18476       if ((BOK == BO_GT || BOK == BO_LT) &&
18477           !(Type->isScalarType() ||
18478             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
18479         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
18480             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
18481         if (!ASE && !OASE) {
18482           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18483                                    VarDecl::DeclarationOnly;
18484           S.Diag(D->getLocation(),
18485                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18486               << D;
18487         }
18488         continue;
18489       }
18490       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
18491           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
18492         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
18493             << getOpenMPClauseName(ClauseKind);
18494         if (!ASE && !OASE) {
18495           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18496                                    VarDecl::DeclarationOnly;
18497           S.Diag(D->getLocation(),
18498                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18499               << D;
18500         }
18501         continue;
18502       }
18503     }
18504 
18505     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
18506     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
18507                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
18508     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
18509                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
18510     QualType PrivateTy = Type;
18511 
18512     // Try if we can determine constant lengths for all array sections and avoid
18513     // the VLA.
18514     bool ConstantLengthOASE = false;
18515     if (OASE) {
18516       bool SingleElement;
18517       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
18518       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
18519           Context, OASE, SingleElement, ArraySizes);
18520 
18521       // If we don't have a single element, we must emit a constant array type.
18522       if (ConstantLengthOASE && !SingleElement) {
18523         for (llvm::APSInt &Size : ArraySizes)
18524           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
18525                                                    ArrayType::Normal,
18526                                                    /*IndexTypeQuals=*/0);
18527       }
18528     }
18529 
18530     if ((OASE && !ConstantLengthOASE) ||
18531         (!OASE && !ASE &&
18532          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
18533       if (!Context.getTargetInfo().isVLASupported()) {
18534         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
18535           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
18536           S.Diag(ELoc, diag::note_vla_unsupported);
18537           continue;
18538         } else {
18539           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
18540           S.targetDiag(ELoc, diag::note_vla_unsupported);
18541         }
18542       }
18543       // For arrays/array sections only:
18544       // Create pseudo array type for private copy. The size for this array will
18545       // be generated during codegen.
18546       // For array subscripts or single variables Private Ty is the same as Type
18547       // (type of the variable or single array element).
18548       PrivateTy = Context.getVariableArrayType(
18549           Type,
18550           new (Context)
18551               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
18552           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
18553     } else if (!ASE && !OASE &&
18554                Context.getAsArrayType(D->getType().getNonReferenceType())) {
18555       PrivateTy = D->getType().getNonReferenceType();
18556     }
18557     // Private copy.
18558     VarDecl *PrivateVD =
18559         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
18560                      D->hasAttrs() ? &D->getAttrs() : nullptr,
18561                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
18562     // Add initializer for private variable.
18563     Expr *Init = nullptr;
18564     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
18565     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
18566     if (DeclareReductionRef.isUsable()) {
18567       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
18568       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
18569       if (DRD->getInitializer()) {
18570         Init = DRDRef;
18571         RHSVD->setInit(DRDRef);
18572         RHSVD->setInitStyle(VarDecl::CallInit);
18573       }
18574     } else {
18575       switch (BOK) {
18576       case BO_Add:
18577       case BO_Xor:
18578       case BO_Or:
18579       case BO_LOr:
18580         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
18581         if (Type->isScalarType() || Type->isAnyComplexType())
18582           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
18583         break;
18584       case BO_Mul:
18585       case BO_LAnd:
18586         if (Type->isScalarType() || Type->isAnyComplexType()) {
18587           // '*' and '&&' reduction ops - initializer is '1'.
18588           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
18589         }
18590         break;
18591       case BO_And: {
18592         // '&' reduction op - initializer is '~0'.
18593         QualType OrigType = Type;
18594         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
18595           Type = ComplexTy->getElementType();
18596         if (Type->isRealFloatingType()) {
18597           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
18598               Context.getFloatTypeSemantics(Type));
18599           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
18600                                          Type, ELoc);
18601         } else if (Type->isScalarType()) {
18602           uint64_t Size = Context.getTypeSize(Type);
18603           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
18604           llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
18605           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
18606         }
18607         if (Init && OrigType->isAnyComplexType()) {
18608           // Init = 0xFFFF + 0xFFFFi;
18609           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
18610           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
18611         }
18612         Type = OrigType;
18613         break;
18614       }
18615       case BO_LT:
18616       case BO_GT: {
18617         // 'min' reduction op - initializer is 'Largest representable number in
18618         // the reduction list item type'.
18619         // 'max' reduction op - initializer is 'Least representable number in
18620         // the reduction list item type'.
18621         if (Type->isIntegerType() || Type->isPointerType()) {
18622           bool IsSigned = Type->hasSignedIntegerRepresentation();
18623           uint64_t Size = Context.getTypeSize(Type);
18624           QualType IntTy =
18625               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
18626           llvm::APInt InitValue =
18627               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
18628                                         : llvm::APInt::getMinValue(Size)
18629               : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
18630                              : llvm::APInt::getMaxValue(Size);
18631           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
18632           if (Type->isPointerType()) {
18633             // Cast to pointer type.
18634             ExprResult CastExpr = S.BuildCStyleCastExpr(
18635                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
18636             if (CastExpr.isInvalid())
18637               continue;
18638             Init = CastExpr.get();
18639           }
18640         } else if (Type->isRealFloatingType()) {
18641           llvm::APFloat InitValue = llvm::APFloat::getLargest(
18642               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
18643           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
18644                                          Type, ELoc);
18645         }
18646         break;
18647       }
18648       case BO_PtrMemD:
18649       case BO_PtrMemI:
18650       case BO_MulAssign:
18651       case BO_Div:
18652       case BO_Rem:
18653       case BO_Sub:
18654       case BO_Shl:
18655       case BO_Shr:
18656       case BO_LE:
18657       case BO_GE:
18658       case BO_EQ:
18659       case BO_NE:
18660       case BO_Cmp:
18661       case BO_AndAssign:
18662       case BO_XorAssign:
18663       case BO_OrAssign:
18664       case BO_Assign:
18665       case BO_AddAssign:
18666       case BO_SubAssign:
18667       case BO_DivAssign:
18668       case BO_RemAssign:
18669       case BO_ShlAssign:
18670       case BO_ShrAssign:
18671       case BO_Comma:
18672         llvm_unreachable("Unexpected reduction operation");
18673       }
18674     }
18675     if (Init && DeclareReductionRef.isUnset()) {
18676       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
18677       // Store initializer for single element in private copy. Will be used
18678       // during codegen.
18679       PrivateVD->setInit(RHSVD->getInit());
18680       PrivateVD->setInitStyle(RHSVD->getInitStyle());
18681     } else if (!Init) {
18682       S.ActOnUninitializedDecl(RHSVD);
18683       // Store initializer for single element in private copy. Will be used
18684       // during codegen.
18685       PrivateVD->setInit(RHSVD->getInit());
18686       PrivateVD->setInitStyle(RHSVD->getInitStyle());
18687     }
18688     if (RHSVD->isInvalidDecl())
18689       continue;
18690     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
18691       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
18692           << Type << ReductionIdRange;
18693       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18694                                VarDecl::DeclarationOnly;
18695       S.Diag(D->getLocation(),
18696              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18697           << D;
18698       continue;
18699     }
18700     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
18701     ExprResult ReductionOp;
18702     if (DeclareReductionRef.isUsable()) {
18703       QualType RedTy = DeclareReductionRef.get()->getType();
18704       QualType PtrRedTy = Context.getPointerType(RedTy);
18705       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
18706       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
18707       if (!BasePath.empty()) {
18708         LHS = S.DefaultLvalueConversion(LHS.get());
18709         RHS = S.DefaultLvalueConversion(RHS.get());
18710         LHS = ImplicitCastExpr::Create(
18711             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
18712             LHS.get()->getValueKind(), FPOptionsOverride());
18713         RHS = ImplicitCastExpr::Create(
18714             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
18715             RHS.get()->getValueKind(), FPOptionsOverride());
18716       }
18717       FunctionProtoType::ExtProtoInfo EPI;
18718       QualType Params[] = {PtrRedTy, PtrRedTy};
18719       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
18720       auto *OVE = new (Context) OpaqueValueExpr(
18721           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
18722           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
18723       Expr *Args[] = {LHS.get(), RHS.get()};
18724       ReductionOp =
18725           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
18726                            S.CurFPFeatureOverrides());
18727     } else {
18728       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
18729       if (Type->isRecordType() && CombBOK != BOK) {
18730         Sema::TentativeAnalysisScope Trap(S);
18731         ReductionOp =
18732             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
18733                          CombBOK, LHSDRE, RHSDRE);
18734       }
18735       if (!ReductionOp.isUsable()) {
18736         ReductionOp =
18737             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
18738                          LHSDRE, RHSDRE);
18739         if (ReductionOp.isUsable()) {
18740           if (BOK != BO_LT && BOK != BO_GT) {
18741             ReductionOp =
18742                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
18743                              BO_Assign, LHSDRE, ReductionOp.get());
18744           } else {
18745             auto *ConditionalOp = new (Context)
18746                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
18747                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
18748             ReductionOp =
18749                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
18750                              BO_Assign, LHSDRE, ConditionalOp);
18751           }
18752         }
18753       }
18754       if (ReductionOp.isUsable())
18755         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
18756                                             /*DiscardedValue*/ false);
18757       if (!ReductionOp.isUsable())
18758         continue;
18759     }
18760 
18761     // Add copy operations for inscan reductions.
18762     // LHS = RHS;
18763     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
18764     if (ClauseKind == OMPC_reduction &&
18765         RD.RedModifier == OMPC_REDUCTION_inscan) {
18766       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
18767       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
18768                                RHS.get());
18769       if (!CopyOpRes.isUsable())
18770         continue;
18771       CopyOpRes =
18772           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
18773       if (!CopyOpRes.isUsable())
18774         continue;
18775       // For simd directive and simd-based directives in simd mode no need to
18776       // construct temp array, need just a single temp element.
18777       if (Stack->getCurrentDirective() == OMPD_simd ||
18778           (S.getLangOpts().OpenMPSimd &&
18779            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
18780         VarDecl *TempArrayVD =
18781             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
18782                          D->hasAttrs() ? &D->getAttrs() : nullptr);
18783         // Add a constructor to the temp decl.
18784         S.ActOnUninitializedDecl(TempArrayVD);
18785         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
18786       } else {
18787         // Build temp array for prefix sum.
18788         auto *Dim = new (S.Context)
18789             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
18790         QualType ArrayTy =
18791             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
18792                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
18793         VarDecl *TempArrayVD =
18794             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
18795                          D->hasAttrs() ? &D->getAttrs() : nullptr);
18796         // Add a constructor to the temp decl.
18797         S.ActOnUninitializedDecl(TempArrayVD);
18798         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
18799         TempArrayElem =
18800             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
18801         auto *Idx = new (S.Context)
18802             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
18803         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
18804                                                           ELoc, Idx, ELoc);
18805       }
18806     }
18807 
18808     // OpenMP [2.15.4.6, Restrictions, p.2]
18809     // A list item that appears in an in_reduction clause of a task construct
18810     // must appear in a task_reduction clause of a construct associated with a
18811     // taskgroup region that includes the participating task in its taskgroup
18812     // set. The construct associated with the innermost region that meets this
18813     // condition must specify the same reduction-identifier as the in_reduction
18814     // clause.
18815     if (ClauseKind == OMPC_in_reduction) {
18816       SourceRange ParentSR;
18817       BinaryOperatorKind ParentBOK;
18818       const Expr *ParentReductionOp = nullptr;
18819       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
18820       DSAStackTy::DSAVarData ParentBOKDSA =
18821           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
18822                                                   ParentBOKTD);
18823       DSAStackTy::DSAVarData ParentReductionOpDSA =
18824           Stack->getTopMostTaskgroupReductionData(
18825               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
18826       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
18827       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
18828       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
18829           (DeclareReductionRef.isUsable() && IsParentBOK) ||
18830           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
18831         bool EmitError = true;
18832         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
18833           llvm::FoldingSetNodeID RedId, ParentRedId;
18834           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
18835           DeclareReductionRef.get()->Profile(RedId, Context,
18836                                              /*Canonical=*/true);
18837           EmitError = RedId != ParentRedId;
18838         }
18839         if (EmitError) {
18840           S.Diag(ReductionId.getBeginLoc(),
18841                  diag::err_omp_reduction_identifier_mismatch)
18842               << ReductionIdRange << RefExpr->getSourceRange();
18843           S.Diag(ParentSR.getBegin(),
18844                  diag::note_omp_previous_reduction_identifier)
18845               << ParentSR
18846               << (IsParentBOK ? ParentBOKDSA.RefExpr
18847                               : ParentReductionOpDSA.RefExpr)
18848                      ->getSourceRange();
18849           continue;
18850         }
18851       }
18852       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
18853     }
18854 
18855     DeclRefExpr *Ref = nullptr;
18856     Expr *VarsExpr = RefExpr->IgnoreParens();
18857     if (!VD && !S.CurContext->isDependentContext()) {
18858       if (ASE || OASE) {
18859         TransformExprToCaptures RebuildToCapture(S, D);
18860         VarsExpr =
18861             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
18862         Ref = RebuildToCapture.getCapturedExpr();
18863       } else {
18864         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
18865       }
18866       if (!S.isOpenMPCapturedDecl(D)) {
18867         RD.ExprCaptures.emplace_back(Ref->getDecl());
18868         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
18869           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
18870           if (!RefRes.isUsable())
18871             continue;
18872           ExprResult PostUpdateRes =
18873               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
18874                            RefRes.get());
18875           if (!PostUpdateRes.isUsable())
18876             continue;
18877           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
18878               Stack->getCurrentDirective() == OMPD_taskgroup) {
18879             S.Diag(RefExpr->getExprLoc(),
18880                    diag::err_omp_reduction_non_addressable_expression)
18881                 << RefExpr->getSourceRange();
18882             continue;
18883           }
18884           RD.ExprPostUpdates.emplace_back(
18885               S.IgnoredValueConversions(PostUpdateRes.get()).get());
18886         }
18887       }
18888     }
18889     // All reduction items are still marked as reduction (to do not increase
18890     // code base size).
18891     unsigned Modifier = RD.RedModifier;
18892     // Consider task_reductions as reductions with task modifier. Required for
18893     // correct analysis of in_reduction clauses.
18894     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
18895       Modifier = OMPC_REDUCTION_task;
18896     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
18897                   ASE || OASE);
18898     if (Modifier == OMPC_REDUCTION_task &&
18899         (CurrDir == OMPD_taskgroup ||
18900          ((isOpenMPParallelDirective(CurrDir) ||
18901            isOpenMPWorksharingDirective(CurrDir)) &&
18902           !isOpenMPSimdDirective(CurrDir)))) {
18903       if (DeclareReductionRef.isUsable())
18904         Stack->addTaskgroupReductionData(D, ReductionIdRange,
18905                                          DeclareReductionRef.get());
18906       else
18907         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
18908     }
18909     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
18910             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
18911             TempArrayElem.get());
18912   }
18913   return RD.Vars.empty();
18914 }
18915 
18916 OMPClause *Sema::ActOnOpenMPReductionClause(
18917     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
18918     SourceLocation StartLoc, SourceLocation LParenLoc,
18919     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
18920     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18921     ArrayRef<Expr *> UnresolvedReductions) {
18922   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
18923     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
18924         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
18925                                    /*Last=*/OMPC_REDUCTION_unknown)
18926         << getOpenMPClauseName(OMPC_reduction);
18927     return nullptr;
18928   }
18929   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
18930   // A reduction clause with the inscan reduction-modifier may only appear on a
18931   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
18932   // construct, a parallel worksharing-loop construct or a parallel
18933   // worksharing-loop SIMD construct.
18934   if (Modifier == OMPC_REDUCTION_inscan &&
18935       (DSAStack->getCurrentDirective() != OMPD_for &&
18936        DSAStack->getCurrentDirective() != OMPD_for_simd &&
18937        DSAStack->getCurrentDirective() != OMPD_simd &&
18938        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
18939        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
18940     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
18941     return nullptr;
18942   }
18943 
18944   ReductionData RD(VarList.size(), Modifier);
18945   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
18946                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
18947                                   ReductionIdScopeSpec, ReductionId,
18948                                   UnresolvedReductions, RD))
18949     return nullptr;
18950 
18951   return OMPReductionClause::Create(
18952       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
18953       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
18954       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
18955       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
18956       buildPreInits(Context, RD.ExprCaptures),
18957       buildPostUpdate(*this, RD.ExprPostUpdates));
18958 }
18959 
18960 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
18961     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
18962     SourceLocation ColonLoc, SourceLocation EndLoc,
18963     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18964     ArrayRef<Expr *> UnresolvedReductions) {
18965   ReductionData RD(VarList.size());
18966   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
18967                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
18968                                   ReductionIdScopeSpec, ReductionId,
18969                                   UnresolvedReductions, RD))
18970     return nullptr;
18971 
18972   return OMPTaskReductionClause::Create(
18973       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
18974       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
18975       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
18976       buildPreInits(Context, RD.ExprCaptures),
18977       buildPostUpdate(*this, RD.ExprPostUpdates));
18978 }
18979 
18980 OMPClause *Sema::ActOnOpenMPInReductionClause(
18981     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
18982     SourceLocation ColonLoc, SourceLocation EndLoc,
18983     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18984     ArrayRef<Expr *> UnresolvedReductions) {
18985   ReductionData RD(VarList.size());
18986   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
18987                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
18988                                   ReductionIdScopeSpec, ReductionId,
18989                                   UnresolvedReductions, RD))
18990     return nullptr;
18991 
18992   return OMPInReductionClause::Create(
18993       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
18994       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
18995       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
18996       buildPreInits(Context, RD.ExprCaptures),
18997       buildPostUpdate(*this, RD.ExprPostUpdates));
18998 }
18999 
19000 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
19001                                      SourceLocation LinLoc) {
19002   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
19003       LinKind == OMPC_LINEAR_unknown) {
19004     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
19005     return true;
19006   }
19007   return false;
19008 }
19009 
19010 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
19011                                  OpenMPLinearClauseKind LinKind, QualType Type,
19012                                  bool IsDeclareSimd) {
19013   const auto *VD = dyn_cast_or_null<VarDecl>(D);
19014   // A variable must not have an incomplete type or a reference type.
19015   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
19016     return true;
19017   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
19018       !Type->isReferenceType()) {
19019     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
19020         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
19021     return true;
19022   }
19023   Type = Type.getNonReferenceType();
19024 
19025   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
19026   // A variable that is privatized must not have a const-qualified type
19027   // unless it is of class type with a mutable member. This restriction does
19028   // not apply to the firstprivate clause, nor to the linear clause on
19029   // declarative directives (like declare simd).
19030   if (!IsDeclareSimd &&
19031       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
19032     return true;
19033 
19034   // A list item must be of integral or pointer type.
19035   Type = Type.getUnqualifiedType().getCanonicalType();
19036   const auto *Ty = Type.getTypePtrOrNull();
19037   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
19038               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
19039     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
19040     if (D) {
19041       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
19042                                VarDecl::DeclarationOnly;
19043       Diag(D->getLocation(),
19044            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
19045           << D;
19046     }
19047     return true;
19048   }
19049   return false;
19050 }
19051 
19052 OMPClause *Sema::ActOnOpenMPLinearClause(
19053     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
19054     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
19055     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
19056   SmallVector<Expr *, 8> Vars;
19057   SmallVector<Expr *, 8> Privates;
19058   SmallVector<Expr *, 8> Inits;
19059   SmallVector<Decl *, 4> ExprCaptures;
19060   SmallVector<Expr *, 4> ExprPostUpdates;
19061   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
19062     LinKind = OMPC_LINEAR_val;
19063   for (Expr *RefExpr : VarList) {
19064     assert(RefExpr && "NULL expr in OpenMP linear clause.");
19065     SourceLocation ELoc;
19066     SourceRange ERange;
19067     Expr *SimpleRefExpr = RefExpr;
19068     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19069     if (Res.second) {
19070       // It will be analyzed later.
19071       Vars.push_back(RefExpr);
19072       Privates.push_back(nullptr);
19073       Inits.push_back(nullptr);
19074     }
19075     ValueDecl *D = Res.first;
19076     if (!D)
19077       continue;
19078 
19079     QualType Type = D->getType();
19080     auto *VD = dyn_cast<VarDecl>(D);
19081 
19082     // OpenMP [2.14.3.7, linear clause]
19083     //  A list-item cannot appear in more than one linear clause.
19084     //  A list-item that appears in a linear clause cannot appear in any
19085     //  other data-sharing attribute clause.
19086     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
19087     if (DVar.RefExpr) {
19088       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
19089                                           << getOpenMPClauseName(OMPC_linear);
19090       reportOriginalDsa(*this, DSAStack, D, DVar);
19091       continue;
19092     }
19093 
19094     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
19095       continue;
19096     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
19097 
19098     // Build private copy of original var.
19099     VarDecl *Private =
19100         buildVarDecl(*this, ELoc, Type, D->getName(),
19101                      D->hasAttrs() ? &D->getAttrs() : nullptr,
19102                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
19103     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
19104     // Build var to save initial value.
19105     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
19106     Expr *InitExpr;
19107     DeclRefExpr *Ref = nullptr;
19108     if (!VD && !CurContext->isDependentContext()) {
19109       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
19110       if (!isOpenMPCapturedDecl(D)) {
19111         ExprCaptures.push_back(Ref->getDecl());
19112         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
19113           ExprResult RefRes = DefaultLvalueConversion(Ref);
19114           if (!RefRes.isUsable())
19115             continue;
19116           ExprResult PostUpdateRes =
19117               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
19118                          SimpleRefExpr, RefRes.get());
19119           if (!PostUpdateRes.isUsable())
19120             continue;
19121           ExprPostUpdates.push_back(
19122               IgnoredValueConversions(PostUpdateRes.get()).get());
19123         }
19124       }
19125     }
19126     if (LinKind == OMPC_LINEAR_uval)
19127       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
19128     else
19129       InitExpr = VD ? SimpleRefExpr : Ref;
19130     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
19131                          /*DirectInit=*/false);
19132     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
19133 
19134     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
19135     Vars.push_back((VD || CurContext->isDependentContext())
19136                        ? RefExpr->IgnoreParens()
19137                        : Ref);
19138     Privates.push_back(PrivateRef);
19139     Inits.push_back(InitRef);
19140   }
19141 
19142   if (Vars.empty())
19143     return nullptr;
19144 
19145   Expr *StepExpr = Step;
19146   Expr *CalcStepExpr = nullptr;
19147   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
19148       !Step->isInstantiationDependent() &&
19149       !Step->containsUnexpandedParameterPack()) {
19150     SourceLocation StepLoc = Step->getBeginLoc();
19151     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
19152     if (Val.isInvalid())
19153       return nullptr;
19154     StepExpr = Val.get();
19155 
19156     // Build var to save the step value.
19157     VarDecl *SaveVar =
19158         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
19159     ExprResult SaveRef =
19160         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
19161     ExprResult CalcStep =
19162         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
19163     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
19164 
19165     // Warn about zero linear step (it would be probably better specified as
19166     // making corresponding variables 'const').
19167     if (Optional<llvm::APSInt> Result =
19168             StepExpr->getIntegerConstantExpr(Context)) {
19169       if (!Result->isNegative() && !Result->isStrictlyPositive())
19170         Diag(StepLoc, diag::warn_omp_linear_step_zero)
19171             << Vars[0] << (Vars.size() > 1);
19172     } else if (CalcStep.isUsable()) {
19173       // Calculate the step beforehand instead of doing this on each iteration.
19174       // (This is not used if the number of iterations may be kfold-ed).
19175       CalcStepExpr = CalcStep.get();
19176     }
19177   }
19178 
19179   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
19180                                  ColonLoc, EndLoc, Vars, Privates, Inits,
19181                                  StepExpr, CalcStepExpr,
19182                                  buildPreInits(Context, ExprCaptures),
19183                                  buildPostUpdate(*this, ExprPostUpdates));
19184 }
19185 
19186 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
19187                                      Expr *NumIterations, Sema &SemaRef,
19188                                      Scope *S, DSAStackTy *Stack) {
19189   // Walk the vars and build update/final expressions for the CodeGen.
19190   SmallVector<Expr *, 8> Updates;
19191   SmallVector<Expr *, 8> Finals;
19192   SmallVector<Expr *, 8> UsedExprs;
19193   Expr *Step = Clause.getStep();
19194   Expr *CalcStep = Clause.getCalcStep();
19195   // OpenMP [2.14.3.7, linear clause]
19196   // If linear-step is not specified it is assumed to be 1.
19197   if (!Step)
19198     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
19199   else if (CalcStep)
19200     Step = cast<BinaryOperator>(CalcStep)->getLHS();
19201   bool HasErrors = false;
19202   auto CurInit = Clause.inits().begin();
19203   auto CurPrivate = Clause.privates().begin();
19204   OpenMPLinearClauseKind LinKind = Clause.getModifier();
19205   for (Expr *RefExpr : Clause.varlists()) {
19206     SourceLocation ELoc;
19207     SourceRange ERange;
19208     Expr *SimpleRefExpr = RefExpr;
19209     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
19210     ValueDecl *D = Res.first;
19211     if (Res.second || !D) {
19212       Updates.push_back(nullptr);
19213       Finals.push_back(nullptr);
19214       HasErrors = true;
19215       continue;
19216     }
19217     auto &&Info = Stack->isLoopControlVariable(D);
19218     // OpenMP [2.15.11, distribute simd Construct]
19219     // A list item may not appear in a linear clause, unless it is the loop
19220     // iteration variable.
19221     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
19222         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
19223       SemaRef.Diag(ELoc,
19224                    diag::err_omp_linear_distribute_var_non_loop_iteration);
19225       Updates.push_back(nullptr);
19226       Finals.push_back(nullptr);
19227       HasErrors = true;
19228       continue;
19229     }
19230     Expr *InitExpr = *CurInit;
19231 
19232     // Build privatized reference to the current linear var.
19233     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
19234     Expr *CapturedRef;
19235     if (LinKind == OMPC_LINEAR_uval)
19236       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
19237     else
19238       CapturedRef =
19239           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
19240                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
19241                            /*RefersToCapture=*/true);
19242 
19243     // Build update: Var = InitExpr + IV * Step
19244     ExprResult Update;
19245     if (!Info.first)
19246       Update = buildCounterUpdate(
19247           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
19248           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
19249     else
19250       Update = *CurPrivate;
19251     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
19252                                          /*DiscardedValue*/ false);
19253 
19254     // Build final: Var = PrivCopy;
19255     ExprResult Final;
19256     if (!Info.first)
19257       Final = SemaRef.BuildBinOp(
19258           S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
19259           SemaRef.DefaultLvalueConversion(*CurPrivate).get());
19260     else
19261       Final = *CurPrivate;
19262     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
19263                                         /*DiscardedValue*/ false);
19264 
19265     if (!Update.isUsable() || !Final.isUsable()) {
19266       Updates.push_back(nullptr);
19267       Finals.push_back(nullptr);
19268       UsedExprs.push_back(nullptr);
19269       HasErrors = true;
19270     } else {
19271       Updates.push_back(Update.get());
19272       Finals.push_back(Final.get());
19273       if (!Info.first)
19274         UsedExprs.push_back(SimpleRefExpr);
19275     }
19276     ++CurInit;
19277     ++CurPrivate;
19278   }
19279   if (Expr *S = Clause.getStep())
19280     UsedExprs.push_back(S);
19281   // Fill the remaining part with the nullptr.
19282   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
19283   Clause.setUpdates(Updates);
19284   Clause.setFinals(Finals);
19285   Clause.setUsedExprs(UsedExprs);
19286   return HasErrors;
19287 }
19288 
19289 OMPClause *Sema::ActOnOpenMPAlignedClause(
19290     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
19291     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
19292   SmallVector<Expr *, 8> Vars;
19293   for (Expr *RefExpr : VarList) {
19294     assert(RefExpr && "NULL expr in OpenMP linear clause.");
19295     SourceLocation ELoc;
19296     SourceRange ERange;
19297     Expr *SimpleRefExpr = RefExpr;
19298     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19299     if (Res.second) {
19300       // It will be analyzed later.
19301       Vars.push_back(RefExpr);
19302     }
19303     ValueDecl *D = Res.first;
19304     if (!D)
19305       continue;
19306 
19307     QualType QType = D->getType();
19308     auto *VD = dyn_cast<VarDecl>(D);
19309 
19310     // OpenMP  [2.8.1, simd construct, Restrictions]
19311     // The type of list items appearing in the aligned clause must be
19312     // array, pointer, reference to array, or reference to pointer.
19313     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
19314     const Type *Ty = QType.getTypePtrOrNull();
19315     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
19316       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
19317           << QType << getLangOpts().CPlusPlus << ERange;
19318       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
19319                                VarDecl::DeclarationOnly;
19320       Diag(D->getLocation(),
19321            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
19322           << D;
19323       continue;
19324     }
19325 
19326     // OpenMP  [2.8.1, simd construct, Restrictions]
19327     // A list-item cannot appear in more than one aligned clause.
19328     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
19329       Diag(ELoc, diag::err_omp_used_in_clause_twice)
19330           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
19331       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
19332           << getOpenMPClauseName(OMPC_aligned);
19333       continue;
19334     }
19335 
19336     DeclRefExpr *Ref = nullptr;
19337     if (!VD && isOpenMPCapturedDecl(D))
19338       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
19339     Vars.push_back(DefaultFunctionArrayConversion(
19340                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
19341                        .get());
19342   }
19343 
19344   // OpenMP [2.8.1, simd construct, Description]
19345   // The parameter of the aligned clause, alignment, must be a constant
19346   // positive integer expression.
19347   // If no optional parameter is specified, implementation-defined default
19348   // alignments for SIMD instructions on the target platforms are assumed.
19349   if (Alignment != nullptr) {
19350     ExprResult AlignResult =
19351         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
19352     if (AlignResult.isInvalid())
19353       return nullptr;
19354     Alignment = AlignResult.get();
19355   }
19356   if (Vars.empty())
19357     return nullptr;
19358 
19359   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
19360                                   EndLoc, Vars, Alignment);
19361 }
19362 
19363 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
19364                                          SourceLocation StartLoc,
19365                                          SourceLocation LParenLoc,
19366                                          SourceLocation EndLoc) {
19367   SmallVector<Expr *, 8> Vars;
19368   SmallVector<Expr *, 8> SrcExprs;
19369   SmallVector<Expr *, 8> DstExprs;
19370   SmallVector<Expr *, 8> AssignmentOps;
19371   for (Expr *RefExpr : VarList) {
19372     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
19373     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
19374       // It will be analyzed later.
19375       Vars.push_back(RefExpr);
19376       SrcExprs.push_back(nullptr);
19377       DstExprs.push_back(nullptr);
19378       AssignmentOps.push_back(nullptr);
19379       continue;
19380     }
19381 
19382     SourceLocation ELoc = RefExpr->getExprLoc();
19383     // OpenMP [2.1, C/C++]
19384     //  A list item is a variable name.
19385     // OpenMP  [2.14.4.1, Restrictions, p.1]
19386     //  A list item that appears in a copyin clause must be threadprivate.
19387     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
19388     if (!DE || !isa<VarDecl>(DE->getDecl())) {
19389       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
19390           << 0 << RefExpr->getSourceRange();
19391       continue;
19392     }
19393 
19394     Decl *D = DE->getDecl();
19395     auto *VD = cast<VarDecl>(D);
19396 
19397     QualType Type = VD->getType();
19398     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
19399       // It will be analyzed later.
19400       Vars.push_back(DE);
19401       SrcExprs.push_back(nullptr);
19402       DstExprs.push_back(nullptr);
19403       AssignmentOps.push_back(nullptr);
19404       continue;
19405     }
19406 
19407     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
19408     //  A list item that appears in a copyin clause must be threadprivate.
19409     if (!DSAStack->isThreadPrivate(VD)) {
19410       Diag(ELoc, diag::err_omp_required_access)
19411           << getOpenMPClauseName(OMPC_copyin)
19412           << getOpenMPDirectiveName(OMPD_threadprivate);
19413       continue;
19414     }
19415 
19416     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
19417     //  A variable of class type (or array thereof) that appears in a
19418     //  copyin clause requires an accessible, unambiguous copy assignment
19419     //  operator for the class type.
19420     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
19421     VarDecl *SrcVD =
19422         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
19423                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
19424     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
19425         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
19426     VarDecl *DstVD =
19427         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
19428                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
19429     DeclRefExpr *PseudoDstExpr =
19430         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
19431     // For arrays generate assignment operation for single element and replace
19432     // it by the original array element in CodeGen.
19433     ExprResult AssignmentOp =
19434         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
19435                    PseudoSrcExpr);
19436     if (AssignmentOp.isInvalid())
19437       continue;
19438     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
19439                                        /*DiscardedValue*/ false);
19440     if (AssignmentOp.isInvalid())
19441       continue;
19442 
19443     DSAStack->addDSA(VD, DE, OMPC_copyin);
19444     Vars.push_back(DE);
19445     SrcExprs.push_back(PseudoSrcExpr);
19446     DstExprs.push_back(PseudoDstExpr);
19447     AssignmentOps.push_back(AssignmentOp.get());
19448   }
19449 
19450   if (Vars.empty())
19451     return nullptr;
19452 
19453   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
19454                                  SrcExprs, DstExprs, AssignmentOps);
19455 }
19456 
19457 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
19458                                               SourceLocation StartLoc,
19459                                               SourceLocation LParenLoc,
19460                                               SourceLocation EndLoc) {
19461   SmallVector<Expr *, 8> Vars;
19462   SmallVector<Expr *, 8> SrcExprs;
19463   SmallVector<Expr *, 8> DstExprs;
19464   SmallVector<Expr *, 8> AssignmentOps;
19465   for (Expr *RefExpr : VarList) {
19466     assert(RefExpr && "NULL expr in OpenMP linear clause.");
19467     SourceLocation ELoc;
19468     SourceRange ERange;
19469     Expr *SimpleRefExpr = RefExpr;
19470     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19471     if (Res.second) {
19472       // It will be analyzed later.
19473       Vars.push_back(RefExpr);
19474       SrcExprs.push_back(nullptr);
19475       DstExprs.push_back(nullptr);
19476       AssignmentOps.push_back(nullptr);
19477     }
19478     ValueDecl *D = Res.first;
19479     if (!D)
19480       continue;
19481 
19482     QualType Type = D->getType();
19483     auto *VD = dyn_cast<VarDecl>(D);
19484 
19485     // OpenMP [2.14.4.2, Restrictions, p.2]
19486     //  A list item that appears in a copyprivate clause may not appear in a
19487     //  private or firstprivate clause on the single construct.
19488     if (!VD || !DSAStack->isThreadPrivate(VD)) {
19489       DSAStackTy::DSAVarData DVar =
19490           DSAStack->getTopDSA(D, /*FromParent=*/false);
19491       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
19492           DVar.RefExpr) {
19493         Diag(ELoc, diag::err_omp_wrong_dsa)
19494             << getOpenMPClauseName(DVar.CKind)
19495             << getOpenMPClauseName(OMPC_copyprivate);
19496         reportOriginalDsa(*this, DSAStack, D, DVar);
19497         continue;
19498       }
19499 
19500       // OpenMP [2.11.4.2, Restrictions, p.1]
19501       //  All list items that appear in a copyprivate clause must be either
19502       //  threadprivate or private in the enclosing context.
19503       if (DVar.CKind == OMPC_unknown) {
19504         DVar = DSAStack->getImplicitDSA(D, false);
19505         if (DVar.CKind == OMPC_shared) {
19506           Diag(ELoc, diag::err_omp_required_access)
19507               << getOpenMPClauseName(OMPC_copyprivate)
19508               << "threadprivate or private in the enclosing context";
19509           reportOriginalDsa(*this, DSAStack, D, DVar);
19510           continue;
19511         }
19512       }
19513     }
19514 
19515     // Variably modified types are not supported.
19516     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
19517       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
19518           << getOpenMPClauseName(OMPC_copyprivate) << Type
19519           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
19520       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
19521                                VarDecl::DeclarationOnly;
19522       Diag(D->getLocation(),
19523            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
19524           << D;
19525       continue;
19526     }
19527 
19528     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
19529     //  A variable of class type (or array thereof) that appears in a
19530     //  copyin clause requires an accessible, unambiguous copy assignment
19531     //  operator for the class type.
19532     Type = Context.getBaseElementType(Type.getNonReferenceType())
19533                .getUnqualifiedType();
19534     VarDecl *SrcVD =
19535         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
19536                      D->hasAttrs() ? &D->getAttrs() : nullptr);
19537     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
19538     VarDecl *DstVD =
19539         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
19540                      D->hasAttrs() ? &D->getAttrs() : nullptr);
19541     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
19542     ExprResult AssignmentOp = BuildBinOp(
19543         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
19544     if (AssignmentOp.isInvalid())
19545       continue;
19546     AssignmentOp =
19547         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
19548     if (AssignmentOp.isInvalid())
19549       continue;
19550 
19551     // No need to mark vars as copyprivate, they are already threadprivate or
19552     // implicitly private.
19553     assert(VD || isOpenMPCapturedDecl(D));
19554     Vars.push_back(
19555         VD ? RefExpr->IgnoreParens()
19556            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
19557     SrcExprs.push_back(PseudoSrcExpr);
19558     DstExprs.push_back(PseudoDstExpr);
19559     AssignmentOps.push_back(AssignmentOp.get());
19560   }
19561 
19562   if (Vars.empty())
19563     return nullptr;
19564 
19565   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19566                                       Vars, SrcExprs, DstExprs, AssignmentOps);
19567 }
19568 
19569 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
19570                                         SourceLocation StartLoc,
19571                                         SourceLocation LParenLoc,
19572                                         SourceLocation EndLoc) {
19573   if (VarList.empty())
19574     return nullptr;
19575 
19576   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
19577 }
19578 
19579 /// Tries to find omp_depend_t. type.
19580 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
19581                            bool Diagnose = true) {
19582   QualType OMPDependT = Stack->getOMPDependT();
19583   if (!OMPDependT.isNull())
19584     return true;
19585   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
19586   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
19587   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19588     if (Diagnose)
19589       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
19590     return false;
19591   }
19592   Stack->setOMPDependT(PT.get());
19593   return true;
19594 }
19595 
19596 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
19597                                          SourceLocation LParenLoc,
19598                                          SourceLocation EndLoc) {
19599   if (!Depobj)
19600     return nullptr;
19601 
19602   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
19603 
19604   // OpenMP 5.0, 2.17.10.1 depobj Construct
19605   // depobj is an lvalue expression of type omp_depend_t.
19606   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
19607       !Depobj->isInstantiationDependent() &&
19608       !Depobj->containsUnexpandedParameterPack() &&
19609       (OMPDependTFound &&
19610        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
19611                                    /*CompareUnqualified=*/true))) {
19612     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
19613         << 0 << Depobj->getType() << Depobj->getSourceRange();
19614   }
19615 
19616   if (!Depobj->isLValue()) {
19617     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
19618         << 1 << Depobj->getSourceRange();
19619   }
19620 
19621   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
19622 }
19623 
19624 OMPClause *
19625 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
19626                               SourceLocation DepLoc, SourceLocation ColonLoc,
19627                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
19628                               SourceLocation LParenLoc, SourceLocation EndLoc) {
19629   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
19630       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
19631     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
19632         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
19633     return nullptr;
19634   }
19635   if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
19636       DepKind == OMPC_DEPEND_mutexinoutset) {
19637     Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
19638     return nullptr;
19639   }
19640   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
19641        DSAStack->getCurrentDirective() == OMPD_depobj) &&
19642       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
19643        DepKind == OMPC_DEPEND_sink ||
19644        ((LangOpts.OpenMP < 50 ||
19645          DSAStack->getCurrentDirective() == OMPD_depobj) &&
19646         DepKind == OMPC_DEPEND_depobj))) {
19647     SmallVector<unsigned, 3> Except;
19648     Except.push_back(OMPC_DEPEND_source);
19649     Except.push_back(OMPC_DEPEND_sink);
19650     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
19651       Except.push_back(OMPC_DEPEND_depobj);
19652     if (LangOpts.OpenMP < 51)
19653       Except.push_back(OMPC_DEPEND_inoutset);
19654     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
19655                                ? "depend modifier(iterator) or "
19656                                : "";
19657     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
19658         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
19659                                               /*Last=*/OMPC_DEPEND_unknown,
19660                                               Except)
19661         << getOpenMPClauseName(OMPC_depend);
19662     return nullptr;
19663   }
19664   if (DepModifier &&
19665       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
19666     Diag(DepModifier->getExprLoc(),
19667          diag::err_omp_depend_sink_source_with_modifier);
19668     return nullptr;
19669   }
19670   if (DepModifier &&
19671       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
19672     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
19673 
19674   SmallVector<Expr *, 8> Vars;
19675   DSAStackTy::OperatorOffsetTy OpsOffs;
19676   llvm::APSInt DepCounter(/*BitWidth=*/32);
19677   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
19678   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
19679     if (const Expr *OrderedCountExpr =
19680             DSAStack->getParentOrderedRegionParam().first) {
19681       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
19682       TotalDepCount.setIsUnsigned(/*Val=*/true);
19683     }
19684   }
19685   for (Expr *RefExpr : VarList) {
19686     assert(RefExpr && "NULL expr in OpenMP shared clause.");
19687     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
19688       // It will be analyzed later.
19689       Vars.push_back(RefExpr);
19690       continue;
19691     }
19692 
19693     SourceLocation ELoc = RefExpr->getExprLoc();
19694     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
19695     if (DepKind == OMPC_DEPEND_sink) {
19696       if (DSAStack->getParentOrderedRegionParam().first &&
19697           DepCounter >= TotalDepCount) {
19698         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
19699         continue;
19700       }
19701       ++DepCounter;
19702       // OpenMP  [2.13.9, Summary]
19703       // depend(dependence-type : vec), where dependence-type is:
19704       // 'sink' and where vec is the iteration vector, which has the form:
19705       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
19706       // where n is the value specified by the ordered clause in the loop
19707       // directive, xi denotes the loop iteration variable of the i-th nested
19708       // loop associated with the loop directive, and di is a constant
19709       // non-negative integer.
19710       if (CurContext->isDependentContext()) {
19711         // It will be analyzed later.
19712         Vars.push_back(RefExpr);
19713         continue;
19714       }
19715       SimpleExpr = SimpleExpr->IgnoreImplicit();
19716       OverloadedOperatorKind OOK = OO_None;
19717       SourceLocation OOLoc;
19718       Expr *LHS = SimpleExpr;
19719       Expr *RHS = nullptr;
19720       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
19721         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
19722         OOLoc = BO->getOperatorLoc();
19723         LHS = BO->getLHS()->IgnoreParenImpCasts();
19724         RHS = BO->getRHS()->IgnoreParenImpCasts();
19725       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
19726         OOK = OCE->getOperator();
19727         OOLoc = OCE->getOperatorLoc();
19728         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
19729         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
19730       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
19731         OOK = MCE->getMethodDecl()
19732                   ->getNameInfo()
19733                   .getName()
19734                   .getCXXOverloadedOperator();
19735         OOLoc = MCE->getCallee()->getExprLoc();
19736         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
19737         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
19738       }
19739       SourceLocation ELoc;
19740       SourceRange ERange;
19741       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
19742       if (Res.second) {
19743         // It will be analyzed later.
19744         Vars.push_back(RefExpr);
19745       }
19746       ValueDecl *D = Res.first;
19747       if (!D)
19748         continue;
19749 
19750       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
19751         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
19752         continue;
19753       }
19754       if (RHS) {
19755         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
19756             RHS, OMPC_depend, /*StrictlyPositive=*/false);
19757         if (RHSRes.isInvalid())
19758           continue;
19759       }
19760       if (!CurContext->isDependentContext() &&
19761           DSAStack->getParentOrderedRegionParam().first &&
19762           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
19763         const ValueDecl *VD =
19764             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
19765         if (VD)
19766           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
19767               << 1 << VD;
19768         else
19769           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
19770         continue;
19771       }
19772       OpsOffs.emplace_back(RHS, OOK);
19773     } else {
19774       bool OMPDependTFound = LangOpts.OpenMP >= 50;
19775       if (OMPDependTFound)
19776         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
19777                                          DepKind == OMPC_DEPEND_depobj);
19778       if (DepKind == OMPC_DEPEND_depobj) {
19779         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
19780         // List items used in depend clauses with the depobj dependence type
19781         // must be expressions of the omp_depend_t type.
19782         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
19783             !RefExpr->isInstantiationDependent() &&
19784             !RefExpr->containsUnexpandedParameterPack() &&
19785             (OMPDependTFound &&
19786              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
19787                                              RefExpr->getType()))) {
19788           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
19789               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
19790           continue;
19791         }
19792         if (!RefExpr->isLValue()) {
19793           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
19794               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
19795           continue;
19796         }
19797       } else {
19798         // OpenMP 5.0 [2.17.11, Restrictions]
19799         // List items used in depend clauses cannot be zero-length array
19800         // sections.
19801         QualType ExprTy = RefExpr->getType().getNonReferenceType();
19802         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
19803         if (OASE) {
19804           QualType BaseType =
19805               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19806           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19807             ExprTy = ATy->getElementType();
19808           else
19809             ExprTy = BaseType->getPointeeType();
19810           ExprTy = ExprTy.getNonReferenceType();
19811           const Expr *Length = OASE->getLength();
19812           Expr::EvalResult Result;
19813           if (Length && !Length->isValueDependent() &&
19814               Length->EvaluateAsInt(Result, Context) &&
19815               Result.Val.getInt().isZero()) {
19816             Diag(ELoc,
19817                  diag::err_omp_depend_zero_length_array_section_not_allowed)
19818                 << SimpleExpr->getSourceRange();
19819             continue;
19820           }
19821         }
19822 
19823         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
19824         // List items used in depend clauses with the in, out, inout,
19825         // inoutset, or mutexinoutset dependence types cannot be
19826         // expressions of the omp_depend_t type.
19827         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
19828             !RefExpr->isInstantiationDependent() &&
19829             !RefExpr->containsUnexpandedParameterPack() &&
19830             (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
19831              (OMPDependTFound &&
19832               DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
19833           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19834               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19835               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19836           continue;
19837         }
19838 
19839         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
19840         if (ASE && !ASE->getBase()->isTypeDependent() &&
19841             !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
19842             !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
19843           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19844               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19845               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19846           continue;
19847         }
19848 
19849         ExprResult Res;
19850         {
19851           Sema::TentativeAnalysisScope Trap(*this);
19852           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
19853                                      RefExpr->IgnoreParenImpCasts());
19854         }
19855         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
19856             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
19857           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19858               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19859               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19860           continue;
19861         }
19862       }
19863     }
19864     Vars.push_back(RefExpr->IgnoreParenImpCasts());
19865   }
19866 
19867   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
19868       TotalDepCount > VarList.size() &&
19869       DSAStack->getParentOrderedRegionParam().first &&
19870       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
19871     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
19872         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
19873   }
19874   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
19875       Vars.empty())
19876     return nullptr;
19877 
19878   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19879                                     DepModifier, DepKind, DepLoc, ColonLoc,
19880                                     Vars, TotalDepCount.getZExtValue());
19881   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
19882       DSAStack->isParentOrderedRegion())
19883     DSAStack->addDoacrossDependClause(C, OpsOffs);
19884   return C;
19885 }
19886 
19887 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
19888                                          Expr *Device, SourceLocation StartLoc,
19889                                          SourceLocation LParenLoc,
19890                                          SourceLocation ModifierLoc,
19891                                          SourceLocation EndLoc) {
19892   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
19893          "Unexpected device modifier in OpenMP < 50.");
19894 
19895   bool ErrorFound = false;
19896   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
19897     std::string Values =
19898         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
19899     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
19900         << Values << getOpenMPClauseName(OMPC_device);
19901     ErrorFound = true;
19902   }
19903 
19904   Expr *ValExpr = Device;
19905   Stmt *HelperValStmt = nullptr;
19906 
19907   // OpenMP [2.9.1, Restrictions]
19908   // The device expression must evaluate to a non-negative integer value.
19909   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
19910                                           /*StrictlyPositive=*/false) ||
19911                ErrorFound;
19912   if (ErrorFound)
19913     return nullptr;
19914 
19915   // OpenMP 5.0 [2.12.5, Restrictions]
19916   // In case of ancestor device-modifier, a requires directive with
19917   // the reverse_offload clause must be specified.
19918   if (Modifier == OMPC_DEVICE_ancestor) {
19919     if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) {
19920       targetDiag(
19921           StartLoc,
19922           diag::err_omp_device_ancestor_without_requires_reverse_offload);
19923       ErrorFound = true;
19924     }
19925   }
19926 
19927   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19928   OpenMPDirectiveKind CaptureRegion =
19929       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
19930   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19931     ValExpr = MakeFullExpr(ValExpr).get();
19932     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19933     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19934     HelperValStmt = buildPreInits(Context, Captures);
19935   }
19936 
19937   return new (Context)
19938       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
19939                       LParenLoc, ModifierLoc, EndLoc);
19940 }
19941 
19942 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
19943                               DSAStackTy *Stack, QualType QTy,
19944                               bool FullCheck = true) {
19945   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
19946     return false;
19947   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
19948       !QTy.isTriviallyCopyableType(SemaRef.Context))
19949     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
19950   return true;
19951 }
19952 
19953 /// Return true if it can be proven that the provided array expression
19954 /// (array section or array subscript) does NOT specify the whole size of the
19955 /// array whose base type is \a BaseQTy.
19956 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
19957                                                         const Expr *E,
19958                                                         QualType BaseQTy) {
19959   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
19960 
19961   // If this is an array subscript, it refers to the whole size if the size of
19962   // the dimension is constant and equals 1. Also, an array section assumes the
19963   // format of an array subscript if no colon is used.
19964   if (isa<ArraySubscriptExpr>(E) ||
19965       (OASE && OASE->getColonLocFirst().isInvalid())) {
19966     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
19967       return ATy->getSize().getSExtValue() != 1;
19968     // Size can't be evaluated statically.
19969     return false;
19970   }
19971 
19972   assert(OASE && "Expecting array section if not an array subscript.");
19973   const Expr *LowerBound = OASE->getLowerBound();
19974   const Expr *Length = OASE->getLength();
19975 
19976   // If there is a lower bound that does not evaluates to zero, we are not
19977   // covering the whole dimension.
19978   if (LowerBound) {
19979     Expr::EvalResult Result;
19980     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
19981       return false; // Can't get the integer value as a constant.
19982 
19983     llvm::APSInt ConstLowerBound = Result.Val.getInt();
19984     if (ConstLowerBound.getSExtValue())
19985       return true;
19986   }
19987 
19988   // If we don't have a length we covering the whole dimension.
19989   if (!Length)
19990     return false;
19991 
19992   // If the base is a pointer, we don't have a way to get the size of the
19993   // pointee.
19994   if (BaseQTy->isPointerType())
19995     return false;
19996 
19997   // We can only check if the length is the same as the size of the dimension
19998   // if we have a constant array.
19999   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
20000   if (!CATy)
20001     return false;
20002 
20003   Expr::EvalResult Result;
20004   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
20005     return false; // Can't get the integer value as a constant.
20006 
20007   llvm::APSInt ConstLength = Result.Val.getInt();
20008   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
20009 }
20010 
20011 // Return true if it can be proven that the provided array expression (array
20012 // section or array subscript) does NOT specify a single element of the array
20013 // whose base type is \a BaseQTy.
20014 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
20015                                                         const Expr *E,
20016                                                         QualType BaseQTy) {
20017   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
20018 
20019   // An array subscript always refer to a single element. Also, an array section
20020   // assumes the format of an array subscript if no colon is used.
20021   if (isa<ArraySubscriptExpr>(E) ||
20022       (OASE && OASE->getColonLocFirst().isInvalid()))
20023     return false;
20024 
20025   assert(OASE && "Expecting array section if not an array subscript.");
20026   const Expr *Length = OASE->getLength();
20027 
20028   // If we don't have a length we have to check if the array has unitary size
20029   // for this dimension. Also, we should always expect a length if the base type
20030   // is pointer.
20031   if (!Length) {
20032     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
20033       return ATy->getSize().getSExtValue() != 1;
20034     // We cannot assume anything.
20035     return false;
20036   }
20037 
20038   // Check if the length evaluates to 1.
20039   Expr::EvalResult Result;
20040   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
20041     return false; // Can't get the integer value as a constant.
20042 
20043   llvm::APSInt ConstLength = Result.Val.getInt();
20044   return ConstLength.getSExtValue() != 1;
20045 }
20046 
20047 // The base of elements of list in a map clause have to be either:
20048 //  - a reference to variable or field.
20049 //  - a member expression.
20050 //  - an array expression.
20051 //
20052 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
20053 // reference to 'r'.
20054 //
20055 // If we have:
20056 //
20057 // struct SS {
20058 //   Bla S;
20059 //   foo() {
20060 //     #pragma omp target map (S.Arr[:12]);
20061 //   }
20062 // }
20063 //
20064 // We want to retrieve the member expression 'this->S';
20065 
20066 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
20067 //  If a list item is an array section, it must specify contiguous storage.
20068 //
20069 // For this restriction it is sufficient that we make sure only references
20070 // to variables or fields and array expressions, and that no array sections
20071 // exist except in the rightmost expression (unless they cover the whole
20072 // dimension of the array). E.g. these would be invalid:
20073 //
20074 //   r.ArrS[3:5].Arr[6:7]
20075 //
20076 //   r.ArrS[3:5].x
20077 //
20078 // but these would be valid:
20079 //   r.ArrS[3].Arr[6:7]
20080 //
20081 //   r.ArrS[3].x
20082 namespace {
20083 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
20084   Sema &SemaRef;
20085   OpenMPClauseKind CKind = OMPC_unknown;
20086   OpenMPDirectiveKind DKind = OMPD_unknown;
20087   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
20088   bool IsNonContiguous = false;
20089   bool NoDiagnose = false;
20090   const Expr *RelevantExpr = nullptr;
20091   bool AllowUnitySizeArraySection = true;
20092   bool AllowWholeSizeArraySection = true;
20093   bool AllowAnotherPtr = true;
20094   SourceLocation ELoc;
20095   SourceRange ERange;
20096 
20097   void emitErrorMsg() {
20098     // If nothing else worked, this is not a valid map clause expression.
20099     if (SemaRef.getLangOpts().OpenMP < 50) {
20100       SemaRef.Diag(ELoc,
20101                    diag::err_omp_expected_named_var_member_or_array_expression)
20102           << ERange;
20103     } else {
20104       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
20105           << getOpenMPClauseName(CKind) << ERange;
20106     }
20107   }
20108 
20109 public:
20110   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
20111     if (!isa<VarDecl>(DRE->getDecl())) {
20112       emitErrorMsg();
20113       return false;
20114     }
20115     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20116     RelevantExpr = DRE;
20117     // Record the component.
20118     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
20119     return true;
20120   }
20121 
20122   bool VisitMemberExpr(MemberExpr *ME) {
20123     Expr *E = ME;
20124     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
20125 
20126     if (isa<CXXThisExpr>(BaseE)) {
20127       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20128       // We found a base expression: this->Val.
20129       RelevantExpr = ME;
20130     } else {
20131       E = BaseE;
20132     }
20133 
20134     if (!isa<FieldDecl>(ME->getMemberDecl())) {
20135       if (!NoDiagnose) {
20136         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
20137             << ME->getSourceRange();
20138         return false;
20139       }
20140       if (RelevantExpr)
20141         return false;
20142       return Visit(E);
20143     }
20144 
20145     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
20146 
20147     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
20148     //  A bit-field cannot appear in a map clause.
20149     //
20150     if (FD->isBitField()) {
20151       if (!NoDiagnose) {
20152         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
20153             << ME->getSourceRange() << getOpenMPClauseName(CKind);
20154         return false;
20155       }
20156       if (RelevantExpr)
20157         return false;
20158       return Visit(E);
20159     }
20160 
20161     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20162     //  If the type of a list item is a reference to a type T then the type
20163     //  will be considered to be T for all purposes of this clause.
20164     QualType CurType = BaseE->getType().getNonReferenceType();
20165 
20166     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
20167     //  A list item cannot be a variable that is a member of a structure with
20168     //  a union type.
20169     //
20170     if (CurType->isUnionType()) {
20171       if (!NoDiagnose) {
20172         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
20173             << ME->getSourceRange();
20174         return false;
20175       }
20176       return RelevantExpr || Visit(E);
20177     }
20178 
20179     // If we got a member expression, we should not expect any array section
20180     // before that:
20181     //
20182     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
20183     //  If a list item is an element of a structure, only the rightmost symbol
20184     //  of the variable reference can be an array section.
20185     //
20186     AllowUnitySizeArraySection = false;
20187     AllowWholeSizeArraySection = false;
20188 
20189     // Record the component.
20190     Components.emplace_back(ME, FD, IsNonContiguous);
20191     return RelevantExpr || Visit(E);
20192   }
20193 
20194   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
20195     Expr *E = AE->getBase()->IgnoreParenImpCasts();
20196 
20197     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
20198       if (!NoDiagnose) {
20199         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
20200             << 0 << AE->getSourceRange();
20201         return false;
20202       }
20203       return RelevantExpr || Visit(E);
20204     }
20205 
20206     // If we got an array subscript that express the whole dimension we
20207     // can have any array expressions before. If it only expressing part of
20208     // the dimension, we can only have unitary-size array expressions.
20209     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
20210       AllowWholeSizeArraySection = false;
20211 
20212     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
20213       Expr::EvalResult Result;
20214       if (!AE->getIdx()->isValueDependent() &&
20215           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
20216           !Result.Val.getInt().isZero()) {
20217         SemaRef.Diag(AE->getIdx()->getExprLoc(),
20218                      diag::err_omp_invalid_map_this_expr);
20219         SemaRef.Diag(AE->getIdx()->getExprLoc(),
20220                      diag::note_omp_invalid_subscript_on_this_ptr_map);
20221       }
20222       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20223       RelevantExpr = TE;
20224     }
20225 
20226     // Record the component - we don't have any declaration associated.
20227     Components.emplace_back(AE, nullptr, IsNonContiguous);
20228 
20229     return RelevantExpr || Visit(E);
20230   }
20231 
20232   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
20233     // After OMP 5.0  Array section in reduction clause will be implicitly
20234     // mapped
20235     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
20236            "Array sections cannot be implicitly mapped.");
20237     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
20238     QualType CurType =
20239         OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
20240 
20241     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20242     //  If the type of a list item is a reference to a type T then the type
20243     //  will be considered to be T for all purposes of this clause.
20244     if (CurType->isReferenceType())
20245       CurType = CurType->getPointeeType();
20246 
20247     bool IsPointer = CurType->isAnyPointerType();
20248 
20249     if (!IsPointer && !CurType->isArrayType()) {
20250       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
20251           << 0 << OASE->getSourceRange();
20252       return false;
20253     }
20254 
20255     bool NotWhole =
20256         checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
20257     bool NotUnity =
20258         checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
20259 
20260     if (AllowWholeSizeArraySection) {
20261       // Any array section is currently allowed. Allowing a whole size array
20262       // section implies allowing a unity array section as well.
20263       //
20264       // If this array section refers to the whole dimension we can still
20265       // accept other array sections before this one, except if the base is a
20266       // pointer. Otherwise, only unitary sections are accepted.
20267       if (NotWhole || IsPointer)
20268         AllowWholeSizeArraySection = false;
20269     } else if (DKind == OMPD_target_update &&
20270                SemaRef.getLangOpts().OpenMP >= 50) {
20271       if (IsPointer && !AllowAnotherPtr)
20272         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
20273             << /*array of unknown bound */ 1;
20274       else
20275         IsNonContiguous = true;
20276     } else if (AllowUnitySizeArraySection && NotUnity) {
20277       // A unity or whole array section is not allowed and that is not
20278       // compatible with the properties of the current array section.
20279       if (NoDiagnose)
20280         return false;
20281       SemaRef.Diag(ELoc,
20282                    diag::err_array_section_does_not_specify_contiguous_storage)
20283           << OASE->getSourceRange();
20284       return false;
20285     }
20286 
20287     if (IsPointer)
20288       AllowAnotherPtr = false;
20289 
20290     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
20291       Expr::EvalResult ResultR;
20292       Expr::EvalResult ResultL;
20293       if (!OASE->getLength()->isValueDependent() &&
20294           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
20295           !ResultR.Val.getInt().isOne()) {
20296         SemaRef.Diag(OASE->getLength()->getExprLoc(),
20297                      diag::err_omp_invalid_map_this_expr);
20298         SemaRef.Diag(OASE->getLength()->getExprLoc(),
20299                      diag::note_omp_invalid_length_on_this_ptr_mapping);
20300       }
20301       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
20302           OASE->getLowerBound()->EvaluateAsInt(ResultL,
20303                                                SemaRef.getASTContext()) &&
20304           !ResultL.Val.getInt().isZero()) {
20305         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
20306                      diag::err_omp_invalid_map_this_expr);
20307         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
20308                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
20309       }
20310       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20311       RelevantExpr = TE;
20312     }
20313 
20314     // Record the component - we don't have any declaration associated.
20315     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
20316     return RelevantExpr || Visit(E);
20317   }
20318   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
20319     Expr *Base = E->getBase();
20320 
20321     // Record the component - we don't have any declaration associated.
20322     Components.emplace_back(E, nullptr, IsNonContiguous);
20323 
20324     return Visit(Base->IgnoreParenImpCasts());
20325   }
20326 
20327   bool VisitUnaryOperator(UnaryOperator *UO) {
20328     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
20329         UO->getOpcode() != UO_Deref) {
20330       emitErrorMsg();
20331       return false;
20332     }
20333     if (!RelevantExpr) {
20334       // Record the component if haven't found base decl.
20335       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
20336     }
20337     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
20338   }
20339   bool VisitBinaryOperator(BinaryOperator *BO) {
20340     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
20341       emitErrorMsg();
20342       return false;
20343     }
20344 
20345     // Pointer arithmetic is the only thing we expect to happen here so after we
20346     // make sure the binary operator is a pointer type, the we only thing need
20347     // to to is to visit the subtree that has the same type as root (so that we
20348     // know the other subtree is just an offset)
20349     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
20350     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
20351     Components.emplace_back(BO, nullptr, false);
20352     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
20353             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
20354            "Either LHS or RHS have base decl inside");
20355     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
20356       return RelevantExpr || Visit(LE);
20357     return RelevantExpr || Visit(RE);
20358   }
20359   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
20360     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20361     RelevantExpr = CTE;
20362     Components.emplace_back(CTE, nullptr, IsNonContiguous);
20363     return true;
20364   }
20365   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
20366     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20367     Components.emplace_back(COCE, nullptr, IsNonContiguous);
20368     return true;
20369   }
20370   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
20371     Expr *Source = E->getSourceExpr();
20372     if (!Source) {
20373       emitErrorMsg();
20374       return false;
20375     }
20376     return Visit(Source);
20377   }
20378   bool VisitStmt(Stmt *) {
20379     emitErrorMsg();
20380     return false;
20381   }
20382   const Expr *getFoundBase() const { return RelevantExpr; }
20383   explicit MapBaseChecker(
20384       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
20385       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
20386       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
20387       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
20388         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
20389 };
20390 } // namespace
20391 
20392 /// Return the expression of the base of the mappable expression or null if it
20393 /// cannot be determined and do all the necessary checks to see if the
20394 /// expression is valid as a standalone mappable expression. In the process,
20395 /// record all the components of the expression.
20396 static const Expr *checkMapClauseExpressionBase(
20397     Sema &SemaRef, Expr *E,
20398     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
20399     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
20400   SourceLocation ELoc = E->getExprLoc();
20401   SourceRange ERange = E->getSourceRange();
20402   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
20403                          ERange);
20404   if (Checker.Visit(E->IgnoreParens())) {
20405     // Check if the highest dimension array section has length specified
20406     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
20407         (CKind == OMPC_to || CKind == OMPC_from)) {
20408       auto CI = CurComponents.rbegin();
20409       auto CE = CurComponents.rend();
20410       for (; CI != CE; ++CI) {
20411         const auto *OASE =
20412             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
20413         if (!OASE)
20414           continue;
20415         if (OASE && OASE->getLength())
20416           break;
20417         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
20418             << ERange;
20419       }
20420     }
20421     return Checker.getFoundBase();
20422   }
20423   return nullptr;
20424 }
20425 
20426 // Return true if expression E associated with value VD has conflicts with other
20427 // map information.
20428 static bool checkMapConflicts(
20429     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
20430     bool CurrentRegionOnly,
20431     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
20432     OpenMPClauseKind CKind) {
20433   assert(VD && E);
20434   SourceLocation ELoc = E->getExprLoc();
20435   SourceRange ERange = E->getSourceRange();
20436 
20437   // In order to easily check the conflicts we need to match each component of
20438   // the expression under test with the components of the expressions that are
20439   // already in the stack.
20440 
20441   assert(!CurComponents.empty() && "Map clause expression with no components!");
20442   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
20443          "Map clause expression with unexpected base!");
20444 
20445   // Variables to help detecting enclosing problems in data environment nests.
20446   bool IsEnclosedByDataEnvironmentExpr = false;
20447   const Expr *EnclosingExpr = nullptr;
20448 
20449   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
20450       VD, CurrentRegionOnly,
20451       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
20452        ERange, CKind, &EnclosingExpr,
20453        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
20454                           StackComponents,
20455                       OpenMPClauseKind Kind) {
20456         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
20457           return false;
20458         assert(!StackComponents.empty() &&
20459                "Map clause expression with no components!");
20460         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
20461                "Map clause expression with unexpected base!");
20462         (void)VD;
20463 
20464         // The whole expression in the stack.
20465         const Expr *RE = StackComponents.front().getAssociatedExpression();
20466 
20467         // Expressions must start from the same base. Here we detect at which
20468         // point both expressions diverge from each other and see if we can
20469         // detect if the memory referred to both expressions is contiguous and
20470         // do not overlap.
20471         auto CI = CurComponents.rbegin();
20472         auto CE = CurComponents.rend();
20473         auto SI = StackComponents.rbegin();
20474         auto SE = StackComponents.rend();
20475         for (; CI != CE && SI != SE; ++CI, ++SI) {
20476 
20477           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
20478           //  At most one list item can be an array item derived from a given
20479           //  variable in map clauses of the same construct.
20480           if (CurrentRegionOnly &&
20481               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
20482                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
20483                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
20484               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
20485                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
20486                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
20487             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
20488                          diag::err_omp_multiple_array_items_in_map_clause)
20489                 << CI->getAssociatedExpression()->getSourceRange();
20490             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
20491                          diag::note_used_here)
20492                 << SI->getAssociatedExpression()->getSourceRange();
20493             return true;
20494           }
20495 
20496           // Do both expressions have the same kind?
20497           if (CI->getAssociatedExpression()->getStmtClass() !=
20498               SI->getAssociatedExpression()->getStmtClass())
20499             break;
20500 
20501           // Are we dealing with different variables/fields?
20502           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
20503             break;
20504         }
20505         // Check if the extra components of the expressions in the enclosing
20506         // data environment are redundant for the current base declaration.
20507         // If they are, the maps completely overlap, which is legal.
20508         for (; SI != SE; ++SI) {
20509           QualType Type;
20510           if (const auto *ASE =
20511                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
20512             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
20513           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
20514                          SI->getAssociatedExpression())) {
20515             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
20516             Type =
20517                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
20518           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
20519                          SI->getAssociatedExpression())) {
20520             Type = OASE->getBase()->getType()->getPointeeType();
20521           }
20522           if (Type.isNull() || Type->isAnyPointerType() ||
20523               checkArrayExpressionDoesNotReferToWholeSize(
20524                   SemaRef, SI->getAssociatedExpression(), Type))
20525             break;
20526         }
20527 
20528         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
20529         //  List items of map clauses in the same construct must not share
20530         //  original storage.
20531         //
20532         // If the expressions are exactly the same or one is a subset of the
20533         // other, it means they are sharing storage.
20534         if (CI == CE && SI == SE) {
20535           if (CurrentRegionOnly) {
20536             if (CKind == OMPC_map) {
20537               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
20538             } else {
20539               assert(CKind == OMPC_to || CKind == OMPC_from);
20540               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
20541                   << ERange;
20542             }
20543             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20544                 << RE->getSourceRange();
20545             return true;
20546           }
20547           // If we find the same expression in the enclosing data environment,
20548           // that is legal.
20549           IsEnclosedByDataEnvironmentExpr = true;
20550           return false;
20551         }
20552 
20553         QualType DerivedType =
20554             std::prev(CI)->getAssociatedDeclaration()->getType();
20555         SourceLocation DerivedLoc =
20556             std::prev(CI)->getAssociatedExpression()->getExprLoc();
20557 
20558         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20559         //  If the type of a list item is a reference to a type T then the type
20560         //  will be considered to be T for all purposes of this clause.
20561         DerivedType = DerivedType.getNonReferenceType();
20562 
20563         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
20564         //  A variable for which the type is pointer and an array section
20565         //  derived from that variable must not appear as list items of map
20566         //  clauses of the same construct.
20567         //
20568         // Also, cover one of the cases in:
20569         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
20570         //  If any part of the original storage of a list item has corresponding
20571         //  storage in the device data environment, all of the original storage
20572         //  must have corresponding storage in the device data environment.
20573         //
20574         if (DerivedType->isAnyPointerType()) {
20575           if (CI == CE || SI == SE) {
20576             SemaRef.Diag(
20577                 DerivedLoc,
20578                 diag::err_omp_pointer_mapped_along_with_derived_section)
20579                 << DerivedLoc;
20580             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20581                 << RE->getSourceRange();
20582             return true;
20583           }
20584           if (CI->getAssociatedExpression()->getStmtClass() !=
20585                   SI->getAssociatedExpression()->getStmtClass() ||
20586               CI->getAssociatedDeclaration()->getCanonicalDecl() ==
20587                   SI->getAssociatedDeclaration()->getCanonicalDecl()) {
20588             assert(CI != CE && SI != SE);
20589             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
20590                 << DerivedLoc;
20591             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20592                 << RE->getSourceRange();
20593             return true;
20594           }
20595         }
20596 
20597         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
20598         //  List items of map clauses in the same construct must not share
20599         //  original storage.
20600         //
20601         // An expression is a subset of the other.
20602         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
20603           if (CKind == OMPC_map) {
20604             if (CI != CE || SI != SE) {
20605               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
20606               // a pointer.
20607               auto Begin =
20608                   CI != CE ? CurComponents.begin() : StackComponents.begin();
20609               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
20610               auto It = Begin;
20611               while (It != End && !It->getAssociatedDeclaration())
20612                 std::advance(It, 1);
20613               assert(It != End &&
20614                      "Expected at least one component with the declaration.");
20615               if (It != Begin && It->getAssociatedDeclaration()
20616                                      ->getType()
20617                                      .getCanonicalType()
20618                                      ->isAnyPointerType()) {
20619                 IsEnclosedByDataEnvironmentExpr = false;
20620                 EnclosingExpr = nullptr;
20621                 return false;
20622               }
20623             }
20624             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
20625           } else {
20626             assert(CKind == OMPC_to || CKind == OMPC_from);
20627             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
20628                 << ERange;
20629           }
20630           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20631               << RE->getSourceRange();
20632           return true;
20633         }
20634 
20635         // The current expression uses the same base as other expression in the
20636         // data environment but does not contain it completely.
20637         if (!CurrentRegionOnly && SI != SE)
20638           EnclosingExpr = RE;
20639 
20640         // The current expression is a subset of the expression in the data
20641         // environment.
20642         IsEnclosedByDataEnvironmentExpr |=
20643             (!CurrentRegionOnly && CI != CE && SI == SE);
20644 
20645         return false;
20646       });
20647 
20648   if (CurrentRegionOnly)
20649     return FoundError;
20650 
20651   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
20652   //  If any part of the original storage of a list item has corresponding
20653   //  storage in the device data environment, all of the original storage must
20654   //  have corresponding storage in the device data environment.
20655   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
20656   //  If a list item is an element of a structure, and a different element of
20657   //  the structure has a corresponding list item in the device data environment
20658   //  prior to a task encountering the construct associated with the map clause,
20659   //  then the list item must also have a corresponding list item in the device
20660   //  data environment prior to the task encountering the construct.
20661   //
20662   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
20663     SemaRef.Diag(ELoc,
20664                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
20665         << ERange;
20666     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
20667         << EnclosingExpr->getSourceRange();
20668     return true;
20669   }
20670 
20671   return FoundError;
20672 }
20673 
20674 // Look up the user-defined mapper given the mapper name and mapped type, and
20675 // build a reference to it.
20676 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
20677                                             CXXScopeSpec &MapperIdScopeSpec,
20678                                             const DeclarationNameInfo &MapperId,
20679                                             QualType Type,
20680                                             Expr *UnresolvedMapper) {
20681   if (MapperIdScopeSpec.isInvalid())
20682     return ExprError();
20683   // Get the actual type for the array type.
20684   if (Type->isArrayType()) {
20685     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
20686     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
20687   }
20688   // Find all user-defined mappers with the given MapperId.
20689   SmallVector<UnresolvedSet<8>, 4> Lookups;
20690   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
20691   Lookup.suppressDiagnostics();
20692   if (S) {
20693     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
20694       NamedDecl *D = Lookup.getRepresentativeDecl();
20695       while (S && !S->isDeclScope(D))
20696         S = S->getParent();
20697       if (S)
20698         S = S->getParent();
20699       Lookups.emplace_back();
20700       Lookups.back().append(Lookup.begin(), Lookup.end());
20701       Lookup.clear();
20702     }
20703   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
20704     // Extract the user-defined mappers with the given MapperId.
20705     Lookups.push_back(UnresolvedSet<8>());
20706     for (NamedDecl *D : ULE->decls()) {
20707       auto *DMD = cast<OMPDeclareMapperDecl>(D);
20708       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
20709       Lookups.back().addDecl(DMD);
20710     }
20711   }
20712   // Defer the lookup for dependent types. The results will be passed through
20713   // UnresolvedMapper on instantiation.
20714   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
20715       Type->isInstantiationDependentType() ||
20716       Type->containsUnexpandedParameterPack() ||
20717       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
20718         return !D->isInvalidDecl() &&
20719                (D->getType()->isDependentType() ||
20720                 D->getType()->isInstantiationDependentType() ||
20721                 D->getType()->containsUnexpandedParameterPack());
20722       })) {
20723     UnresolvedSet<8> URS;
20724     for (const UnresolvedSet<8> &Set : Lookups) {
20725       if (Set.empty())
20726         continue;
20727       URS.append(Set.begin(), Set.end());
20728     }
20729     return UnresolvedLookupExpr::Create(
20730         SemaRef.Context, /*NamingClass=*/nullptr,
20731         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
20732         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
20733   }
20734   SourceLocation Loc = MapperId.getLoc();
20735   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20736   //  The type must be of struct, union or class type in C and C++
20737   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
20738       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
20739     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
20740     return ExprError();
20741   }
20742   // Perform argument dependent lookup.
20743   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
20744     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
20745   // Return the first user-defined mapper with the desired type.
20746   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
20747           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
20748             if (!D->isInvalidDecl() &&
20749                 SemaRef.Context.hasSameType(D->getType(), Type))
20750               return D;
20751             return nullptr;
20752           }))
20753     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
20754   // Find the first user-defined mapper with a type derived from the desired
20755   // type.
20756   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
20757           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
20758             if (!D->isInvalidDecl() &&
20759                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
20760                 !Type.isMoreQualifiedThan(D->getType()))
20761               return D;
20762             return nullptr;
20763           })) {
20764     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
20765                        /*DetectVirtual=*/false);
20766     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
20767       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
20768               VD->getType().getUnqualifiedType()))) {
20769         if (SemaRef.CheckBaseClassAccess(
20770                 Loc, VD->getType(), Type, Paths.front(),
20771                 /*DiagID=*/0) != Sema::AR_inaccessible) {
20772           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
20773         }
20774       }
20775     }
20776   }
20777   // Report error if a mapper is specified, but cannot be found.
20778   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
20779     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
20780         << Type << MapperId.getName();
20781     return ExprError();
20782   }
20783   return ExprEmpty();
20784 }
20785 
20786 namespace {
20787 // Utility struct that gathers all the related lists associated with a mappable
20788 // expression.
20789 struct MappableVarListInfo {
20790   // The list of expressions.
20791   ArrayRef<Expr *> VarList;
20792   // The list of processed expressions.
20793   SmallVector<Expr *, 16> ProcessedVarList;
20794   // The mappble components for each expression.
20795   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
20796   // The base declaration of the variable.
20797   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
20798   // The reference to the user-defined mapper associated with every expression.
20799   SmallVector<Expr *, 16> UDMapperList;
20800 
20801   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
20802     // We have a list of components and base declarations for each entry in the
20803     // variable list.
20804     VarComponents.reserve(VarList.size());
20805     VarBaseDeclarations.reserve(VarList.size());
20806   }
20807 };
20808 } // namespace
20809 
20810 // Check the validity of the provided variable list for the provided clause kind
20811 // \a CKind. In the check process the valid expressions, mappable expression
20812 // components, variables, and user-defined mappers are extracted and used to
20813 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
20814 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
20815 // and \a MapperId are expected to be valid if the clause kind is 'map'.
20816 static void checkMappableExpressionList(
20817     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
20818     MappableVarListInfo &MVLI, SourceLocation StartLoc,
20819     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
20820     ArrayRef<Expr *> UnresolvedMappers,
20821     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
20822     ArrayRef<OpenMPMapModifierKind> Modifiers = None,
20823     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
20824   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
20825   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
20826          "Unexpected clause kind with mappable expressions!");
20827 
20828   // If the identifier of user-defined mapper is not specified, it is "default".
20829   // We do not change the actual name in this clause to distinguish whether a
20830   // mapper is specified explicitly, i.e., it is not explicitly specified when
20831   // MapperId.getName() is empty.
20832   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
20833     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
20834     MapperId.setName(DeclNames.getIdentifier(
20835         &SemaRef.getASTContext().Idents.get("default")));
20836     MapperId.setLoc(StartLoc);
20837   }
20838 
20839   // Iterators to find the current unresolved mapper expression.
20840   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
20841   bool UpdateUMIt = false;
20842   Expr *UnresolvedMapper = nullptr;
20843 
20844   bool HasHoldModifier =
20845       llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
20846 
20847   // Keep track of the mappable components and base declarations in this clause.
20848   // Each entry in the list is going to have a list of components associated. We
20849   // record each set of the components so that we can build the clause later on.
20850   // In the end we should have the same amount of declarations and component
20851   // lists.
20852 
20853   for (Expr *RE : MVLI.VarList) {
20854     assert(RE && "Null expr in omp to/from/map clause");
20855     SourceLocation ELoc = RE->getExprLoc();
20856 
20857     // Find the current unresolved mapper expression.
20858     if (UpdateUMIt && UMIt != UMEnd) {
20859       UMIt++;
20860       assert(
20861           UMIt != UMEnd &&
20862           "Expect the size of UnresolvedMappers to match with that of VarList");
20863     }
20864     UpdateUMIt = true;
20865     if (UMIt != UMEnd)
20866       UnresolvedMapper = *UMIt;
20867 
20868     const Expr *VE = RE->IgnoreParenLValueCasts();
20869 
20870     if (VE->isValueDependent() || VE->isTypeDependent() ||
20871         VE->isInstantiationDependent() ||
20872         VE->containsUnexpandedParameterPack()) {
20873       // Try to find the associated user-defined mapper.
20874       ExprResult ER = buildUserDefinedMapperRef(
20875           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20876           VE->getType().getCanonicalType(), UnresolvedMapper);
20877       if (ER.isInvalid())
20878         continue;
20879       MVLI.UDMapperList.push_back(ER.get());
20880       // We can only analyze this information once the missing information is
20881       // resolved.
20882       MVLI.ProcessedVarList.push_back(RE);
20883       continue;
20884     }
20885 
20886     Expr *SimpleExpr = RE->IgnoreParenCasts();
20887 
20888     if (!RE->isLValue()) {
20889       if (SemaRef.getLangOpts().OpenMP < 50) {
20890         SemaRef.Diag(
20891             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
20892             << RE->getSourceRange();
20893       } else {
20894         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
20895             << getOpenMPClauseName(CKind) << RE->getSourceRange();
20896       }
20897       continue;
20898     }
20899 
20900     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
20901     ValueDecl *CurDeclaration = nullptr;
20902 
20903     // Obtain the array or member expression bases if required. Also, fill the
20904     // components array with all the components identified in the process.
20905     const Expr *BE =
20906         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
20907                                      DSAS->getCurrentDirective(), NoDiagnose);
20908     if (!BE)
20909       continue;
20910 
20911     assert(!CurComponents.empty() &&
20912            "Invalid mappable expression information.");
20913 
20914     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
20915       // Add store "this" pointer to class in DSAStackTy for future checking
20916       DSAS->addMappedClassesQualTypes(TE->getType());
20917       // Try to find the associated user-defined mapper.
20918       ExprResult ER = buildUserDefinedMapperRef(
20919           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20920           VE->getType().getCanonicalType(), UnresolvedMapper);
20921       if (ER.isInvalid())
20922         continue;
20923       MVLI.UDMapperList.push_back(ER.get());
20924       // Skip restriction checking for variable or field declarations
20925       MVLI.ProcessedVarList.push_back(RE);
20926       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20927       MVLI.VarComponents.back().append(CurComponents.begin(),
20928                                        CurComponents.end());
20929       MVLI.VarBaseDeclarations.push_back(nullptr);
20930       continue;
20931     }
20932 
20933     // For the following checks, we rely on the base declaration which is
20934     // expected to be associated with the last component. The declaration is
20935     // expected to be a variable or a field (if 'this' is being mapped).
20936     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
20937     assert(CurDeclaration && "Null decl on map clause.");
20938     assert(
20939         CurDeclaration->isCanonicalDecl() &&
20940         "Expecting components to have associated only canonical declarations.");
20941 
20942     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
20943     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
20944 
20945     assert((VD || FD) && "Only variables or fields are expected here!");
20946     (void)FD;
20947 
20948     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
20949     // threadprivate variables cannot appear in a map clause.
20950     // OpenMP 4.5 [2.10.5, target update Construct]
20951     // threadprivate variables cannot appear in a from clause.
20952     if (VD && DSAS->isThreadPrivate(VD)) {
20953       if (NoDiagnose)
20954         continue;
20955       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
20956       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
20957           << getOpenMPClauseName(CKind);
20958       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
20959       continue;
20960     }
20961 
20962     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
20963     //  A list item cannot appear in both a map clause and a data-sharing
20964     //  attribute clause on the same construct.
20965 
20966     // Check conflicts with other map clause expressions. We check the conflicts
20967     // with the current construct separately from the enclosing data
20968     // environment, because the restrictions are different. We only have to
20969     // check conflicts across regions for the map clauses.
20970     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
20971                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
20972       break;
20973     if (CKind == OMPC_map &&
20974         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
20975         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
20976                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
20977       break;
20978 
20979     // OpenMP 4.5 [2.10.5, target update Construct]
20980     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20981     //  If the type of a list item is a reference to a type T then the type will
20982     //  be considered to be T for all purposes of this clause.
20983     auto I = llvm::find_if(
20984         CurComponents,
20985         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
20986           return MC.getAssociatedDeclaration();
20987         });
20988     assert(I != CurComponents.end() && "Null decl on map clause.");
20989     (void)I;
20990     QualType Type;
20991     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
20992     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
20993     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
20994     if (ASE) {
20995       Type = ASE->getType().getNonReferenceType();
20996     } else if (OASE) {
20997       QualType BaseType =
20998           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
20999       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
21000         Type = ATy->getElementType();
21001       else
21002         Type = BaseType->getPointeeType();
21003       Type = Type.getNonReferenceType();
21004     } else if (OAShE) {
21005       Type = OAShE->getBase()->getType()->getPointeeType();
21006     } else {
21007       Type = VE->getType();
21008     }
21009 
21010     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
21011     // A list item in a to or from clause must have a mappable type.
21012     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
21013     //  A list item must have a mappable type.
21014     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
21015                            DSAS, Type, /*FullCheck=*/true))
21016       continue;
21017 
21018     if (CKind == OMPC_map) {
21019       // target enter data
21020       // OpenMP [2.10.2, Restrictions, p. 99]
21021       // A map-type must be specified in all map clauses and must be either
21022       // to or alloc.
21023       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
21024       if (DKind == OMPD_target_enter_data &&
21025           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
21026         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
21027             << (IsMapTypeImplicit ? 1 : 0)
21028             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
21029             << getOpenMPDirectiveName(DKind);
21030         continue;
21031       }
21032 
21033       // target exit_data
21034       // OpenMP [2.10.3, Restrictions, p. 102]
21035       // A map-type must be specified in all map clauses and must be either
21036       // from, release, or delete.
21037       if (DKind == OMPD_target_exit_data &&
21038           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
21039             MapType == OMPC_MAP_delete)) {
21040         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
21041             << (IsMapTypeImplicit ? 1 : 0)
21042             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
21043             << getOpenMPDirectiveName(DKind);
21044         continue;
21045       }
21046 
21047       // The 'ompx_hold' modifier is specifically intended to be used on a
21048       // 'target' or 'target data' directive to prevent data from being unmapped
21049       // during the associated statement.  It is not permitted on a 'target
21050       // enter data' or 'target exit data' directive, which have no associated
21051       // statement.
21052       if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
21053           HasHoldModifier) {
21054         SemaRef.Diag(StartLoc,
21055                      diag::err_omp_invalid_map_type_modifier_for_directive)
21056             << getOpenMPSimpleClauseTypeName(OMPC_map,
21057                                              OMPC_MAP_MODIFIER_ompx_hold)
21058             << getOpenMPDirectiveName(DKind);
21059         continue;
21060       }
21061 
21062       // target, target data
21063       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
21064       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
21065       // A map-type in a map clause must be to, from, tofrom or alloc
21066       if ((DKind == OMPD_target_data ||
21067            isOpenMPTargetExecutionDirective(DKind)) &&
21068           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
21069             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
21070         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
21071             << (IsMapTypeImplicit ? 1 : 0)
21072             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
21073             << getOpenMPDirectiveName(DKind);
21074         continue;
21075       }
21076 
21077       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
21078       // A list item cannot appear in both a map clause and a data-sharing
21079       // attribute clause on the same construct
21080       //
21081       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
21082       // A list item cannot appear in both a map clause and a data-sharing
21083       // attribute clause on the same construct unless the construct is a
21084       // combined construct.
21085       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
21086                   isOpenMPTargetExecutionDirective(DKind)) ||
21087                  DKind == OMPD_target)) {
21088         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
21089         if (isOpenMPPrivate(DVar.CKind)) {
21090           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21091               << getOpenMPClauseName(DVar.CKind)
21092               << getOpenMPClauseName(OMPC_map)
21093               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
21094           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
21095           continue;
21096         }
21097       }
21098     }
21099 
21100     // Try to find the associated user-defined mapper.
21101     ExprResult ER = buildUserDefinedMapperRef(
21102         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
21103         Type.getCanonicalType(), UnresolvedMapper);
21104     if (ER.isInvalid())
21105       continue;
21106     MVLI.UDMapperList.push_back(ER.get());
21107 
21108     // Save the current expression.
21109     MVLI.ProcessedVarList.push_back(RE);
21110 
21111     // Store the components in the stack so that they can be used to check
21112     // against other clauses later on.
21113     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
21114                                           /*WhereFoundClauseKind=*/OMPC_map);
21115 
21116     // Save the components and declaration to create the clause. For purposes of
21117     // the clause creation, any component list that has has base 'this' uses
21118     // null as base declaration.
21119     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21120     MVLI.VarComponents.back().append(CurComponents.begin(),
21121                                      CurComponents.end());
21122     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
21123                                                            : CurDeclaration);
21124   }
21125 }
21126 
21127 OMPClause *Sema::ActOnOpenMPMapClause(
21128     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
21129     ArrayRef<SourceLocation> MapTypeModifiersLoc,
21130     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
21131     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
21132     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
21133     const OMPVarListLocTy &Locs, bool NoDiagnose,
21134     ArrayRef<Expr *> UnresolvedMappers) {
21135   OpenMPMapModifierKind Modifiers[] = {
21136       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
21137       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
21138       OMPC_MAP_MODIFIER_unknown};
21139   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
21140 
21141   // Process map-type-modifiers, flag errors for duplicate modifiers.
21142   unsigned Count = 0;
21143   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
21144     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
21145         llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
21146       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
21147       continue;
21148     }
21149     assert(Count < NumberOfOMPMapClauseModifiers &&
21150            "Modifiers exceed the allowed number of map type modifiers");
21151     Modifiers[Count] = MapTypeModifiers[I];
21152     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
21153     ++Count;
21154   }
21155 
21156   MappableVarListInfo MVLI(VarList);
21157   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
21158                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
21159                               MapType, Modifiers, IsMapTypeImplicit,
21160                               NoDiagnose);
21161 
21162   // We need to produce a map clause even if we don't have variables so that
21163   // other diagnostics related with non-existing map clauses are accurate.
21164   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
21165                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
21166                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
21167                               MapperIdScopeSpec.getWithLocInContext(Context),
21168                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
21169 }
21170 
21171 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
21172                                                TypeResult ParsedType) {
21173   assert(ParsedType.isUsable());
21174 
21175   QualType ReductionType = GetTypeFromParser(ParsedType.get());
21176   if (ReductionType.isNull())
21177     return QualType();
21178 
21179   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
21180   // A type name in a declare reduction directive cannot be a function type, an
21181   // array type, a reference type, or a type qualified with const, volatile or
21182   // restrict.
21183   if (ReductionType.hasQualifiers()) {
21184     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
21185     return QualType();
21186   }
21187 
21188   if (ReductionType->isFunctionType()) {
21189     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
21190     return QualType();
21191   }
21192   if (ReductionType->isReferenceType()) {
21193     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
21194     return QualType();
21195   }
21196   if (ReductionType->isArrayType()) {
21197     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
21198     return QualType();
21199   }
21200   return ReductionType;
21201 }
21202 
21203 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
21204     Scope *S, DeclContext *DC, DeclarationName Name,
21205     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
21206     AccessSpecifier AS, Decl *PrevDeclInScope) {
21207   SmallVector<Decl *, 8> Decls;
21208   Decls.reserve(ReductionTypes.size());
21209 
21210   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
21211                       forRedeclarationInCurContext());
21212   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
21213   // A reduction-identifier may not be re-declared in the current scope for the
21214   // same type or for a type that is compatible according to the base language
21215   // rules.
21216   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
21217   OMPDeclareReductionDecl *PrevDRD = nullptr;
21218   bool InCompoundScope = true;
21219   if (S != nullptr) {
21220     // Find previous declaration with the same name not referenced in other
21221     // declarations.
21222     FunctionScopeInfo *ParentFn = getEnclosingFunction();
21223     InCompoundScope =
21224         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
21225     LookupName(Lookup, S);
21226     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
21227                          /*AllowInlineNamespace=*/false);
21228     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
21229     LookupResult::Filter Filter = Lookup.makeFilter();
21230     while (Filter.hasNext()) {
21231       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
21232       if (InCompoundScope) {
21233         auto I = UsedAsPrevious.find(PrevDecl);
21234         if (I == UsedAsPrevious.end())
21235           UsedAsPrevious[PrevDecl] = false;
21236         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
21237           UsedAsPrevious[D] = true;
21238       }
21239       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
21240           PrevDecl->getLocation();
21241     }
21242     Filter.done();
21243     if (InCompoundScope) {
21244       for (const auto &PrevData : UsedAsPrevious) {
21245         if (!PrevData.second) {
21246           PrevDRD = PrevData.first;
21247           break;
21248         }
21249       }
21250     }
21251   } else if (PrevDeclInScope != nullptr) {
21252     auto *PrevDRDInScope = PrevDRD =
21253         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
21254     do {
21255       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
21256           PrevDRDInScope->getLocation();
21257       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
21258     } while (PrevDRDInScope != nullptr);
21259   }
21260   for (const auto &TyData : ReductionTypes) {
21261     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
21262     bool Invalid = false;
21263     if (I != PreviousRedeclTypes.end()) {
21264       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
21265           << TyData.first;
21266       Diag(I->second, diag::note_previous_definition);
21267       Invalid = true;
21268     }
21269     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
21270     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
21271                                                 Name, TyData.first, PrevDRD);
21272     DC->addDecl(DRD);
21273     DRD->setAccess(AS);
21274     Decls.push_back(DRD);
21275     if (Invalid)
21276       DRD->setInvalidDecl();
21277     else
21278       PrevDRD = DRD;
21279   }
21280 
21281   return DeclGroupPtrTy::make(
21282       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
21283 }
21284 
21285 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
21286   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21287 
21288   // Enter new function scope.
21289   PushFunctionScope();
21290   setFunctionHasBranchProtectedScope();
21291   getCurFunction()->setHasOMPDeclareReductionCombiner();
21292 
21293   if (S != nullptr)
21294     PushDeclContext(S, DRD);
21295   else
21296     CurContext = DRD;
21297 
21298   PushExpressionEvaluationContext(
21299       ExpressionEvaluationContext::PotentiallyEvaluated);
21300 
21301   QualType ReductionType = DRD->getType();
21302   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
21303   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
21304   // uses semantics of argument handles by value, but it should be passed by
21305   // reference. C lang does not support references, so pass all parameters as
21306   // pointers.
21307   // Create 'T omp_in;' variable.
21308   VarDecl *OmpInParm =
21309       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
21310   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
21311   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
21312   // uses semantics of argument handles by value, but it should be passed by
21313   // reference. C lang does not support references, so pass all parameters as
21314   // pointers.
21315   // Create 'T omp_out;' variable.
21316   VarDecl *OmpOutParm =
21317       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
21318   if (S != nullptr) {
21319     PushOnScopeChains(OmpInParm, S);
21320     PushOnScopeChains(OmpOutParm, S);
21321   } else {
21322     DRD->addDecl(OmpInParm);
21323     DRD->addDecl(OmpOutParm);
21324   }
21325   Expr *InE =
21326       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
21327   Expr *OutE =
21328       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
21329   DRD->setCombinerData(InE, OutE);
21330 }
21331 
21332 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
21333   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21334   DiscardCleanupsInEvaluationContext();
21335   PopExpressionEvaluationContext();
21336 
21337   PopDeclContext();
21338   PopFunctionScopeInfo();
21339 
21340   if (Combiner != nullptr)
21341     DRD->setCombiner(Combiner);
21342   else
21343     DRD->setInvalidDecl();
21344 }
21345 
21346 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
21347   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21348 
21349   // Enter new function scope.
21350   PushFunctionScope();
21351   setFunctionHasBranchProtectedScope();
21352 
21353   if (S != nullptr)
21354     PushDeclContext(S, DRD);
21355   else
21356     CurContext = DRD;
21357 
21358   PushExpressionEvaluationContext(
21359       ExpressionEvaluationContext::PotentiallyEvaluated);
21360 
21361   QualType ReductionType = DRD->getType();
21362   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
21363   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
21364   // uses semantics of argument handles by value, but it should be passed by
21365   // reference. C lang does not support references, so pass all parameters as
21366   // pointers.
21367   // Create 'T omp_priv;' variable.
21368   VarDecl *OmpPrivParm =
21369       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
21370   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
21371   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
21372   // uses semantics of argument handles by value, but it should be passed by
21373   // reference. C lang does not support references, so pass all parameters as
21374   // pointers.
21375   // Create 'T omp_orig;' variable.
21376   VarDecl *OmpOrigParm =
21377       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
21378   if (S != nullptr) {
21379     PushOnScopeChains(OmpPrivParm, S);
21380     PushOnScopeChains(OmpOrigParm, S);
21381   } else {
21382     DRD->addDecl(OmpPrivParm);
21383     DRD->addDecl(OmpOrigParm);
21384   }
21385   Expr *OrigE =
21386       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
21387   Expr *PrivE =
21388       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
21389   DRD->setInitializerData(OrigE, PrivE);
21390   return OmpPrivParm;
21391 }
21392 
21393 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
21394                                                      VarDecl *OmpPrivParm) {
21395   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21396   DiscardCleanupsInEvaluationContext();
21397   PopExpressionEvaluationContext();
21398 
21399   PopDeclContext();
21400   PopFunctionScopeInfo();
21401 
21402   if (Initializer != nullptr) {
21403     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
21404   } else if (OmpPrivParm->hasInit()) {
21405     DRD->setInitializer(OmpPrivParm->getInit(),
21406                         OmpPrivParm->isDirectInit()
21407                             ? OMPDeclareReductionDecl::DirectInit
21408                             : OMPDeclareReductionDecl::CopyInit);
21409   } else {
21410     DRD->setInvalidDecl();
21411   }
21412 }
21413 
21414 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
21415     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
21416   for (Decl *D : DeclReductions.get()) {
21417     if (IsValid) {
21418       if (S)
21419         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
21420                           /*AddToContext=*/false);
21421     } else {
21422       D->setInvalidDecl();
21423     }
21424   }
21425   return DeclReductions;
21426 }
21427 
21428 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
21429   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
21430   QualType T = TInfo->getType();
21431   if (D.isInvalidType())
21432     return true;
21433 
21434   if (getLangOpts().CPlusPlus) {
21435     // Check that there are no default arguments (C++ only).
21436     CheckExtraCXXDefaultArguments(D);
21437   }
21438 
21439   return CreateParsedType(T, TInfo);
21440 }
21441 
21442 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
21443                                             TypeResult ParsedType) {
21444   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
21445 
21446   QualType MapperType = GetTypeFromParser(ParsedType.get());
21447   assert(!MapperType.isNull() && "Expect valid mapper type");
21448 
21449   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
21450   //  The type must be of struct, union or class type in C and C++
21451   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
21452     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
21453     return QualType();
21454   }
21455   return MapperType;
21456 }
21457 
21458 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
21459     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
21460     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
21461     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
21462   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
21463                       forRedeclarationInCurContext());
21464   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
21465   //  A mapper-identifier may not be redeclared in the current scope for the
21466   //  same type or for a type that is compatible according to the base language
21467   //  rules.
21468   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
21469   OMPDeclareMapperDecl *PrevDMD = nullptr;
21470   bool InCompoundScope = true;
21471   if (S != nullptr) {
21472     // Find previous declaration with the same name not referenced in other
21473     // declarations.
21474     FunctionScopeInfo *ParentFn = getEnclosingFunction();
21475     InCompoundScope =
21476         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
21477     LookupName(Lookup, S);
21478     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
21479                          /*AllowInlineNamespace=*/false);
21480     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
21481     LookupResult::Filter Filter = Lookup.makeFilter();
21482     while (Filter.hasNext()) {
21483       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
21484       if (InCompoundScope) {
21485         auto I = UsedAsPrevious.find(PrevDecl);
21486         if (I == UsedAsPrevious.end())
21487           UsedAsPrevious[PrevDecl] = false;
21488         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
21489           UsedAsPrevious[D] = true;
21490       }
21491       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
21492           PrevDecl->getLocation();
21493     }
21494     Filter.done();
21495     if (InCompoundScope) {
21496       for (const auto &PrevData : UsedAsPrevious) {
21497         if (!PrevData.second) {
21498           PrevDMD = PrevData.first;
21499           break;
21500         }
21501       }
21502     }
21503   } else if (PrevDeclInScope) {
21504     auto *PrevDMDInScope = PrevDMD =
21505         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
21506     do {
21507       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
21508           PrevDMDInScope->getLocation();
21509       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
21510     } while (PrevDMDInScope != nullptr);
21511   }
21512   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
21513   bool Invalid = false;
21514   if (I != PreviousRedeclTypes.end()) {
21515     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
21516         << MapperType << Name;
21517     Diag(I->second, diag::note_previous_definition);
21518     Invalid = true;
21519   }
21520   // Build expressions for implicit maps of data members with 'default'
21521   // mappers.
21522   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
21523                                                   Clauses.end());
21524   if (LangOpts.OpenMP >= 50)
21525     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
21526   auto *DMD =
21527       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
21528                                    ClausesWithImplicit, PrevDMD);
21529   if (S)
21530     PushOnScopeChains(DMD, S);
21531   else
21532     DC->addDecl(DMD);
21533   DMD->setAccess(AS);
21534   if (Invalid)
21535     DMD->setInvalidDecl();
21536 
21537   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
21538   VD->setDeclContext(DMD);
21539   VD->setLexicalDeclContext(DMD);
21540   DMD->addDecl(VD);
21541   DMD->setMapperVarRef(MapperVarRef);
21542 
21543   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
21544 }
21545 
21546 ExprResult
21547 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
21548                                                SourceLocation StartLoc,
21549                                                DeclarationName VN) {
21550   TypeSourceInfo *TInfo =
21551       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
21552   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
21553                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
21554                              MapperType, TInfo, SC_None);
21555   if (S)
21556     PushOnScopeChains(VD, S, /*AddToContext=*/false);
21557   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
21558   DSAStack->addDeclareMapperVarRef(E);
21559   return E;
21560 }
21561 
21562 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
21563   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
21564   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
21565   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
21566     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
21567       return true;
21568     if (VD->isUsableInConstantExpressions(Context))
21569       return true;
21570     return false;
21571   }
21572   return true;
21573 }
21574 
21575 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
21576   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
21577   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
21578 }
21579 
21580 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
21581                                            SourceLocation StartLoc,
21582                                            SourceLocation LParenLoc,
21583                                            SourceLocation EndLoc) {
21584   Expr *ValExpr = NumTeams;
21585   Stmt *HelperValStmt = nullptr;
21586 
21587   // OpenMP [teams Constrcut, Restrictions]
21588   // The num_teams expression must evaluate to a positive integer value.
21589   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
21590                                  /*StrictlyPositive=*/true))
21591     return nullptr;
21592 
21593   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
21594   OpenMPDirectiveKind CaptureRegion =
21595       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
21596   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
21597     ValExpr = MakeFullExpr(ValExpr).get();
21598     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21599     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21600     HelperValStmt = buildPreInits(Context, Captures);
21601   }
21602 
21603   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
21604                                          StartLoc, LParenLoc, EndLoc);
21605 }
21606 
21607 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
21608                                               SourceLocation StartLoc,
21609                                               SourceLocation LParenLoc,
21610                                               SourceLocation EndLoc) {
21611   Expr *ValExpr = ThreadLimit;
21612   Stmt *HelperValStmt = nullptr;
21613 
21614   // OpenMP [teams Constrcut, Restrictions]
21615   // The thread_limit expression must evaluate to a positive integer value.
21616   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
21617                                  /*StrictlyPositive=*/true))
21618     return nullptr;
21619 
21620   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
21621   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
21622       DKind, OMPC_thread_limit, LangOpts.OpenMP);
21623   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
21624     ValExpr = MakeFullExpr(ValExpr).get();
21625     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21626     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21627     HelperValStmt = buildPreInits(Context, Captures);
21628   }
21629 
21630   return new (Context) OMPThreadLimitClause(
21631       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
21632 }
21633 
21634 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
21635                                            SourceLocation StartLoc,
21636                                            SourceLocation LParenLoc,
21637                                            SourceLocation EndLoc) {
21638   Expr *ValExpr = Priority;
21639   Stmt *HelperValStmt = nullptr;
21640   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
21641 
21642   // OpenMP [2.9.1, task Constrcut]
21643   // The priority-value is a non-negative numerical scalar expression.
21644   if (!isNonNegativeIntegerValue(
21645           ValExpr, *this, OMPC_priority,
21646           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
21647           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
21648     return nullptr;
21649 
21650   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
21651                                          StartLoc, LParenLoc, EndLoc);
21652 }
21653 
21654 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
21655                                             SourceLocation StartLoc,
21656                                             SourceLocation LParenLoc,
21657                                             SourceLocation EndLoc) {
21658   Expr *ValExpr = Grainsize;
21659   Stmt *HelperValStmt = nullptr;
21660   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
21661 
21662   // OpenMP [2.9.2, taskloop Constrcut]
21663   // The parameter of the grainsize clause must be a positive integer
21664   // expression.
21665   if (!isNonNegativeIntegerValue(
21666           ValExpr, *this, OMPC_grainsize,
21667           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
21668           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
21669     return nullptr;
21670 
21671   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
21672                                           StartLoc, LParenLoc, EndLoc);
21673 }
21674 
21675 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
21676                                            SourceLocation StartLoc,
21677                                            SourceLocation LParenLoc,
21678                                            SourceLocation EndLoc) {
21679   Expr *ValExpr = NumTasks;
21680   Stmt *HelperValStmt = nullptr;
21681   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
21682 
21683   // OpenMP [2.9.2, taskloop Constrcut]
21684   // The parameter of the num_tasks clause must be a positive integer
21685   // expression.
21686   if (!isNonNegativeIntegerValue(
21687           ValExpr, *this, OMPC_num_tasks,
21688           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
21689           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
21690     return nullptr;
21691 
21692   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
21693                                          StartLoc, LParenLoc, EndLoc);
21694 }
21695 
21696 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
21697                                        SourceLocation LParenLoc,
21698                                        SourceLocation EndLoc) {
21699   // OpenMP [2.13.2, critical construct, Description]
21700   // ... where hint-expression is an integer constant expression that evaluates
21701   // to a valid lock hint.
21702   ExprResult HintExpr =
21703       VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint, false);
21704   if (HintExpr.isInvalid())
21705     return nullptr;
21706   return new (Context)
21707       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
21708 }
21709 
21710 /// Tries to find omp_event_handle_t type.
21711 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
21712                                 DSAStackTy *Stack) {
21713   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
21714   if (!OMPEventHandleT.isNull())
21715     return true;
21716   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
21717   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
21718   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21719     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
21720     return false;
21721   }
21722   Stack->setOMPEventHandleT(PT.get());
21723   return true;
21724 }
21725 
21726 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
21727                                          SourceLocation LParenLoc,
21728                                          SourceLocation EndLoc) {
21729   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
21730       !Evt->isInstantiationDependent() &&
21731       !Evt->containsUnexpandedParameterPack()) {
21732     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
21733       return nullptr;
21734     // OpenMP 5.0, 2.10.1 task Construct.
21735     // event-handle is a variable of the omp_event_handle_t type.
21736     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
21737     if (!Ref) {
21738       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
21739           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
21740       return nullptr;
21741     }
21742     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
21743     if (!VD) {
21744       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
21745           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
21746       return nullptr;
21747     }
21748     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
21749                                         VD->getType()) ||
21750         VD->getType().isConstant(Context)) {
21751       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
21752           << "omp_event_handle_t" << 1 << VD->getType()
21753           << Evt->getSourceRange();
21754       return nullptr;
21755     }
21756     // OpenMP 5.0, 2.10.1 task Construct
21757     // [detach clause]... The event-handle will be considered as if it was
21758     // specified on a firstprivate clause.
21759     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
21760     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
21761         DVar.RefExpr) {
21762       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
21763           << getOpenMPClauseName(DVar.CKind)
21764           << getOpenMPClauseName(OMPC_firstprivate);
21765       reportOriginalDsa(*this, DSAStack, VD, DVar);
21766       return nullptr;
21767     }
21768   }
21769 
21770   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
21771 }
21772 
21773 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
21774     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
21775     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
21776     SourceLocation EndLoc) {
21777   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
21778     std::string Values;
21779     Values += "'";
21780     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
21781     Values += "'";
21782     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21783         << Values << getOpenMPClauseName(OMPC_dist_schedule);
21784     return nullptr;
21785   }
21786   Expr *ValExpr = ChunkSize;
21787   Stmt *HelperValStmt = nullptr;
21788   if (ChunkSize) {
21789     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
21790         !ChunkSize->isInstantiationDependent() &&
21791         !ChunkSize->containsUnexpandedParameterPack()) {
21792       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
21793       ExprResult Val =
21794           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
21795       if (Val.isInvalid())
21796         return nullptr;
21797 
21798       ValExpr = Val.get();
21799 
21800       // OpenMP [2.7.1, Restrictions]
21801       //  chunk_size must be a loop invariant integer expression with a positive
21802       //  value.
21803       if (Optional<llvm::APSInt> Result =
21804               ValExpr->getIntegerConstantExpr(Context)) {
21805         if (Result->isSigned() && !Result->isStrictlyPositive()) {
21806           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
21807               << "dist_schedule" << ChunkSize->getSourceRange();
21808           return nullptr;
21809         }
21810       } else if (getOpenMPCaptureRegionForClause(
21811                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
21812                      LangOpts.OpenMP) != OMPD_unknown &&
21813                  !CurContext->isDependentContext()) {
21814         ValExpr = MakeFullExpr(ValExpr).get();
21815         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21816         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21817         HelperValStmt = buildPreInits(Context, Captures);
21818       }
21819     }
21820   }
21821 
21822   return new (Context)
21823       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
21824                             Kind, ValExpr, HelperValStmt);
21825 }
21826 
21827 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
21828     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
21829     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
21830     SourceLocation KindLoc, SourceLocation EndLoc) {
21831   if (getLangOpts().OpenMP < 50) {
21832     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
21833         Kind != OMPC_DEFAULTMAP_scalar) {
21834       std::string Value;
21835       SourceLocation Loc;
21836       Value += "'";
21837       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
21838         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
21839                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
21840         Loc = MLoc;
21841       } else {
21842         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
21843                                                OMPC_DEFAULTMAP_scalar);
21844         Loc = KindLoc;
21845       }
21846       Value += "'";
21847       Diag(Loc, diag::err_omp_unexpected_clause_value)
21848           << Value << getOpenMPClauseName(OMPC_defaultmap);
21849       return nullptr;
21850     }
21851   } else {
21852     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
21853     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
21854                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
21855     if (!isDefaultmapKind || !isDefaultmapModifier) {
21856       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
21857       if (LangOpts.OpenMP == 50) {
21858         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
21859                                   "'firstprivate', 'none', 'default'";
21860         if (!isDefaultmapKind && isDefaultmapModifier) {
21861           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21862               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21863         } else if (isDefaultmapKind && !isDefaultmapModifier) {
21864           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21865               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21866         } else {
21867           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21868               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21869           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21870               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21871         }
21872       } else {
21873         StringRef ModifierValue =
21874             "'alloc', 'from', 'to', 'tofrom', "
21875             "'firstprivate', 'none', 'default', 'present'";
21876         if (!isDefaultmapKind && isDefaultmapModifier) {
21877           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21878               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21879         } else if (isDefaultmapKind && !isDefaultmapModifier) {
21880           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21881               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21882         } else {
21883           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21884               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21885           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21886               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21887         }
21888       }
21889       return nullptr;
21890     }
21891 
21892     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
21893     //  At most one defaultmap clause for each category can appear on the
21894     //  directive.
21895     if (DSAStack->checkDefaultmapCategory(Kind)) {
21896       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
21897       return nullptr;
21898     }
21899   }
21900   if (Kind == OMPC_DEFAULTMAP_unknown) {
21901     // Variable category is not specified - mark all categories.
21902     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
21903     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
21904     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
21905   } else {
21906     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
21907   }
21908 
21909   return new (Context)
21910       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
21911 }
21912 
21913 bool Sema::ActOnStartOpenMPDeclareTargetContext(
21914     DeclareTargetContextInfo &DTCI) {
21915   DeclContext *CurLexicalContext = getCurLexicalContext();
21916   if (!CurLexicalContext->isFileContext() &&
21917       !CurLexicalContext->isExternCContext() &&
21918       !CurLexicalContext->isExternCXXContext() &&
21919       !isa<CXXRecordDecl>(CurLexicalContext) &&
21920       !isa<ClassTemplateDecl>(CurLexicalContext) &&
21921       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
21922       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
21923     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
21924     return false;
21925   }
21926   DeclareTargetNesting.push_back(DTCI);
21927   return true;
21928 }
21929 
21930 const Sema::DeclareTargetContextInfo
21931 Sema::ActOnOpenMPEndDeclareTargetDirective() {
21932   assert(!DeclareTargetNesting.empty() &&
21933          "check isInOpenMPDeclareTargetContext() first!");
21934   return DeclareTargetNesting.pop_back_val();
21935 }
21936 
21937 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
21938     DeclareTargetContextInfo &DTCI) {
21939   for (auto &It : DTCI.ExplicitlyMapped)
21940     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI);
21941 }
21942 
21943 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
21944                                                CXXScopeSpec &ScopeSpec,
21945                                                const DeclarationNameInfo &Id) {
21946   LookupResult Lookup(*this, Id, LookupOrdinaryName);
21947   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
21948 
21949   if (Lookup.isAmbiguous())
21950     return nullptr;
21951   Lookup.suppressDiagnostics();
21952 
21953   if (!Lookup.isSingleResult()) {
21954     VarOrFuncDeclFilterCCC CCC(*this);
21955     if (TypoCorrection Corrected =
21956             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
21957                         CTK_ErrorRecovery)) {
21958       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
21959                                   << Id.getName());
21960       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
21961       return nullptr;
21962     }
21963 
21964     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
21965     return nullptr;
21966   }
21967 
21968   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
21969   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
21970       !isa<FunctionTemplateDecl>(ND)) {
21971     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
21972     return nullptr;
21973   }
21974   return ND;
21975 }
21976 
21977 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
21978                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
21979                                         DeclareTargetContextInfo &DTCI) {
21980   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
21981           isa<FunctionTemplateDecl>(ND)) &&
21982          "Expected variable, function or function template.");
21983 
21984   // Diagnose marking after use as it may lead to incorrect diagnosis and
21985   // codegen.
21986   if (LangOpts.OpenMP >= 50 &&
21987       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
21988     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
21989 
21990   // Explicit declare target lists have precedence.
21991   const unsigned Level = -1;
21992 
21993   auto *VD = cast<ValueDecl>(ND);
21994   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
21995       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
21996   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT &&
21997       ActiveAttr.getValue()->getLevel() == Level) {
21998     Diag(Loc, diag::err_omp_device_type_mismatch)
21999         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
22000         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
22001                ActiveAttr.getValue()->getDevType());
22002     return;
22003   }
22004   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
22005       ActiveAttr.getValue()->getLevel() == Level) {
22006     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
22007     return;
22008   }
22009 
22010   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
22011     return;
22012 
22013   Expr *IndirectE = nullptr;
22014   bool IsIndirect = false;
22015   if (DTCI.Indirect.hasValue()) {
22016     IndirectE = DTCI.Indirect.getValue();
22017     if (!IndirectE)
22018       IsIndirect = true;
22019   }
22020   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
22021       Context, MT, DTCI.DT, IndirectE, IsIndirect, Level,
22022       SourceRange(Loc, Loc));
22023   ND->addAttr(A);
22024   if (ASTMutationListener *ML = Context.getASTMutationListener())
22025     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
22026   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
22027 }
22028 
22029 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
22030                                      Sema &SemaRef, Decl *D) {
22031   if (!D || !isa<VarDecl>(D))
22032     return;
22033   auto *VD = cast<VarDecl>(D);
22034   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
22035       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
22036   if (SemaRef.LangOpts.OpenMP >= 50 &&
22037       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
22038        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
22039       VD->hasGlobalStorage()) {
22040     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
22041       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
22042       // If a lambda declaration and definition appears between a
22043       // declare target directive and the matching end declare target
22044       // directive, all variables that are captured by the lambda
22045       // expression must also appear in a to clause.
22046       SemaRef.Diag(VD->getLocation(),
22047                    diag::err_omp_lambda_capture_in_declare_target_not_to);
22048       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
22049           << VD << 0 << SR;
22050       return;
22051     }
22052   }
22053   if (MapTy.hasValue())
22054     return;
22055   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
22056   SemaRef.Diag(SL, diag::note_used_here) << SR;
22057 }
22058 
22059 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
22060                                    Sema &SemaRef, DSAStackTy *Stack,
22061                                    ValueDecl *VD) {
22062   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
22063          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
22064                            /*FullCheck=*/false);
22065 }
22066 
22067 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
22068                                             SourceLocation IdLoc) {
22069   if (!D || D->isInvalidDecl())
22070     return;
22071   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
22072   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
22073   if (auto *VD = dyn_cast<VarDecl>(D)) {
22074     // Only global variables can be marked as declare target.
22075     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
22076         !VD->isStaticDataMember())
22077       return;
22078     // 2.10.6: threadprivate variable cannot appear in a declare target
22079     // directive.
22080     if (DSAStack->isThreadPrivate(VD)) {
22081       Diag(SL, diag::err_omp_threadprivate_in_target);
22082       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
22083       return;
22084     }
22085   }
22086   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
22087     D = FTD->getTemplatedDecl();
22088   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
22089     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
22090         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
22091     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
22092       Diag(IdLoc, diag::err_omp_function_in_link_clause);
22093       Diag(FD->getLocation(), diag::note_defined_here) << FD;
22094       return;
22095     }
22096   }
22097   if (auto *VD = dyn_cast<ValueDecl>(D)) {
22098     // Problem if any with var declared with incomplete type will be reported
22099     // as normal, so no need to check it here.
22100     if ((E || !VD->getType()->isIncompleteType()) &&
22101         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
22102       return;
22103     if (!E && isInOpenMPDeclareTargetContext()) {
22104       // Checking declaration inside declare target region.
22105       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
22106           isa<FunctionTemplateDecl>(D)) {
22107         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
22108             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
22109         unsigned Level = DeclareTargetNesting.size();
22110         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
22111           return;
22112         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
22113         Expr *IndirectE = nullptr;
22114         bool IsIndirect = false;
22115         if (DTCI.Indirect.hasValue()) {
22116           IndirectE = DTCI.Indirect.getValue();
22117           if (!IndirectE)
22118             IsIndirect = true;
22119         }
22120         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
22121             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE,
22122             IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc));
22123         D->addAttr(A);
22124         if (ASTMutationListener *ML = Context.getASTMutationListener())
22125           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
22126       }
22127       return;
22128     }
22129   }
22130   if (!E)
22131     return;
22132   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
22133 }
22134 
22135 OMPClause *Sema::ActOnOpenMPToClause(
22136     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
22137     ArrayRef<SourceLocation> MotionModifiersLoc,
22138     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
22139     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
22140     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
22141   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
22142                                           OMPC_MOTION_MODIFIER_unknown};
22143   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
22144 
22145   // Process motion-modifiers, flag errors for duplicate modifiers.
22146   unsigned Count = 0;
22147   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
22148     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
22149         llvm::is_contained(Modifiers, MotionModifiers[I])) {
22150       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
22151       continue;
22152     }
22153     assert(Count < NumberOfOMPMotionModifiers &&
22154            "Modifiers exceed the allowed number of motion modifiers");
22155     Modifiers[Count] = MotionModifiers[I];
22156     ModifiersLoc[Count] = MotionModifiersLoc[I];
22157     ++Count;
22158   }
22159 
22160   MappableVarListInfo MVLI(VarList);
22161   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
22162                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
22163   if (MVLI.ProcessedVarList.empty())
22164     return nullptr;
22165 
22166   return OMPToClause::Create(
22167       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
22168       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
22169       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
22170 }
22171 
22172 OMPClause *Sema::ActOnOpenMPFromClause(
22173     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
22174     ArrayRef<SourceLocation> MotionModifiersLoc,
22175     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
22176     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
22177     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
22178   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
22179                                           OMPC_MOTION_MODIFIER_unknown};
22180   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
22181 
22182   // Process motion-modifiers, flag errors for duplicate modifiers.
22183   unsigned Count = 0;
22184   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
22185     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
22186         llvm::is_contained(Modifiers, MotionModifiers[I])) {
22187       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
22188       continue;
22189     }
22190     assert(Count < NumberOfOMPMotionModifiers &&
22191            "Modifiers exceed the allowed number of motion modifiers");
22192     Modifiers[Count] = MotionModifiers[I];
22193     ModifiersLoc[Count] = MotionModifiersLoc[I];
22194     ++Count;
22195   }
22196 
22197   MappableVarListInfo MVLI(VarList);
22198   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
22199                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
22200   if (MVLI.ProcessedVarList.empty())
22201     return nullptr;
22202 
22203   return OMPFromClause::Create(
22204       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
22205       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
22206       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
22207 }
22208 
22209 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
22210                                                const OMPVarListLocTy &Locs) {
22211   MappableVarListInfo MVLI(VarList);
22212   SmallVector<Expr *, 8> PrivateCopies;
22213   SmallVector<Expr *, 8> Inits;
22214 
22215   for (Expr *RefExpr : VarList) {
22216     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
22217     SourceLocation ELoc;
22218     SourceRange ERange;
22219     Expr *SimpleRefExpr = RefExpr;
22220     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22221     if (Res.second) {
22222       // It will be analyzed later.
22223       MVLI.ProcessedVarList.push_back(RefExpr);
22224       PrivateCopies.push_back(nullptr);
22225       Inits.push_back(nullptr);
22226     }
22227     ValueDecl *D = Res.first;
22228     if (!D)
22229       continue;
22230 
22231     QualType Type = D->getType();
22232     Type = Type.getNonReferenceType().getUnqualifiedType();
22233 
22234     auto *VD = dyn_cast<VarDecl>(D);
22235 
22236     // Item should be a pointer or reference to pointer.
22237     if (!Type->isPointerType()) {
22238       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
22239           << 0 << RefExpr->getSourceRange();
22240       continue;
22241     }
22242 
22243     // Build the private variable and the expression that refers to it.
22244     auto VDPrivate =
22245         buildVarDecl(*this, ELoc, Type, D->getName(),
22246                      D->hasAttrs() ? &D->getAttrs() : nullptr,
22247                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
22248     if (VDPrivate->isInvalidDecl())
22249       continue;
22250 
22251     CurContext->addDecl(VDPrivate);
22252     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
22253         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
22254 
22255     // Add temporary variable to initialize the private copy of the pointer.
22256     VarDecl *VDInit =
22257         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
22258     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
22259         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
22260     AddInitializerToDecl(VDPrivate,
22261                          DefaultLvalueConversion(VDInitRefExpr).get(),
22262                          /*DirectInit=*/false);
22263 
22264     // If required, build a capture to implement the privatization initialized
22265     // with the current list item value.
22266     DeclRefExpr *Ref = nullptr;
22267     if (!VD)
22268       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
22269     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
22270     PrivateCopies.push_back(VDPrivateRefExpr);
22271     Inits.push_back(VDInitRefExpr);
22272 
22273     // We need to add a data sharing attribute for this variable to make sure it
22274     // is correctly captured. A variable that shows up in a use_device_ptr has
22275     // similar properties of a first private variable.
22276     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
22277 
22278     // Create a mappable component for the list item. List items in this clause
22279     // only need a component.
22280     MVLI.VarBaseDeclarations.push_back(D);
22281     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
22282     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
22283                                            /*IsNonContiguous=*/false);
22284   }
22285 
22286   if (MVLI.ProcessedVarList.empty())
22287     return nullptr;
22288 
22289   return OMPUseDevicePtrClause::Create(
22290       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
22291       MVLI.VarBaseDeclarations, MVLI.VarComponents);
22292 }
22293 
22294 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
22295                                                 const OMPVarListLocTy &Locs) {
22296   MappableVarListInfo MVLI(VarList);
22297 
22298   for (Expr *RefExpr : VarList) {
22299     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
22300     SourceLocation ELoc;
22301     SourceRange ERange;
22302     Expr *SimpleRefExpr = RefExpr;
22303     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22304                               /*AllowArraySection=*/true);
22305     if (Res.second) {
22306       // It will be analyzed later.
22307       MVLI.ProcessedVarList.push_back(RefExpr);
22308     }
22309     ValueDecl *D = Res.first;
22310     if (!D)
22311       continue;
22312     auto *VD = dyn_cast<VarDecl>(D);
22313 
22314     // If required, build a capture to implement the privatization initialized
22315     // with the current list item value.
22316     DeclRefExpr *Ref = nullptr;
22317     if (!VD)
22318       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
22319     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
22320 
22321     // We need to add a data sharing attribute for this variable to make sure it
22322     // is correctly captured. A variable that shows up in a use_device_addr has
22323     // similar properties of a first private variable.
22324     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
22325 
22326     // Create a mappable component for the list item. List items in this clause
22327     // only need a component.
22328     MVLI.VarBaseDeclarations.push_back(D);
22329     MVLI.VarComponents.emplace_back();
22330     Expr *Component = SimpleRefExpr;
22331     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
22332                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
22333       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
22334     MVLI.VarComponents.back().emplace_back(Component, D,
22335                                            /*IsNonContiguous=*/false);
22336   }
22337 
22338   if (MVLI.ProcessedVarList.empty())
22339     return nullptr;
22340 
22341   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
22342                                         MVLI.VarBaseDeclarations,
22343                                         MVLI.VarComponents);
22344 }
22345 
22346 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
22347                                               const OMPVarListLocTy &Locs) {
22348   MappableVarListInfo MVLI(VarList);
22349   for (Expr *RefExpr : VarList) {
22350     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
22351     SourceLocation ELoc;
22352     SourceRange ERange;
22353     Expr *SimpleRefExpr = RefExpr;
22354     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22355     if (Res.second) {
22356       // It will be analyzed later.
22357       MVLI.ProcessedVarList.push_back(RefExpr);
22358     }
22359     ValueDecl *D = Res.first;
22360     if (!D)
22361       continue;
22362 
22363     QualType Type = D->getType();
22364     // item should be a pointer or array or reference to pointer or array
22365     if (!Type.getNonReferenceType()->isPointerType() &&
22366         !Type.getNonReferenceType()->isArrayType()) {
22367       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
22368           << 0 << RefExpr->getSourceRange();
22369       continue;
22370     }
22371 
22372     // Check if the declaration in the clause does not show up in any data
22373     // sharing attribute.
22374     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
22375     if (isOpenMPPrivate(DVar.CKind)) {
22376       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
22377           << getOpenMPClauseName(DVar.CKind)
22378           << getOpenMPClauseName(OMPC_is_device_ptr)
22379           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
22380       reportOriginalDsa(*this, DSAStack, D, DVar);
22381       continue;
22382     }
22383 
22384     const Expr *ConflictExpr;
22385     if (DSAStack->checkMappableExprComponentListsForDecl(
22386             D, /*CurrentRegionOnly=*/true,
22387             [&ConflictExpr](
22388                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
22389                 OpenMPClauseKind) -> bool {
22390               ConflictExpr = R.front().getAssociatedExpression();
22391               return true;
22392             })) {
22393       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
22394       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
22395           << ConflictExpr->getSourceRange();
22396       continue;
22397     }
22398 
22399     // Store the components in the stack so that they can be used to check
22400     // against other clauses later on.
22401     OMPClauseMappableExprCommon::MappableComponent MC(
22402         SimpleRefExpr, D, /*IsNonContiguous=*/false);
22403     DSAStack->addMappableExpressionComponents(
22404         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
22405 
22406     // Record the expression we've just processed.
22407     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
22408 
22409     // Create a mappable component for the list item. List items in this clause
22410     // only need a component. We use a null declaration to signal fields in
22411     // 'this'.
22412     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
22413             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
22414            "Unexpected device pointer expression!");
22415     MVLI.VarBaseDeclarations.push_back(
22416         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
22417     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
22418     MVLI.VarComponents.back().push_back(MC);
22419   }
22420 
22421   if (MVLI.ProcessedVarList.empty())
22422     return nullptr;
22423 
22424   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
22425                                       MVLI.VarBaseDeclarations,
22426                                       MVLI.VarComponents);
22427 }
22428 
22429 OMPClause *Sema::ActOnOpenMPAllocateClause(
22430     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
22431     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
22432   if (Allocator) {
22433     // OpenMP [2.11.4 allocate Clause, Description]
22434     // allocator is an expression of omp_allocator_handle_t type.
22435     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
22436       return nullptr;
22437 
22438     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
22439     if (AllocatorRes.isInvalid())
22440       return nullptr;
22441     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
22442                                              DSAStack->getOMPAllocatorHandleT(),
22443                                              Sema::AA_Initializing,
22444                                              /*AllowExplicit=*/true);
22445     if (AllocatorRes.isInvalid())
22446       return nullptr;
22447     Allocator = AllocatorRes.get();
22448   } else {
22449     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
22450     // allocate clauses that appear on a target construct or on constructs in a
22451     // target region must specify an allocator expression unless a requires
22452     // directive with the dynamic_allocators clause is present in the same
22453     // compilation unit.
22454     if (LangOpts.OpenMPIsDevice &&
22455         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
22456       targetDiag(StartLoc, diag::err_expected_allocator_expression);
22457   }
22458   // Analyze and build list of variables.
22459   SmallVector<Expr *, 8> Vars;
22460   for (Expr *RefExpr : VarList) {
22461     assert(RefExpr && "NULL expr in OpenMP private clause.");
22462     SourceLocation ELoc;
22463     SourceRange ERange;
22464     Expr *SimpleRefExpr = RefExpr;
22465     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22466     if (Res.second) {
22467       // It will be analyzed later.
22468       Vars.push_back(RefExpr);
22469     }
22470     ValueDecl *D = Res.first;
22471     if (!D)
22472       continue;
22473 
22474     auto *VD = dyn_cast<VarDecl>(D);
22475     DeclRefExpr *Ref = nullptr;
22476     if (!VD && !CurContext->isDependentContext())
22477       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
22478     Vars.push_back((VD || CurContext->isDependentContext())
22479                        ? RefExpr->IgnoreParens()
22480                        : Ref);
22481   }
22482 
22483   if (Vars.empty())
22484     return nullptr;
22485 
22486   if (Allocator)
22487     DSAStack->addInnerAllocatorExpr(Allocator);
22488   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
22489                                    ColonLoc, EndLoc, Vars);
22490 }
22491 
22492 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
22493                                               SourceLocation StartLoc,
22494                                               SourceLocation LParenLoc,
22495                                               SourceLocation EndLoc) {
22496   SmallVector<Expr *, 8> Vars;
22497   for (Expr *RefExpr : VarList) {
22498     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
22499     SourceLocation ELoc;
22500     SourceRange ERange;
22501     Expr *SimpleRefExpr = RefExpr;
22502     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22503     if (Res.second)
22504       // It will be analyzed later.
22505       Vars.push_back(RefExpr);
22506     ValueDecl *D = Res.first;
22507     if (!D)
22508       continue;
22509 
22510     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
22511     // A list-item cannot appear in more than one nontemporal clause.
22512     if (const Expr *PrevRef =
22513             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
22514       Diag(ELoc, diag::err_omp_used_in_clause_twice)
22515           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
22516       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
22517           << getOpenMPClauseName(OMPC_nontemporal);
22518       continue;
22519     }
22520 
22521     Vars.push_back(RefExpr);
22522   }
22523 
22524   if (Vars.empty())
22525     return nullptr;
22526 
22527   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
22528                                       Vars);
22529 }
22530 
22531 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
22532                                             SourceLocation StartLoc,
22533                                             SourceLocation LParenLoc,
22534                                             SourceLocation EndLoc) {
22535   SmallVector<Expr *, 8> Vars;
22536   for (Expr *RefExpr : VarList) {
22537     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
22538     SourceLocation ELoc;
22539     SourceRange ERange;
22540     Expr *SimpleRefExpr = RefExpr;
22541     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22542                               /*AllowArraySection=*/true);
22543     if (Res.second)
22544       // It will be analyzed later.
22545       Vars.push_back(RefExpr);
22546     ValueDecl *D = Res.first;
22547     if (!D)
22548       continue;
22549 
22550     const DSAStackTy::DSAVarData DVar =
22551         DSAStack->getTopDSA(D, /*FromParent=*/true);
22552     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
22553     // A list item that appears in the inclusive or exclusive clause must appear
22554     // in a reduction clause with the inscan modifier on the enclosing
22555     // worksharing-loop, worksharing-loop SIMD, or simd construct.
22556     if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
22557       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
22558           << RefExpr->getSourceRange();
22559 
22560     if (DSAStack->getParentDirective() != OMPD_unknown)
22561       DSAStack->markDeclAsUsedInScanDirective(D);
22562     Vars.push_back(RefExpr);
22563   }
22564 
22565   if (Vars.empty())
22566     return nullptr;
22567 
22568   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
22569 }
22570 
22571 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
22572                                             SourceLocation StartLoc,
22573                                             SourceLocation LParenLoc,
22574                                             SourceLocation EndLoc) {
22575   SmallVector<Expr *, 8> Vars;
22576   for (Expr *RefExpr : VarList) {
22577     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
22578     SourceLocation ELoc;
22579     SourceRange ERange;
22580     Expr *SimpleRefExpr = RefExpr;
22581     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22582                               /*AllowArraySection=*/true);
22583     if (Res.second)
22584       // It will be analyzed later.
22585       Vars.push_back(RefExpr);
22586     ValueDecl *D = Res.first;
22587     if (!D)
22588       continue;
22589 
22590     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
22591     DSAStackTy::DSAVarData DVar;
22592     if (ParentDirective != OMPD_unknown)
22593       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
22594     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
22595     // A list item that appears in the inclusive or exclusive clause must appear
22596     // in a reduction clause with the inscan modifier on the enclosing
22597     // worksharing-loop, worksharing-loop SIMD, or simd construct.
22598     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
22599         DVar.Modifier != OMPC_REDUCTION_inscan) {
22600       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
22601           << RefExpr->getSourceRange();
22602     } else {
22603       DSAStack->markDeclAsUsedInScanDirective(D);
22604     }
22605     Vars.push_back(RefExpr);
22606   }
22607 
22608   if (Vars.empty())
22609     return nullptr;
22610 
22611   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
22612 }
22613 
22614 /// Tries to find omp_alloctrait_t type.
22615 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
22616   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
22617   if (!OMPAlloctraitT.isNull())
22618     return true;
22619   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
22620   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
22621   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
22622     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
22623     return false;
22624   }
22625   Stack->setOMPAlloctraitT(PT.get());
22626   return true;
22627 }
22628 
22629 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
22630     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
22631     ArrayRef<UsesAllocatorsData> Data) {
22632   // OpenMP [2.12.5, target Construct]
22633   // allocator is an identifier of omp_allocator_handle_t type.
22634   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
22635     return nullptr;
22636   // OpenMP [2.12.5, target Construct]
22637   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
22638   if (llvm::any_of(
22639           Data,
22640           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
22641       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
22642     return nullptr;
22643   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
22644   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
22645     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
22646     StringRef Allocator =
22647         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
22648     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
22649     PredefinedAllocators.insert(LookupSingleName(
22650         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
22651   }
22652 
22653   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
22654   for (const UsesAllocatorsData &D : Data) {
22655     Expr *AllocatorExpr = nullptr;
22656     // Check allocator expression.
22657     if (D.Allocator->isTypeDependent()) {
22658       AllocatorExpr = D.Allocator;
22659     } else {
22660       // Traits were specified - need to assign new allocator to the specified
22661       // allocator, so it must be an lvalue.
22662       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
22663       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
22664       bool IsPredefinedAllocator = false;
22665       if (DRE)
22666         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
22667       if (!DRE ||
22668           !(Context.hasSameUnqualifiedType(
22669                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
22670             Context.typesAreCompatible(AllocatorExpr->getType(),
22671                                        DSAStack->getOMPAllocatorHandleT(),
22672                                        /*CompareUnqualified=*/true)) ||
22673           (!IsPredefinedAllocator &&
22674            (AllocatorExpr->getType().isConstant(Context) ||
22675             !AllocatorExpr->isLValue()))) {
22676         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
22677             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
22678             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
22679         continue;
22680       }
22681       // OpenMP [2.12.5, target Construct]
22682       // Predefined allocators appearing in a uses_allocators clause cannot have
22683       // traits specified.
22684       if (IsPredefinedAllocator && D.AllocatorTraits) {
22685         Diag(D.AllocatorTraits->getExprLoc(),
22686              diag::err_omp_predefined_allocator_with_traits)
22687             << D.AllocatorTraits->getSourceRange();
22688         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
22689             << cast<NamedDecl>(DRE->getDecl())->getName()
22690             << D.Allocator->getSourceRange();
22691         continue;
22692       }
22693       // OpenMP [2.12.5, target Construct]
22694       // Non-predefined allocators appearing in a uses_allocators clause must
22695       // have traits specified.
22696       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
22697         Diag(D.Allocator->getExprLoc(),
22698              diag::err_omp_nonpredefined_allocator_without_traits);
22699         continue;
22700       }
22701       // No allocator traits - just convert it to rvalue.
22702       if (!D.AllocatorTraits)
22703         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
22704       DSAStack->addUsesAllocatorsDecl(
22705           DRE->getDecl(),
22706           IsPredefinedAllocator
22707               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
22708               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
22709     }
22710     Expr *AllocatorTraitsExpr = nullptr;
22711     if (D.AllocatorTraits) {
22712       if (D.AllocatorTraits->isTypeDependent()) {
22713         AllocatorTraitsExpr = D.AllocatorTraits;
22714       } else {
22715         // OpenMP [2.12.5, target Construct]
22716         // Arrays that contain allocator traits that appear in a uses_allocators
22717         // clause must be constant arrays, have constant values and be defined
22718         // in the same scope as the construct in which the clause appears.
22719         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
22720         // Check that traits expr is a constant array.
22721         QualType TraitTy;
22722         if (const ArrayType *Ty =
22723                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
22724           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
22725             TraitTy = ConstArrayTy->getElementType();
22726         if (TraitTy.isNull() ||
22727             !(Context.hasSameUnqualifiedType(TraitTy,
22728                                              DSAStack->getOMPAlloctraitT()) ||
22729               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
22730                                          /*CompareUnqualified=*/true))) {
22731           Diag(D.AllocatorTraits->getExprLoc(),
22732                diag::err_omp_expected_array_alloctraits)
22733               << AllocatorTraitsExpr->getType();
22734           continue;
22735         }
22736         // Do not map by default allocator traits if it is a standalone
22737         // variable.
22738         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
22739           DSAStack->addUsesAllocatorsDecl(
22740               DRE->getDecl(),
22741               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
22742       }
22743     }
22744     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
22745     NewD.Allocator = AllocatorExpr;
22746     NewD.AllocatorTraits = AllocatorTraitsExpr;
22747     NewD.LParenLoc = D.LParenLoc;
22748     NewD.RParenLoc = D.RParenLoc;
22749   }
22750   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
22751                                          NewData);
22752 }
22753 
22754 OMPClause *Sema::ActOnOpenMPAffinityClause(
22755     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
22756     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
22757   SmallVector<Expr *, 8> Vars;
22758   for (Expr *RefExpr : Locators) {
22759     assert(RefExpr && "NULL expr in OpenMP shared clause.");
22760     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
22761       // It will be analyzed later.
22762       Vars.push_back(RefExpr);
22763       continue;
22764     }
22765 
22766     SourceLocation ELoc = RefExpr->getExprLoc();
22767     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
22768 
22769     if (!SimpleExpr->isLValue()) {
22770       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
22771           << 1 << 0 << RefExpr->getSourceRange();
22772       continue;
22773     }
22774 
22775     ExprResult Res;
22776     {
22777       Sema::TentativeAnalysisScope Trap(*this);
22778       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
22779     }
22780     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
22781         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
22782       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
22783           << 1 << 0 << RefExpr->getSourceRange();
22784       continue;
22785     }
22786     Vars.push_back(SimpleExpr);
22787   }
22788 
22789   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
22790                                    EndLoc, Modifier, Vars);
22791 }
22792 
22793 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
22794                                        SourceLocation KindLoc,
22795                                        SourceLocation StartLoc,
22796                                        SourceLocation LParenLoc,
22797                                        SourceLocation EndLoc) {
22798   if (Kind == OMPC_BIND_unknown) {
22799     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
22800         << getListOfPossibleValues(OMPC_bind, /*First=*/0,
22801                                    /*Last=*/unsigned(OMPC_BIND_unknown))
22802         << getOpenMPClauseName(OMPC_bind);
22803     return nullptr;
22804   }
22805 
22806   return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
22807                                EndLoc);
22808 }
22809