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_private = 1 << 2,      /// Default data sharing attribute 'private'.
63   DSA_firstprivate = 1 << 3, /// Default data sharing attribute 'firstprivate'.
64 };
65 
66 /// Stack for tracking declarations used in OpenMP directives and
67 /// clauses and their data-sharing attributes.
68 class DSAStackTy {
69 public:
70   struct DSAVarData {
71     OpenMPDirectiveKind DKind = OMPD_unknown;
72     OpenMPClauseKind CKind = OMPC_unknown;
73     unsigned Modifier = 0;
74     const Expr *RefExpr = nullptr;
75     DeclRefExpr *PrivateCopy = nullptr;
76     SourceLocation ImplicitDSALoc;
77     bool AppliedToPointee = false;
78     DSAVarData() = default;
79     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
80                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
81                SourceLocation ImplicitDSALoc, unsigned Modifier,
82                bool AppliedToPointee)
83         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
84           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
85           AppliedToPointee(AppliedToPointee) {}
86   };
87   using OperatorOffsetTy =
88       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
89   using DoacrossDependMapTy =
90       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
91   /// Kind of the declaration used in the uses_allocators clauses.
92   enum class UsesAllocatorsDeclKind {
93     /// Predefined allocator
94     PredefinedAllocator,
95     /// User-defined allocator
96     UserDefinedAllocator,
97     /// The declaration that represent allocator trait
98     AllocatorTrait,
99   };
100 
101 private:
102   struct DSAInfo {
103     OpenMPClauseKind Attributes = OMPC_unknown;
104     unsigned Modifier = 0;
105     /// Pointer to a reference expression and a flag which shows that the
106     /// variable is marked as lastprivate(true) or not (false).
107     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
108     DeclRefExpr *PrivateCopy = nullptr;
109     /// true if the attribute is applied to the pointee, not the variable
110     /// itself.
111     bool AppliedToPointee = false;
112   };
113   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
114   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
115   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
116   using LoopControlVariablesMapTy =
117       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
118   /// Struct that associates a component with the clause kind where they are
119   /// found.
120   struct MappedExprComponentTy {
121     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
122     OpenMPClauseKind Kind = OMPC_unknown;
123   };
124   using MappedExprComponentsTy =
125       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
126   using CriticalsWithHintsTy =
127       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
128   struct ReductionData {
129     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
130     SourceRange ReductionRange;
131     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
132     ReductionData() = default;
133     void set(BinaryOperatorKind BO, SourceRange RR) {
134       ReductionRange = RR;
135       ReductionOp = BO;
136     }
137     void set(const Expr *RefExpr, SourceRange RR) {
138       ReductionRange = RR;
139       ReductionOp = RefExpr;
140     }
141   };
142   using DeclReductionMapTy =
143       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
144   struct DefaultmapInfo {
145     OpenMPDefaultmapClauseModifier ImplicitBehavior =
146         OMPC_DEFAULTMAP_MODIFIER_unknown;
147     SourceLocation SLoc;
148     DefaultmapInfo() = default;
149     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
150         : ImplicitBehavior(M), SLoc(Loc) {}
151   };
152 
153   struct SharingMapTy {
154     DeclSAMapTy SharingMap;
155     DeclReductionMapTy ReductionMap;
156     UsedRefMapTy AlignedMap;
157     UsedRefMapTy NontemporalMap;
158     MappedExprComponentsTy MappedExprComponents;
159     LoopControlVariablesMapTy LCVMap;
160     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
161     SourceLocation DefaultAttrLoc;
162     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
163     OpenMPDirectiveKind Directive = OMPD_unknown;
164     DeclarationNameInfo DirectiveName;
165     Scope *CurScope = nullptr;
166     DeclContext *Context = nullptr;
167     SourceLocation ConstructLoc;
168     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
169     /// get the data (loop counters etc.) about enclosing loop-based construct.
170     /// This data is required during codegen.
171     DoacrossDependMapTy DoacrossDepends;
172     /// First argument (Expr *) contains optional argument of the
173     /// 'ordered' clause, the second one is true if the regions has 'ordered'
174     /// clause, false otherwise.
175     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
176     unsigned AssociatedLoops = 1;
177     bool HasMutipleLoops = false;
178     const Decl *PossiblyLoopCounter = nullptr;
179     bool NowaitRegion = false;
180     bool UntiedRegion = false;
181     bool CancelRegion = false;
182     bool LoopStart = false;
183     bool BodyComplete = false;
184     SourceLocation PrevScanLocation;
185     SourceLocation PrevOrderedLocation;
186     SourceLocation InnerTeamsRegionLoc;
187     /// Reference to the taskgroup task_reduction reference expression.
188     Expr *TaskgroupReductionRef = nullptr;
189     llvm::DenseSet<QualType> MappedClassesQualTypes;
190     SmallVector<Expr *, 4> InnerUsedAllocators;
191     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
192     /// List of globals marked as declare target link in this target region
193     /// (isOpenMPTargetExecutionDirective(Directive) == true).
194     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
195     /// List of decls used in inclusive/exclusive clauses of the scan directive.
196     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
197     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
198         UsesAllocatorsDecls;
199     Expr *DeclareMapperVar = nullptr;
200     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
201                  Scope *CurScope, SourceLocation Loc)
202         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
203           ConstructLoc(Loc) {}
204     SharingMapTy() = default;
205   };
206 
207   using StackTy = SmallVector<SharingMapTy, 4>;
208 
209   /// Stack of used declaration and their data-sharing attributes.
210   DeclSAMapTy Threadprivates;
211   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
212   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
213   /// true, if check for DSA must be from parent directive, false, if
214   /// from current directive.
215   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
216   Sema &SemaRef;
217   bool ForceCapturing = false;
218   /// true if all the variables in the target executable directives must be
219   /// captured by reference.
220   bool ForceCaptureByReferenceInTargetExecutable = false;
221   CriticalsWithHintsTy Criticals;
222   unsigned IgnoredStackElements = 0;
223 
224   /// Iterators over the stack iterate in order from innermost to outermost
225   /// directive.
226   using const_iterator = StackTy::const_reverse_iterator;
227   const_iterator begin() const {
228     return Stack.empty() ? const_iterator()
229                          : Stack.back().first.rbegin() + IgnoredStackElements;
230   }
231   const_iterator end() const {
232     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
233   }
234   using iterator = StackTy::reverse_iterator;
235   iterator begin() {
236     return Stack.empty() ? iterator()
237                          : Stack.back().first.rbegin() + IgnoredStackElements;
238   }
239   iterator end() {
240     return Stack.empty() ? iterator() : Stack.back().first.rend();
241   }
242 
243   // Convenience operations to get at the elements of the stack.
244 
245   bool isStackEmpty() const {
246     return Stack.empty() ||
247            Stack.back().second != CurrentNonCapturingFunctionScope ||
248            Stack.back().first.size() <= IgnoredStackElements;
249   }
250   size_t getStackSize() const {
251     return isStackEmpty() ? 0
252                           : Stack.back().first.size() - IgnoredStackElements;
253   }
254 
255   SharingMapTy *getTopOfStackOrNull() {
256     size_t Size = getStackSize();
257     if (Size == 0)
258       return nullptr;
259     return &Stack.back().first[Size - 1];
260   }
261   const SharingMapTy *getTopOfStackOrNull() const {
262     return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
263   }
264   SharingMapTy &getTopOfStack() {
265     assert(!isStackEmpty() && "no current directive");
266     return *getTopOfStackOrNull();
267   }
268   const SharingMapTy &getTopOfStack() const {
269     return const_cast<DSAStackTy &>(*this).getTopOfStack();
270   }
271 
272   SharingMapTy *getSecondOnStackOrNull() {
273     size_t Size = getStackSize();
274     if (Size <= 1)
275       return nullptr;
276     return &Stack.back().first[Size - 2];
277   }
278   const SharingMapTy *getSecondOnStackOrNull() const {
279     return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
280   }
281 
282   /// Get the stack element at a certain level (previously returned by
283   /// \c getNestingLevel).
284   ///
285   /// Note that nesting levels count from outermost to innermost, and this is
286   /// the reverse of our iteration order where new inner levels are pushed at
287   /// the front of the stack.
288   SharingMapTy &getStackElemAtLevel(unsigned Level) {
289     assert(Level < getStackSize() && "no such stack element");
290     return Stack.back().first[Level];
291   }
292   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
293     return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
294   }
295 
296   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
297 
298   /// Checks if the variable is a local for OpenMP region.
299   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
300 
301   /// Vector of previously declared requires directives
302   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
303   /// omp_allocator_handle_t type.
304   QualType OMPAllocatorHandleT;
305   /// omp_depend_t type.
306   QualType OMPDependT;
307   /// omp_event_handle_t type.
308   QualType OMPEventHandleT;
309   /// omp_alloctrait_t type.
310   QualType OMPAlloctraitT;
311   /// Expression for the predefined allocators.
312   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
313       nullptr};
314   /// Vector of previously encountered target directives
315   SmallVector<SourceLocation, 2> TargetLocations;
316   SourceLocation AtomicLocation;
317   /// Vector of declare variant construct traits.
318   SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
319 
320 public:
321   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
322 
323   /// Sets omp_allocator_handle_t type.
324   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
325   /// Gets omp_allocator_handle_t type.
326   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
327   /// Sets omp_alloctrait_t type.
328   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
329   /// Gets omp_alloctrait_t type.
330   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
331   /// Sets the given default allocator.
332   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
333                     Expr *Allocator) {
334     OMPPredefinedAllocators[AllocatorKind] = Allocator;
335   }
336   /// Returns the specified default allocator.
337   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
338     return OMPPredefinedAllocators[AllocatorKind];
339   }
340   /// Sets omp_depend_t type.
341   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
342   /// Gets omp_depend_t type.
343   QualType getOMPDependT() const { return OMPDependT; }
344 
345   /// Sets omp_event_handle_t type.
346   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
347   /// Gets omp_event_handle_t type.
348   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
349 
350   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
351   OpenMPClauseKind getClauseParsingMode() const {
352     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
353     return ClauseKindMode;
354   }
355   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
356 
357   bool isBodyComplete() const {
358     const SharingMapTy *Top = getTopOfStackOrNull();
359     return Top && Top->BodyComplete;
360   }
361   void setBodyComplete() { getTopOfStack().BodyComplete = true; }
362 
363   bool isForceVarCapturing() const { return ForceCapturing; }
364   void setForceVarCapturing(bool V) { ForceCapturing = V; }
365 
366   void setForceCaptureByReferenceInTargetExecutable(bool V) {
367     ForceCaptureByReferenceInTargetExecutable = V;
368   }
369   bool isForceCaptureByReferenceInTargetExecutable() const {
370     return ForceCaptureByReferenceInTargetExecutable;
371   }
372 
373   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
374             Scope *CurScope, SourceLocation Loc) {
375     assert(!IgnoredStackElements &&
376            "cannot change stack while ignoring elements");
377     if (Stack.empty() ||
378         Stack.back().second != CurrentNonCapturingFunctionScope)
379       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
380     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
381     Stack.back().first.back().DefaultAttrLoc = Loc;
382   }
383 
384   void pop() {
385     assert(!IgnoredStackElements &&
386            "cannot change stack while ignoring elements");
387     assert(!Stack.back().first.empty() &&
388            "Data-sharing attributes stack is empty!");
389     Stack.back().first.pop_back();
390   }
391 
392   /// RAII object to temporarily leave the scope of a directive when we want to
393   /// logically operate in its parent.
394   class ParentDirectiveScope {
395     DSAStackTy &Self;
396     bool Active;
397 
398   public:
399     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
400         : Self(Self), Active(false) {
401       if (Activate)
402         enable();
403     }
404     ~ParentDirectiveScope() { disable(); }
405     void disable() {
406       if (Active) {
407         --Self.IgnoredStackElements;
408         Active = false;
409       }
410     }
411     void enable() {
412       if (!Active) {
413         ++Self.IgnoredStackElements;
414         Active = true;
415       }
416     }
417   };
418 
419   /// Marks that we're started loop parsing.
420   void loopInit() {
421     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
422            "Expected loop-based directive.");
423     getTopOfStack().LoopStart = true;
424   }
425   /// Start capturing of the variables in the loop context.
426   void loopStart() {
427     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
428            "Expected loop-based directive.");
429     getTopOfStack().LoopStart = false;
430   }
431   /// true, if variables are captured, false otherwise.
432   bool isLoopStarted() const {
433     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
434            "Expected loop-based directive.");
435     return !getTopOfStack().LoopStart;
436   }
437   /// Marks (or clears) declaration as possibly loop counter.
438   void resetPossibleLoopCounter(const Decl *D = nullptr) {
439     getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
440   }
441   /// Gets the possible loop counter decl.
442   const Decl *getPossiblyLoopCunter() const {
443     return getTopOfStack().PossiblyLoopCounter;
444   }
445   /// Start new OpenMP region stack in new non-capturing function.
446   void pushFunction() {
447     assert(!IgnoredStackElements &&
448            "cannot change stack while ignoring elements");
449     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
450     assert(!isa<CapturingScopeInfo>(CurFnScope));
451     CurrentNonCapturingFunctionScope = CurFnScope;
452   }
453   /// Pop region stack for non-capturing function.
454   void popFunction(const FunctionScopeInfo *OldFSI) {
455     assert(!IgnoredStackElements &&
456            "cannot change stack while ignoring elements");
457     if (!Stack.empty() && Stack.back().second == OldFSI) {
458       assert(Stack.back().first.empty());
459       Stack.pop_back();
460     }
461     CurrentNonCapturingFunctionScope = nullptr;
462     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
463       if (!isa<CapturingScopeInfo>(FSI)) {
464         CurrentNonCapturingFunctionScope = FSI;
465         break;
466       }
467     }
468   }
469 
470   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
471     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
472   }
473   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
474   getCriticalWithHint(const DeclarationNameInfo &Name) const {
475     auto I = Criticals.find(Name.getAsString());
476     if (I != Criticals.end())
477       return I->second;
478     return std::make_pair(nullptr, llvm::APSInt());
479   }
480   /// If 'aligned' declaration for given variable \a D was not seen yet,
481   /// add it and return NULL; otherwise return previous occurrence's expression
482   /// for diagnostics.
483   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
484   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
485   /// add it and return NULL; otherwise return previous occurrence's expression
486   /// for diagnostics.
487   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
488 
489   /// Register specified variable as loop control variable.
490   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
491   /// Check if the specified variable is a loop control variable for
492   /// current region.
493   /// \return The index of the loop control variable in the list of associated
494   /// for-loops (from outer to inner).
495   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
496   /// Check if the specified variable is a loop control variable for
497   /// parent region.
498   /// \return The index of the loop control variable in the list of associated
499   /// for-loops (from outer to inner).
500   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
501   /// Check if the specified variable is a loop control variable for
502   /// current region.
503   /// \return The index of the loop control variable in the list of associated
504   /// for-loops (from outer to inner).
505   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
506                                          unsigned Level) const;
507   /// Get the loop control variable for the I-th loop (or nullptr) in
508   /// parent directive.
509   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
510 
511   /// Marks the specified decl \p D as used in scan directive.
512   void markDeclAsUsedInScanDirective(ValueDecl *D) {
513     if (SharingMapTy *Stack = getSecondOnStackOrNull())
514       Stack->UsedInScanDirective.insert(D);
515   }
516 
517   /// Checks if the specified declaration was used in the inner scan directive.
518   bool isUsedInScanDirective(ValueDecl *D) const {
519     if (const SharingMapTy *Stack = getTopOfStackOrNull())
520       return Stack->UsedInScanDirective.contains(D);
521     return false;
522   }
523 
524   /// Adds explicit data sharing attribute to the specified declaration.
525   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
526               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
527               bool AppliedToPointee = false);
528 
529   /// Adds additional information for the reduction items with the reduction id
530   /// represented as an operator.
531   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
532                                  BinaryOperatorKind BOK);
533   /// Adds additional information for the reduction items with the reduction id
534   /// represented as reduction identifier.
535   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
536                                  const Expr *ReductionRef);
537   /// Returns the location and reduction operation from the innermost parent
538   /// region for the given \p D.
539   const DSAVarData
540   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
541                                    BinaryOperatorKind &BOK,
542                                    Expr *&TaskgroupDescriptor) const;
543   /// Returns the location and reduction operation from the innermost parent
544   /// region for the given \p D.
545   const DSAVarData
546   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
547                                    const Expr *&ReductionRef,
548                                    Expr *&TaskgroupDescriptor) const;
549   /// Return reduction reference expression for the current taskgroup or
550   /// parallel/worksharing directives with task reductions.
551   Expr *getTaskgroupReductionRef() const {
552     assert((getTopOfStack().Directive == OMPD_taskgroup ||
553             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
554               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
555              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
556            "taskgroup reference expression requested for non taskgroup or "
557            "parallel/worksharing directive.");
558     return getTopOfStack().TaskgroupReductionRef;
559   }
560   /// Checks if the given \p VD declaration is actually a taskgroup reduction
561   /// descriptor variable at the \p Level of OpenMP regions.
562   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
563     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
564            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
565                    ->getDecl() == VD;
566   }
567 
568   /// Returns data sharing attributes from top of the stack for the
569   /// specified declaration.
570   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
571   /// Returns data-sharing attributes for the specified declaration.
572   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
573   /// Returns data-sharing attributes for the specified declaration.
574   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
575   /// Checks if the specified variables has data-sharing attributes which
576   /// match specified \a CPred predicate in any directive which matches \a DPred
577   /// predicate.
578   const DSAVarData
579   hasDSA(ValueDecl *D,
580          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
581          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
582          bool FromParent) const;
583   /// Checks if the specified variables has data-sharing attributes which
584   /// match specified \a CPred predicate in any innermost directive which
585   /// matches \a DPred predicate.
586   const DSAVarData
587   hasInnermostDSA(ValueDecl *D,
588                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
589                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
590                   bool FromParent) const;
591   /// Checks if the specified variables has explicit data-sharing
592   /// attributes which match specified \a CPred predicate at the specified
593   /// OpenMP region.
594   bool
595   hasExplicitDSA(const ValueDecl *D,
596                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
597                  unsigned Level, bool NotLastprivate = false) const;
598 
599   /// Returns true if the directive at level \Level matches in the
600   /// specified \a DPred predicate.
601   bool hasExplicitDirective(
602       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
603       unsigned Level) const;
604 
605   /// Finds a directive which matches specified \a DPred predicate.
606   bool hasDirective(
607       const llvm::function_ref<bool(
608           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
609           DPred,
610       bool FromParent) const;
611 
612   /// Returns currently analyzed directive.
613   OpenMPDirectiveKind getCurrentDirective() const {
614     const SharingMapTy *Top = getTopOfStackOrNull();
615     return Top ? Top->Directive : OMPD_unknown;
616   }
617   /// Returns directive kind at specified level.
618   OpenMPDirectiveKind getDirective(unsigned Level) const {
619     assert(!isStackEmpty() && "No directive at specified level.");
620     return getStackElemAtLevel(Level).Directive;
621   }
622   /// Returns the capture region at the specified level.
623   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
624                                        unsigned OpenMPCaptureLevel) const {
625     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
626     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
627     return CaptureRegions[OpenMPCaptureLevel];
628   }
629   /// Returns parent directive.
630   OpenMPDirectiveKind getParentDirective() const {
631     const SharingMapTy *Parent = getSecondOnStackOrNull();
632     return Parent ? Parent->Directive : OMPD_unknown;
633   }
634 
635   /// Add requires decl to internal vector
636   void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
637 
638   /// Checks if the defined 'requires' directive has specified type of clause.
639   template <typename ClauseType> bool hasRequiresDeclWithClause() const {
640     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
641       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
642         return isa<ClauseType>(C);
643       });
644     });
645   }
646 
647   /// Checks for a duplicate clause amongst previously declared requires
648   /// directives
649   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
650     bool IsDuplicate = false;
651     for (OMPClause *CNew : ClauseList) {
652       for (const OMPRequiresDecl *D : RequiresDecls) {
653         for (const OMPClause *CPrev : D->clauselists()) {
654           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
655             SemaRef.Diag(CNew->getBeginLoc(),
656                          diag::err_omp_requires_clause_redeclaration)
657                 << getOpenMPClauseName(CNew->getClauseKind());
658             SemaRef.Diag(CPrev->getBeginLoc(),
659                          diag::note_omp_requires_previous_clause)
660                 << getOpenMPClauseName(CPrev->getClauseKind());
661             IsDuplicate = true;
662           }
663         }
664       }
665     }
666     return IsDuplicate;
667   }
668 
669   /// Add location of previously encountered target to internal vector
670   void addTargetDirLocation(SourceLocation LocStart) {
671     TargetLocations.push_back(LocStart);
672   }
673 
674   /// Add location for the first encountered atomicc directive.
675   void addAtomicDirectiveLoc(SourceLocation Loc) {
676     if (AtomicLocation.isInvalid())
677       AtomicLocation = Loc;
678   }
679 
680   /// Returns the location of the first encountered atomic directive in the
681   /// module.
682   SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
683 
684   // Return previously encountered target region locations.
685   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
686     return TargetLocations;
687   }
688 
689   /// Set default data sharing attribute to none.
690   void setDefaultDSANone(SourceLocation Loc) {
691     getTopOfStack().DefaultAttr = DSA_none;
692     getTopOfStack().DefaultAttrLoc = Loc;
693   }
694   /// Set default data sharing attribute to shared.
695   void setDefaultDSAShared(SourceLocation Loc) {
696     getTopOfStack().DefaultAttr = DSA_shared;
697     getTopOfStack().DefaultAttrLoc = Loc;
698   }
699   /// Set default data sharing attribute to private.
700   void setDefaultDSAPrivate(SourceLocation Loc) {
701     getTopOfStack().DefaultAttr = DSA_private;
702     getTopOfStack().DefaultAttrLoc = Loc;
703   }
704   /// Set default data sharing attribute to firstprivate.
705   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
706     getTopOfStack().DefaultAttr = DSA_firstprivate;
707     getTopOfStack().DefaultAttrLoc = Loc;
708   }
709   /// Set default data mapping attribute to Modifier:Kind
710   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
711                          OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
712     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
713     DMI.ImplicitBehavior = M;
714     DMI.SLoc = Loc;
715   }
716   /// Check whether the implicit-behavior has been set in defaultmap
717   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
718     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
719       return getTopOfStack()
720                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
721                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
722              getTopOfStack()
723                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
724                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
725              getTopOfStack()
726                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
727                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
728     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
729            OMPC_DEFAULTMAP_MODIFIER_unknown;
730   }
731 
732   ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
733     return ConstructTraits;
734   }
735   void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
736                             bool ScopeEntry) {
737     if (ScopeEntry)
738       ConstructTraits.append(Traits.begin(), Traits.end());
739     else
740       for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
741         llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
742         assert(Top == Trait && "Something left a trait on the stack!");
743         (void)Trait;
744         (void)Top;
745       }
746   }
747 
748   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
749     return getStackSize() <= Level ? DSA_unspecified
750                                    : getStackElemAtLevel(Level).DefaultAttr;
751   }
752   DefaultDataSharingAttributes getDefaultDSA() const {
753     return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
754   }
755   SourceLocation getDefaultDSALocation() const {
756     return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
757   }
758   OpenMPDefaultmapClauseModifier
759   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
760     return isStackEmpty()
761                ? OMPC_DEFAULTMAP_MODIFIER_unknown
762                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
763   }
764   OpenMPDefaultmapClauseModifier
765   getDefaultmapModifierAtLevel(unsigned Level,
766                                OpenMPDefaultmapClauseKind Kind) const {
767     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
768   }
769   bool isDefaultmapCapturedByRef(unsigned Level,
770                                  OpenMPDefaultmapClauseKind Kind) const {
771     OpenMPDefaultmapClauseModifier M =
772         getDefaultmapModifierAtLevel(Level, Kind);
773     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
774       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
775              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
776              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
777              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
778     }
779     return true;
780   }
781   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
782                                      OpenMPDefaultmapClauseKind Kind) {
783     switch (Kind) {
784     case OMPC_DEFAULTMAP_scalar:
785     case OMPC_DEFAULTMAP_pointer:
786       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
787              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
788              (M == OMPC_DEFAULTMAP_MODIFIER_default);
789     case OMPC_DEFAULTMAP_aggregate:
790       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
791     default:
792       break;
793     }
794     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
795   }
796   bool mustBeFirstprivateAtLevel(unsigned Level,
797                                  OpenMPDefaultmapClauseKind Kind) const {
798     OpenMPDefaultmapClauseModifier M =
799         getDefaultmapModifierAtLevel(Level, Kind);
800     return mustBeFirstprivateBase(M, Kind);
801   }
802   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
803     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
804     return mustBeFirstprivateBase(M, Kind);
805   }
806 
807   /// Checks if the specified variable is a threadprivate.
808   bool isThreadPrivate(VarDecl *D) {
809     const DSAVarData DVar = getTopDSA(D, false);
810     return isOpenMPThreadPrivate(DVar.CKind);
811   }
812 
813   /// Marks current region as ordered (it has an 'ordered' clause).
814   void setOrderedRegion(bool IsOrdered, const Expr *Param,
815                         OMPOrderedClause *Clause) {
816     if (IsOrdered)
817       getTopOfStack().OrderedRegion.emplace(Param, Clause);
818     else
819       getTopOfStack().OrderedRegion.reset();
820   }
821   /// Returns true, if region is ordered (has associated 'ordered' clause),
822   /// false - otherwise.
823   bool isOrderedRegion() const {
824     if (const SharingMapTy *Top = getTopOfStackOrNull())
825       return Top->OrderedRegion.hasValue();
826     return false;
827   }
828   /// Returns optional parameter for the ordered region.
829   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
830     if (const SharingMapTy *Top = getTopOfStackOrNull())
831       if (Top->OrderedRegion.hasValue())
832         return Top->OrderedRegion.getValue();
833     return std::make_pair(nullptr, nullptr);
834   }
835   /// Returns true, if parent region is ordered (has associated
836   /// 'ordered' clause), false - otherwise.
837   bool isParentOrderedRegion() const {
838     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
839       return Parent->OrderedRegion.hasValue();
840     return false;
841   }
842   /// Returns optional parameter for the ordered region.
843   std::pair<const Expr *, OMPOrderedClause *>
844   getParentOrderedRegionParam() const {
845     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
846       if (Parent->OrderedRegion.hasValue())
847         return Parent->OrderedRegion.getValue();
848     return std::make_pair(nullptr, nullptr);
849   }
850   /// Marks current region as nowait (it has a 'nowait' clause).
851   void setNowaitRegion(bool IsNowait = true) {
852     getTopOfStack().NowaitRegion = IsNowait;
853   }
854   /// Returns true, if parent region is nowait (has associated
855   /// 'nowait' clause), false - otherwise.
856   bool isParentNowaitRegion() const {
857     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
858       return Parent->NowaitRegion;
859     return false;
860   }
861   /// Marks current region as untied (it has a 'untied' clause).
862   void setUntiedRegion(bool IsUntied = true) {
863     getTopOfStack().UntiedRegion = IsUntied;
864   }
865   /// Return true if current region is untied.
866   bool isUntiedRegion() const {
867     const SharingMapTy *Top = getTopOfStackOrNull();
868     return Top ? Top->UntiedRegion : false;
869   }
870   /// Marks parent region as cancel region.
871   void setParentCancelRegion(bool Cancel = true) {
872     if (SharingMapTy *Parent = getSecondOnStackOrNull())
873       Parent->CancelRegion |= Cancel;
874   }
875   /// Return true if current region has inner cancel construct.
876   bool isCancelRegion() const {
877     const SharingMapTy *Top = getTopOfStackOrNull();
878     return Top ? Top->CancelRegion : false;
879   }
880 
881   /// Mark that parent region already has scan directive.
882   void setParentHasScanDirective(SourceLocation Loc) {
883     if (SharingMapTy *Parent = getSecondOnStackOrNull())
884       Parent->PrevScanLocation = Loc;
885   }
886   /// Return true if current region has inner cancel construct.
887   bool doesParentHasScanDirective() const {
888     const SharingMapTy *Top = getSecondOnStackOrNull();
889     return Top ? Top->PrevScanLocation.isValid() : false;
890   }
891   /// Return true if current region has inner cancel construct.
892   SourceLocation getParentScanDirectiveLoc() const {
893     const SharingMapTy *Top = getSecondOnStackOrNull();
894     return Top ? Top->PrevScanLocation : SourceLocation();
895   }
896   /// Mark that parent region already has ordered directive.
897   void setParentHasOrderedDirective(SourceLocation Loc) {
898     if (SharingMapTy *Parent = getSecondOnStackOrNull())
899       Parent->PrevOrderedLocation = Loc;
900   }
901   /// Return true if current region has inner ordered construct.
902   bool doesParentHasOrderedDirective() const {
903     const SharingMapTy *Top = getSecondOnStackOrNull();
904     return Top ? Top->PrevOrderedLocation.isValid() : false;
905   }
906   /// Returns the location of the previously specified ordered directive.
907   SourceLocation getParentOrderedDirectiveLoc() const {
908     const SharingMapTy *Top = getSecondOnStackOrNull();
909     return Top ? Top->PrevOrderedLocation : SourceLocation();
910   }
911 
912   /// Set collapse value for the region.
913   void setAssociatedLoops(unsigned Val) {
914     getTopOfStack().AssociatedLoops = Val;
915     if (Val > 1)
916       getTopOfStack().HasMutipleLoops = true;
917   }
918   /// Return collapse value for region.
919   unsigned getAssociatedLoops() const {
920     const SharingMapTy *Top = getTopOfStackOrNull();
921     return Top ? Top->AssociatedLoops : 0;
922   }
923   /// Returns true if the construct is associated with multiple loops.
924   bool hasMutipleLoops() const {
925     const SharingMapTy *Top = getTopOfStackOrNull();
926     return Top ? Top->HasMutipleLoops : false;
927   }
928 
929   /// Marks current target region as one with closely nested teams
930   /// region.
931   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
932     if (SharingMapTy *Parent = getSecondOnStackOrNull())
933       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
934   }
935   /// Returns true, if current region has closely nested teams region.
936   bool hasInnerTeamsRegion() const {
937     return getInnerTeamsRegionLoc().isValid();
938   }
939   /// Returns location of the nested teams region (if any).
940   SourceLocation getInnerTeamsRegionLoc() const {
941     const SharingMapTy *Top = getTopOfStackOrNull();
942     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
943   }
944 
945   Scope *getCurScope() const {
946     const SharingMapTy *Top = getTopOfStackOrNull();
947     return Top ? Top->CurScope : nullptr;
948   }
949   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
950   SourceLocation getConstructLoc() const {
951     const SharingMapTy *Top = getTopOfStackOrNull();
952     return Top ? Top->ConstructLoc : SourceLocation();
953   }
954 
955   /// Do the check specified in \a Check to all component lists and return true
956   /// if any issue is found.
957   bool checkMappableExprComponentListsForDecl(
958       const ValueDecl *VD, bool CurrentRegionOnly,
959       const llvm::function_ref<
960           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
961                OpenMPClauseKind)>
962           Check) const {
963     if (isStackEmpty())
964       return false;
965     auto SI = begin();
966     auto SE = end();
967 
968     if (SI == SE)
969       return false;
970 
971     if (CurrentRegionOnly)
972       SE = std::next(SI);
973     else
974       std::advance(SI, 1);
975 
976     for (; SI != SE; ++SI) {
977       auto MI = SI->MappedExprComponents.find(VD);
978       if (MI != SI->MappedExprComponents.end())
979         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
980              MI->second.Components)
981           if (Check(L, MI->second.Kind))
982             return true;
983     }
984     return false;
985   }
986 
987   /// Do the check specified in \a Check to all component lists at a given level
988   /// and return true if any issue is found.
989   bool checkMappableExprComponentListsForDeclAtLevel(
990       const ValueDecl *VD, unsigned Level,
991       const llvm::function_ref<
992           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
993                OpenMPClauseKind)>
994           Check) const {
995     if (getStackSize() <= Level)
996       return false;
997 
998     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
999     auto MI = StackElem.MappedExprComponents.find(VD);
1000     if (MI != StackElem.MappedExprComponents.end())
1001       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
1002            MI->second.Components)
1003         if (Check(L, MI->second.Kind))
1004           return true;
1005     return false;
1006   }
1007 
1008   /// Create a new mappable expression component list associated with a given
1009   /// declaration and initialize it with the provided list of components.
1010   void addMappableExpressionComponents(
1011       const ValueDecl *VD,
1012       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
1013       OpenMPClauseKind WhereFoundClauseKind) {
1014     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
1015     // Create new entry and append the new components there.
1016     MEC.Components.resize(MEC.Components.size() + 1);
1017     MEC.Components.back().append(Components.begin(), Components.end());
1018     MEC.Kind = WhereFoundClauseKind;
1019   }
1020 
1021   unsigned getNestingLevel() const {
1022     assert(!isStackEmpty());
1023     return getStackSize() - 1;
1024   }
1025   void addDoacrossDependClause(OMPDependClause *C,
1026                                const OperatorOffsetTy &OpsOffs) {
1027     SharingMapTy *Parent = getSecondOnStackOrNull();
1028     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1029     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1030   }
1031   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1032   getDoacrossDependClauses() const {
1033     const SharingMapTy &StackElem = getTopOfStack();
1034     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1035       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1036       return llvm::make_range(Ref.begin(), Ref.end());
1037     }
1038     return llvm::make_range(StackElem.DoacrossDepends.end(),
1039                             StackElem.DoacrossDepends.end());
1040   }
1041 
1042   // Store types of classes which have been explicitly mapped
1043   void addMappedClassesQualTypes(QualType QT) {
1044     SharingMapTy &StackElem = getTopOfStack();
1045     StackElem.MappedClassesQualTypes.insert(QT);
1046   }
1047 
1048   // Return set of mapped classes types
1049   bool isClassPreviouslyMapped(QualType QT) const {
1050     const SharingMapTy &StackElem = getTopOfStack();
1051     return StackElem.MappedClassesQualTypes.contains(QT);
1052   }
1053 
1054   /// Adds global declare target to the parent target region.
1055   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1056     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1057                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1058            "Expected declare target link global.");
1059     for (auto &Elem : *this) {
1060       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1061         Elem.DeclareTargetLinkVarDecls.push_back(E);
1062         return;
1063       }
1064     }
1065   }
1066 
1067   /// Returns the list of globals with declare target link if current directive
1068   /// is target.
1069   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1070     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1071            "Expected target executable directive.");
1072     return getTopOfStack().DeclareTargetLinkVarDecls;
1073   }
1074 
1075   /// Adds list of allocators expressions.
1076   void addInnerAllocatorExpr(Expr *E) {
1077     getTopOfStack().InnerUsedAllocators.push_back(E);
1078   }
1079   /// Return list of used allocators.
1080   ArrayRef<Expr *> getInnerAllocators() const {
1081     return getTopOfStack().InnerUsedAllocators;
1082   }
1083   /// Marks the declaration as implicitly firstprivate nin the task-based
1084   /// regions.
1085   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1086     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1087   }
1088   /// Checks if the decl is implicitly firstprivate in the task-based region.
1089   bool isImplicitTaskFirstprivate(Decl *D) const {
1090     return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1091   }
1092 
1093   /// Marks decl as used in uses_allocators clause as the allocator.
1094   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1095     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1096   }
1097   /// Checks if specified decl is used in uses allocator clause as the
1098   /// allocator.
1099   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1100                                                         const Decl *D) const {
1101     const SharingMapTy &StackElem = getTopOfStack();
1102     auto I = StackElem.UsesAllocatorsDecls.find(D);
1103     if (I == StackElem.UsesAllocatorsDecls.end())
1104       return None;
1105     return I->getSecond();
1106   }
1107   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1108     const SharingMapTy &StackElem = getTopOfStack();
1109     auto I = StackElem.UsesAllocatorsDecls.find(D);
1110     if (I == StackElem.UsesAllocatorsDecls.end())
1111       return None;
1112     return I->getSecond();
1113   }
1114 
1115   void addDeclareMapperVarRef(Expr *Ref) {
1116     SharingMapTy &StackElem = getTopOfStack();
1117     StackElem.DeclareMapperVar = Ref;
1118   }
1119   const Expr *getDeclareMapperVarRef() const {
1120     const SharingMapTy *Top = getTopOfStackOrNull();
1121     return Top ? Top->DeclareMapperVar : nullptr;
1122   }
1123 };
1124 
1125 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1126   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1127 }
1128 
1129 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1130   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1131          DKind == OMPD_unknown;
1132 }
1133 
1134 } // namespace
1135 
1136 static const Expr *getExprAsWritten(const Expr *E) {
1137   if (const auto *FE = dyn_cast<FullExpr>(E))
1138     E = FE->getSubExpr();
1139 
1140   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1141     E = MTE->getSubExpr();
1142 
1143   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1144     E = Binder->getSubExpr();
1145 
1146   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1147     E = ICE->getSubExprAsWritten();
1148   return E->IgnoreParens();
1149 }
1150 
1151 static Expr *getExprAsWritten(Expr *E) {
1152   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1153 }
1154 
1155 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1156   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1157     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1158       D = ME->getMemberDecl();
1159   const auto *VD = dyn_cast<VarDecl>(D);
1160   const auto *FD = dyn_cast<FieldDecl>(D);
1161   if (VD != nullptr) {
1162     VD = VD->getCanonicalDecl();
1163     D = VD;
1164   } else {
1165     assert(FD);
1166     FD = FD->getCanonicalDecl();
1167     D = FD;
1168   }
1169   return D;
1170 }
1171 
1172 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1173   return const_cast<ValueDecl *>(
1174       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1175 }
1176 
1177 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1178                                           ValueDecl *D) const {
1179   D = getCanonicalDecl(D);
1180   auto *VD = dyn_cast<VarDecl>(D);
1181   const auto *FD = dyn_cast<FieldDecl>(D);
1182   DSAVarData DVar;
1183   if (Iter == end()) {
1184     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1185     // in a region but not in construct]
1186     //  File-scope or namespace-scope variables referenced in called routines
1187     //  in the region are shared unless they appear in a threadprivate
1188     //  directive.
1189     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1190       DVar.CKind = OMPC_shared;
1191 
1192     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1193     // in a region but not in construct]
1194     //  Variables with static storage duration that are declared in called
1195     //  routines in the region are shared.
1196     if (VD && VD->hasGlobalStorage())
1197       DVar.CKind = OMPC_shared;
1198 
1199     // Non-static data members are shared by default.
1200     if (FD)
1201       DVar.CKind = OMPC_shared;
1202 
1203     return DVar;
1204   }
1205 
1206   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1207   // in a Construct, C/C++, predetermined, p.1]
1208   // Variables with automatic storage duration that are declared in a scope
1209   // inside the construct are private.
1210   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1211       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1212     DVar.CKind = OMPC_private;
1213     return DVar;
1214   }
1215 
1216   DVar.DKind = Iter->Directive;
1217   // Explicitly specified attributes and local variables with predetermined
1218   // attributes.
1219   if (Iter->SharingMap.count(D)) {
1220     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1221     DVar.RefExpr = Data.RefExpr.getPointer();
1222     DVar.PrivateCopy = Data.PrivateCopy;
1223     DVar.CKind = Data.Attributes;
1224     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1225     DVar.Modifier = Data.Modifier;
1226     DVar.AppliedToPointee = Data.AppliedToPointee;
1227     return DVar;
1228   }
1229 
1230   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1231   // in a Construct, C/C++, implicitly determined, p.1]
1232   //  In a parallel or task construct, the data-sharing attributes of these
1233   //  variables are determined by the default clause, if present.
1234   switch (Iter->DefaultAttr) {
1235   case DSA_shared:
1236     DVar.CKind = OMPC_shared;
1237     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1238     return DVar;
1239   case DSA_none:
1240     return DVar;
1241   case DSA_firstprivate:
1242     if (VD && VD->getStorageDuration() == SD_Static &&
1243         VD->getDeclContext()->isFileContext()) {
1244       DVar.CKind = OMPC_unknown;
1245     } else {
1246       DVar.CKind = OMPC_firstprivate;
1247     }
1248     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1249     return DVar;
1250   case DSA_private:
1251     // each variable with static storage duration that is declared
1252     // in a namespace or global scope and referenced in the construct,
1253     // and that does not have a predetermined data-sharing attribute
1254     if (VD && VD->getStorageDuration() == SD_Static &&
1255         VD->getDeclContext()->isFileContext()) {
1256       DVar.CKind = OMPC_unknown;
1257     } else {
1258       DVar.CKind = OMPC_private;
1259     }
1260     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1261     return DVar;
1262   case DSA_unspecified:
1263     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1264     // in a Construct, implicitly determined, p.2]
1265     //  In a parallel construct, if no default clause is present, these
1266     //  variables are shared.
1267     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1268     if ((isOpenMPParallelDirective(DVar.DKind) &&
1269          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1270         isOpenMPTeamsDirective(DVar.DKind)) {
1271       DVar.CKind = OMPC_shared;
1272       return DVar;
1273     }
1274 
1275     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1276     // in a Construct, implicitly determined, p.4]
1277     //  In a task construct, if no default clause is present, a variable that in
1278     //  the enclosing context is determined to be shared by all implicit tasks
1279     //  bound to the current team is shared.
1280     if (isOpenMPTaskingDirective(DVar.DKind)) {
1281       DSAVarData DVarTemp;
1282       const_iterator I = Iter, E = end();
1283       do {
1284         ++I;
1285         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1286         // Referenced in a Construct, implicitly determined, p.6]
1287         //  In a task construct, if no default clause is present, a variable
1288         //  whose data-sharing attribute is not determined by the rules above is
1289         //  firstprivate.
1290         DVarTemp = getDSA(I, D);
1291         if (DVarTemp.CKind != OMPC_shared) {
1292           DVar.RefExpr = nullptr;
1293           DVar.CKind = OMPC_firstprivate;
1294           return DVar;
1295         }
1296       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1297       DVar.CKind =
1298           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1299       return DVar;
1300     }
1301   }
1302   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1303   // in a Construct, implicitly determined, p.3]
1304   //  For constructs other than task, if no default clause is present, these
1305   //  variables inherit their data-sharing attributes from the enclosing
1306   //  context.
1307   return getDSA(++Iter, D);
1308 }
1309 
1310 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1311                                          const Expr *NewDE) {
1312   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1313   D = getCanonicalDecl(D);
1314   SharingMapTy &StackElem = getTopOfStack();
1315   auto It = StackElem.AlignedMap.find(D);
1316   if (It == StackElem.AlignedMap.end()) {
1317     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1318     StackElem.AlignedMap[D] = NewDE;
1319     return nullptr;
1320   }
1321   assert(It->second && "Unexpected nullptr expr in the aligned map");
1322   return It->second;
1323 }
1324 
1325 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1326                                              const Expr *NewDE) {
1327   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1328   D = getCanonicalDecl(D);
1329   SharingMapTy &StackElem = getTopOfStack();
1330   auto It = StackElem.NontemporalMap.find(D);
1331   if (It == StackElem.NontemporalMap.end()) {
1332     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1333     StackElem.NontemporalMap[D] = NewDE;
1334     return nullptr;
1335   }
1336   assert(It->second && "Unexpected nullptr expr in the aligned map");
1337   return It->second;
1338 }
1339 
1340 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1341   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1342   D = getCanonicalDecl(D);
1343   SharingMapTy &StackElem = getTopOfStack();
1344   StackElem.LCVMap.try_emplace(
1345       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1346 }
1347 
1348 const DSAStackTy::LCDeclInfo
1349 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1350   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1351   D = getCanonicalDecl(D);
1352   const SharingMapTy &StackElem = getTopOfStack();
1353   auto It = StackElem.LCVMap.find(D);
1354   if (It != StackElem.LCVMap.end())
1355     return It->second;
1356   return {0, nullptr};
1357 }
1358 
1359 const DSAStackTy::LCDeclInfo
1360 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1361   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1362   D = getCanonicalDecl(D);
1363   for (unsigned I = Level + 1; I > 0; --I) {
1364     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1365     auto It = StackElem.LCVMap.find(D);
1366     if (It != StackElem.LCVMap.end())
1367       return It->second;
1368   }
1369   return {0, nullptr};
1370 }
1371 
1372 const DSAStackTy::LCDeclInfo
1373 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1374   const SharingMapTy *Parent = getSecondOnStackOrNull();
1375   assert(Parent && "Data-sharing attributes stack is empty");
1376   D = getCanonicalDecl(D);
1377   auto It = Parent->LCVMap.find(D);
1378   if (It != Parent->LCVMap.end())
1379     return It->second;
1380   return {0, nullptr};
1381 }
1382 
1383 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1384   const SharingMapTy *Parent = getSecondOnStackOrNull();
1385   assert(Parent && "Data-sharing attributes stack is empty");
1386   if (Parent->LCVMap.size() < I)
1387     return nullptr;
1388   for (const auto &Pair : Parent->LCVMap)
1389     if (Pair.second.first == I)
1390       return Pair.first;
1391   return nullptr;
1392 }
1393 
1394 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1395                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1396                         bool AppliedToPointee) {
1397   D = getCanonicalDecl(D);
1398   if (A == OMPC_threadprivate) {
1399     DSAInfo &Data = Threadprivates[D];
1400     Data.Attributes = A;
1401     Data.RefExpr.setPointer(E);
1402     Data.PrivateCopy = nullptr;
1403     Data.Modifier = Modifier;
1404   } else {
1405     DSAInfo &Data = getTopOfStack().SharingMap[D];
1406     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1407            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1408            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1409            (isLoopControlVariable(D).first && A == OMPC_private));
1410     Data.Modifier = Modifier;
1411     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1412       Data.RefExpr.setInt(/*IntVal=*/true);
1413       return;
1414     }
1415     const bool IsLastprivate =
1416         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1417     Data.Attributes = A;
1418     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1419     Data.PrivateCopy = PrivateCopy;
1420     Data.AppliedToPointee = AppliedToPointee;
1421     if (PrivateCopy) {
1422       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1423       Data.Modifier = Modifier;
1424       Data.Attributes = A;
1425       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1426       Data.PrivateCopy = nullptr;
1427       Data.AppliedToPointee = AppliedToPointee;
1428     }
1429   }
1430 }
1431 
1432 /// Build a variable declaration for OpenMP loop iteration variable.
1433 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1434                              StringRef Name, const AttrVec *Attrs = nullptr,
1435                              DeclRefExpr *OrigRef = nullptr) {
1436   DeclContext *DC = SemaRef.CurContext;
1437   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1438   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1439   auto *Decl =
1440       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1441   if (Attrs) {
1442     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1443          I != E; ++I)
1444       Decl->addAttr(*I);
1445   }
1446   Decl->setImplicit();
1447   if (OrigRef) {
1448     Decl->addAttr(
1449         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1450   }
1451   return Decl;
1452 }
1453 
1454 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1455                                      SourceLocation Loc,
1456                                      bool RefersToCapture = false) {
1457   D->setReferenced();
1458   D->markUsed(S.Context);
1459   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1460                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1461                              VK_LValue);
1462 }
1463 
1464 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1465                                            BinaryOperatorKind BOK) {
1466   D = getCanonicalDecl(D);
1467   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1468   assert(
1469       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1470       "Additional reduction info may be specified only for reduction items.");
1471   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1472   assert(ReductionData.ReductionRange.isInvalid() &&
1473          (getTopOfStack().Directive == OMPD_taskgroup ||
1474           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1475             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1476            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1477          "Additional reduction info may be specified only once for reduction "
1478          "items.");
1479   ReductionData.set(BOK, SR);
1480   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1481   if (!TaskgroupReductionRef) {
1482     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1483                                SemaRef.Context.VoidPtrTy, ".task_red.");
1484     TaskgroupReductionRef =
1485         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1486   }
1487 }
1488 
1489 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1490                                            const Expr *ReductionRef) {
1491   D = getCanonicalDecl(D);
1492   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1493   assert(
1494       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1495       "Additional reduction info may be specified only for reduction items.");
1496   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1497   assert(ReductionData.ReductionRange.isInvalid() &&
1498          (getTopOfStack().Directive == OMPD_taskgroup ||
1499           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1500             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1501            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1502          "Additional reduction info may be specified only once for reduction "
1503          "items.");
1504   ReductionData.set(ReductionRef, SR);
1505   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1506   if (!TaskgroupReductionRef) {
1507     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1508                                SemaRef.Context.VoidPtrTy, ".task_red.");
1509     TaskgroupReductionRef =
1510         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1511   }
1512 }
1513 
1514 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1515     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1516     Expr *&TaskgroupDescriptor) const {
1517   D = getCanonicalDecl(D);
1518   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1519   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1520     const DSAInfo &Data = I->SharingMap.lookup(D);
1521     if (Data.Attributes != OMPC_reduction ||
1522         Data.Modifier != OMPC_REDUCTION_task)
1523       continue;
1524     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1525     if (!ReductionData.ReductionOp ||
1526         ReductionData.ReductionOp.is<const Expr *>())
1527       return DSAVarData();
1528     SR = ReductionData.ReductionRange;
1529     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1530     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1531                                        "expression for the descriptor is not "
1532                                        "set.");
1533     TaskgroupDescriptor = I->TaskgroupReductionRef;
1534     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1535                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1536                       /*AppliedToPointee=*/false);
1537   }
1538   return DSAVarData();
1539 }
1540 
1541 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1542     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1543     Expr *&TaskgroupDescriptor) const {
1544   D = getCanonicalDecl(D);
1545   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1546   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1547     const DSAInfo &Data = I->SharingMap.lookup(D);
1548     if (Data.Attributes != OMPC_reduction ||
1549         Data.Modifier != OMPC_REDUCTION_task)
1550       continue;
1551     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1552     if (!ReductionData.ReductionOp ||
1553         !ReductionData.ReductionOp.is<const Expr *>())
1554       return DSAVarData();
1555     SR = ReductionData.ReductionRange;
1556     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1557     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1558                                        "expression for the descriptor is not "
1559                                        "set.");
1560     TaskgroupDescriptor = I->TaskgroupReductionRef;
1561     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1562                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1563                       /*AppliedToPointee=*/false);
1564   }
1565   return DSAVarData();
1566 }
1567 
1568 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1569   D = D->getCanonicalDecl();
1570   for (const_iterator E = end(); I != E; ++I) {
1571     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1572         isOpenMPTargetExecutionDirective(I->Directive)) {
1573       if (I->CurScope) {
1574         Scope *TopScope = I->CurScope->getParent();
1575         Scope *CurScope = getCurScope();
1576         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1577           CurScope = CurScope->getParent();
1578         return CurScope != TopScope;
1579       }
1580       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1581         if (I->Context == DC)
1582           return true;
1583       return false;
1584     }
1585   }
1586   return false;
1587 }
1588 
1589 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1590                                   bool AcceptIfMutable = true,
1591                                   bool *IsClassType = nullptr) {
1592   ASTContext &Context = SemaRef.getASTContext();
1593   Type = Type.getNonReferenceType().getCanonicalType();
1594   bool IsConstant = Type.isConstant(Context);
1595   Type = Context.getBaseElementType(Type);
1596   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1597                                 ? Type->getAsCXXRecordDecl()
1598                                 : nullptr;
1599   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1600     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1601       RD = CTD->getTemplatedDecl();
1602   if (IsClassType)
1603     *IsClassType = RD;
1604   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1605                          RD->hasDefinition() && RD->hasMutableFields());
1606 }
1607 
1608 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1609                                       QualType Type, OpenMPClauseKind CKind,
1610                                       SourceLocation ELoc,
1611                                       bool AcceptIfMutable = true,
1612                                       bool ListItemNotVar = false) {
1613   ASTContext &Context = SemaRef.getASTContext();
1614   bool IsClassType;
1615   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1616     unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1617                     : IsClassType  ? diag::err_omp_const_not_mutable_variable
1618                                    : diag::err_omp_const_variable;
1619     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1620     if (!ListItemNotVar && D) {
1621       const VarDecl *VD = dyn_cast<VarDecl>(D);
1622       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1623                                VarDecl::DeclarationOnly;
1624       SemaRef.Diag(D->getLocation(),
1625                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1626           << D;
1627     }
1628     return true;
1629   }
1630   return false;
1631 }
1632 
1633 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1634                                                    bool FromParent) {
1635   D = getCanonicalDecl(D);
1636   DSAVarData DVar;
1637 
1638   auto *VD = dyn_cast<VarDecl>(D);
1639   auto TI = Threadprivates.find(D);
1640   if (TI != Threadprivates.end()) {
1641     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1642     DVar.CKind = OMPC_threadprivate;
1643     DVar.Modifier = TI->getSecond().Modifier;
1644     return DVar;
1645   }
1646   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1647     DVar.RefExpr = buildDeclRefExpr(
1648         SemaRef, VD, D->getType().getNonReferenceType(),
1649         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1650     DVar.CKind = OMPC_threadprivate;
1651     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1652     return DVar;
1653   }
1654   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1655   // in a Construct, C/C++, predetermined, p.1]
1656   //  Variables appearing in threadprivate directives are threadprivate.
1657   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1658        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1659          SemaRef.getLangOpts().OpenMPUseTLS &&
1660          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1661       (VD && VD->getStorageClass() == SC_Register &&
1662        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1663     DVar.RefExpr = buildDeclRefExpr(
1664         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1665     DVar.CKind = OMPC_threadprivate;
1666     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1667     return DVar;
1668   }
1669   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1670       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1671       !isLoopControlVariable(D).first) {
1672     const_iterator IterTarget =
1673         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1674           return isOpenMPTargetExecutionDirective(Data.Directive);
1675         });
1676     if (IterTarget != end()) {
1677       const_iterator ParentIterTarget = IterTarget + 1;
1678       for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1679         if (isOpenMPLocal(VD, Iter)) {
1680           DVar.RefExpr =
1681               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1682                                D->getLocation());
1683           DVar.CKind = OMPC_threadprivate;
1684           return DVar;
1685         }
1686       }
1687       if (!isClauseParsingMode() || IterTarget != begin()) {
1688         auto DSAIter = IterTarget->SharingMap.find(D);
1689         if (DSAIter != IterTarget->SharingMap.end() &&
1690             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1691           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1692           DVar.CKind = OMPC_threadprivate;
1693           return DVar;
1694         }
1695         const_iterator End = end();
1696         if (!SemaRef.isOpenMPCapturedByRef(D,
1697                                            std::distance(ParentIterTarget, End),
1698                                            /*OpenMPCaptureLevel=*/0)) {
1699           DVar.RefExpr =
1700               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1701                                IterTarget->ConstructLoc);
1702           DVar.CKind = OMPC_threadprivate;
1703           return DVar;
1704         }
1705       }
1706     }
1707   }
1708 
1709   if (isStackEmpty())
1710     // Not in OpenMP execution region and top scope was already checked.
1711     return DVar;
1712 
1713   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1714   // in a Construct, C/C++, predetermined, p.4]
1715   //  Static data members are shared.
1716   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1717   // in a Construct, C/C++, predetermined, p.7]
1718   //  Variables with static storage duration that are declared in a scope
1719   //  inside the construct are shared.
1720   if (VD && VD->isStaticDataMember()) {
1721     // Check for explicitly specified attributes.
1722     const_iterator I = begin();
1723     const_iterator EndI = end();
1724     if (FromParent && I != EndI)
1725       ++I;
1726     if (I != EndI) {
1727       auto It = I->SharingMap.find(D);
1728       if (It != I->SharingMap.end()) {
1729         const DSAInfo &Data = It->getSecond();
1730         DVar.RefExpr = Data.RefExpr.getPointer();
1731         DVar.PrivateCopy = Data.PrivateCopy;
1732         DVar.CKind = Data.Attributes;
1733         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1734         DVar.DKind = I->Directive;
1735         DVar.Modifier = Data.Modifier;
1736         DVar.AppliedToPointee = Data.AppliedToPointee;
1737         return DVar;
1738       }
1739     }
1740 
1741     DVar.CKind = OMPC_shared;
1742     return DVar;
1743   }
1744 
1745   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1746   // The predetermined shared attribute for const-qualified types having no
1747   // mutable members was removed after OpenMP 3.1.
1748   if (SemaRef.LangOpts.OpenMP <= 31) {
1749     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1750     // in a Construct, C/C++, predetermined, p.6]
1751     //  Variables with const qualified type having no mutable member are
1752     //  shared.
1753     if (isConstNotMutableType(SemaRef, D->getType())) {
1754       // Variables with const-qualified type having no mutable member may be
1755       // listed in a firstprivate clause, even if they are static data members.
1756       DSAVarData DVarTemp = hasInnermostDSA(
1757           D,
1758           [](OpenMPClauseKind C, bool) {
1759             return C == OMPC_firstprivate || C == OMPC_shared;
1760           },
1761           MatchesAlways, FromParent);
1762       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1763         return DVarTemp;
1764 
1765       DVar.CKind = OMPC_shared;
1766       return DVar;
1767     }
1768   }
1769 
1770   // Explicitly specified attributes and local variables with predetermined
1771   // attributes.
1772   const_iterator I = begin();
1773   const_iterator EndI = end();
1774   if (FromParent && I != EndI)
1775     ++I;
1776   if (I == EndI)
1777     return DVar;
1778   auto It = I->SharingMap.find(D);
1779   if (It != I->SharingMap.end()) {
1780     const DSAInfo &Data = It->getSecond();
1781     DVar.RefExpr = Data.RefExpr.getPointer();
1782     DVar.PrivateCopy = Data.PrivateCopy;
1783     DVar.CKind = Data.Attributes;
1784     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1785     DVar.DKind = I->Directive;
1786     DVar.Modifier = Data.Modifier;
1787     DVar.AppliedToPointee = Data.AppliedToPointee;
1788   }
1789 
1790   return DVar;
1791 }
1792 
1793 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1794                                                         bool FromParent) const {
1795   if (isStackEmpty()) {
1796     const_iterator I;
1797     return getDSA(I, D);
1798   }
1799   D = getCanonicalDecl(D);
1800   const_iterator StartI = begin();
1801   const_iterator EndI = end();
1802   if (FromParent && StartI != EndI)
1803     ++StartI;
1804   return getDSA(StartI, D);
1805 }
1806 
1807 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1808                                                         unsigned Level) const {
1809   if (getStackSize() <= Level)
1810     return DSAVarData();
1811   D = getCanonicalDecl(D);
1812   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1813   return getDSA(StartI, D);
1814 }
1815 
1816 const DSAStackTy::DSAVarData
1817 DSAStackTy::hasDSA(ValueDecl *D,
1818                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1819                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1820                    bool FromParent) const {
1821   if (isStackEmpty())
1822     return {};
1823   D = getCanonicalDecl(D);
1824   const_iterator I = begin();
1825   const_iterator EndI = end();
1826   if (FromParent && I != EndI)
1827     ++I;
1828   for (; I != EndI; ++I) {
1829     if (!DPred(I->Directive) &&
1830         !isImplicitOrExplicitTaskingRegion(I->Directive))
1831       continue;
1832     const_iterator NewI = I;
1833     DSAVarData DVar = getDSA(NewI, D);
1834     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1835       return DVar;
1836   }
1837   return {};
1838 }
1839 
1840 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1841     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1842     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1843     bool FromParent) const {
1844   if (isStackEmpty())
1845     return {};
1846   D = getCanonicalDecl(D);
1847   const_iterator StartI = begin();
1848   const_iterator EndI = end();
1849   if (FromParent && StartI != EndI)
1850     ++StartI;
1851   if (StartI == EndI || !DPred(StartI->Directive))
1852     return {};
1853   const_iterator NewI = StartI;
1854   DSAVarData DVar = getDSA(NewI, D);
1855   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1856              ? DVar
1857              : DSAVarData();
1858 }
1859 
1860 bool DSAStackTy::hasExplicitDSA(
1861     const ValueDecl *D,
1862     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1863     unsigned Level, bool NotLastprivate) const {
1864   if (getStackSize() <= Level)
1865     return false;
1866   D = getCanonicalDecl(D);
1867   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1868   auto I = StackElem.SharingMap.find(D);
1869   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1870       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1871       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1872     return true;
1873   // Check predetermined rules for the loop control variables.
1874   auto LI = StackElem.LCVMap.find(D);
1875   if (LI != StackElem.LCVMap.end())
1876     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1877   return false;
1878 }
1879 
1880 bool DSAStackTy::hasExplicitDirective(
1881     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1882     unsigned Level) const {
1883   if (getStackSize() <= Level)
1884     return false;
1885   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1886   return DPred(StackElem.Directive);
1887 }
1888 
1889 bool DSAStackTy::hasDirective(
1890     const llvm::function_ref<bool(OpenMPDirectiveKind,
1891                                   const DeclarationNameInfo &, SourceLocation)>
1892         DPred,
1893     bool FromParent) const {
1894   // We look only in the enclosing region.
1895   size_t Skip = FromParent ? 2 : 1;
1896   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1897        I != E; ++I) {
1898     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1899       return true;
1900   }
1901   return false;
1902 }
1903 
1904 void Sema::InitDataSharingAttributesStack() {
1905   VarDataSharingAttributesStack = new DSAStackTy(*this);
1906 }
1907 
1908 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1909 
1910 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
1911 
1912 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1913   DSAStack->popFunction(OldFSI);
1914 }
1915 
1916 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1917   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1918          "Expected OpenMP device compilation.");
1919   return !S.isInOpenMPTargetExecutionDirective();
1920 }
1921 
1922 namespace {
1923 /// Status of the function emission on the host/device.
1924 enum class FunctionEmissionStatus {
1925   Emitted,
1926   Discarded,
1927   Unknown,
1928 };
1929 } // anonymous namespace
1930 
1931 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1932                                                          unsigned DiagID,
1933                                                          FunctionDecl *FD) {
1934   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1935          "Expected OpenMP device compilation.");
1936 
1937   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1938   if (FD) {
1939     FunctionEmissionStatus FES = getEmissionStatus(FD);
1940     switch (FES) {
1941     case FunctionEmissionStatus::Emitted:
1942       Kind = SemaDiagnosticBuilder::K_Immediate;
1943       break;
1944     case FunctionEmissionStatus::Unknown:
1945       // TODO: We should always delay diagnostics here in case a target
1946       //       region is in a function we do not emit. However, as the
1947       //       current diagnostics are associated with the function containing
1948       //       the target region and we do not emit that one, we would miss out
1949       //       on diagnostics for the target region itself. We need to anchor
1950       //       the diagnostics with the new generated function *or* ensure we
1951       //       emit diagnostics associated with the surrounding function.
1952       Kind = isOpenMPDeviceDelayedContext(*this)
1953                  ? SemaDiagnosticBuilder::K_Deferred
1954                  : SemaDiagnosticBuilder::K_Immediate;
1955       break;
1956     case FunctionEmissionStatus::TemplateDiscarded:
1957     case FunctionEmissionStatus::OMPDiscarded:
1958       Kind = SemaDiagnosticBuilder::K_Nop;
1959       break;
1960     case FunctionEmissionStatus::CUDADiscarded:
1961       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1962       break;
1963     }
1964   }
1965 
1966   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1967 }
1968 
1969 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1970                                                        unsigned DiagID,
1971                                                        FunctionDecl *FD) {
1972   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1973          "Expected OpenMP host compilation.");
1974 
1975   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1976   if (FD) {
1977     FunctionEmissionStatus FES = getEmissionStatus(FD);
1978     switch (FES) {
1979     case FunctionEmissionStatus::Emitted:
1980       Kind = SemaDiagnosticBuilder::K_Immediate;
1981       break;
1982     case FunctionEmissionStatus::Unknown:
1983       Kind = SemaDiagnosticBuilder::K_Deferred;
1984       break;
1985     case FunctionEmissionStatus::TemplateDiscarded:
1986     case FunctionEmissionStatus::OMPDiscarded:
1987     case FunctionEmissionStatus::CUDADiscarded:
1988       Kind = SemaDiagnosticBuilder::K_Nop;
1989       break;
1990     }
1991   }
1992 
1993   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1994 }
1995 
1996 static OpenMPDefaultmapClauseKind
1997 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1998   if (LO.OpenMP <= 45) {
1999     if (VD->getType().getNonReferenceType()->isScalarType())
2000       return OMPC_DEFAULTMAP_scalar;
2001     return OMPC_DEFAULTMAP_aggregate;
2002   }
2003   if (VD->getType().getNonReferenceType()->isAnyPointerType())
2004     return OMPC_DEFAULTMAP_pointer;
2005   if (VD->getType().getNonReferenceType()->isScalarType())
2006     return OMPC_DEFAULTMAP_scalar;
2007   return OMPC_DEFAULTMAP_aggregate;
2008 }
2009 
2010 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
2011                                  unsigned OpenMPCaptureLevel) const {
2012   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2013 
2014   ASTContext &Ctx = getASTContext();
2015   bool IsByRef = true;
2016 
2017   // Find the directive that is associated with the provided scope.
2018   D = cast<ValueDecl>(D->getCanonicalDecl());
2019   QualType Ty = D->getType();
2020 
2021   bool IsVariableUsedInMapClause = false;
2022   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
2023     // This table summarizes how a given variable should be passed to the device
2024     // given its type and the clauses where it appears. This table is based on
2025     // the description in OpenMP 4.5 [2.10.4, target Construct] and
2026     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
2027     //
2028     // =========================================================================
2029     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
2030     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
2031     // =========================================================================
2032     // | scl  |               |     |       |       -       |          | bycopy|
2033     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2034     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2035     // | scl  |       x       |     |       |       -       |          | byref |
2036     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2037     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2038     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2039     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2040     //
2041     // | agg  |      n.a.     |     |       |       -       |          | byref |
2042     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2043     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2044     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2045     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2046     //
2047     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2048     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2049     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2050     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2051     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2052     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2053     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2054     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2055     // =========================================================================
2056     // Legend:
2057     //  scl - scalar
2058     //  ptr - pointer
2059     //  agg - aggregate
2060     //  x - applies
2061     //  - - invalid in this combination
2062     //  [] - mapped with an array section
2063     //  byref - should be mapped by reference
2064     //  byval - should be mapped by value
2065     //  null - initialize a local variable to null on the device
2066     //
2067     // Observations:
2068     //  - All scalar declarations that show up in a map clause have to be passed
2069     //    by reference, because they may have been mapped in the enclosing data
2070     //    environment.
2071     //  - If the scalar value does not fit the size of uintptr, it has to be
2072     //    passed by reference, regardless the result in the table above.
2073     //  - For pointers mapped by value that have either an implicit map or an
2074     //    array section, the runtime library may pass the NULL value to the
2075     //    device instead of the value passed to it by the compiler.
2076 
2077     if (Ty->isReferenceType())
2078       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2079 
2080     // Locate map clauses and see if the variable being captured is referred to
2081     // in any of those clauses. Here we only care about variables, not fields,
2082     // because fields are part of aggregates.
2083     bool IsVariableAssociatedWithSection = false;
2084 
2085     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2086         D, Level,
2087         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2088          D](OMPClauseMappableExprCommon::MappableExprComponentListRef
2089                 MapExprComponents,
2090             OpenMPClauseKind WhereFoundClauseKind) {
2091           // Only the map clause information influences how a variable is
2092           // captured. E.g. is_device_ptr does not require changing the default
2093           // behavior.
2094           if (WhereFoundClauseKind != OMPC_map)
2095             return false;
2096 
2097           auto EI = MapExprComponents.rbegin();
2098           auto EE = MapExprComponents.rend();
2099 
2100           assert(EI != EE && "Invalid map expression!");
2101 
2102           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2103             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2104 
2105           ++EI;
2106           if (EI == EE)
2107             return false;
2108 
2109           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2110               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2111               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2112               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2113             IsVariableAssociatedWithSection = true;
2114             // There is nothing more we need to know about this variable.
2115             return true;
2116           }
2117 
2118           // Keep looking for more map info.
2119           return false;
2120         });
2121 
2122     if (IsVariableUsedInMapClause) {
2123       // If variable is identified in a map clause it is always captured by
2124       // reference except if it is a pointer that is dereferenced somehow.
2125       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2126     } else {
2127       // By default, all the data that has a scalar type is mapped by copy
2128       // (except for reduction variables).
2129       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2130       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2131                  !Ty->isAnyPointerType()) ||
2132                 !Ty->isScalarType() ||
2133                 DSAStack->isDefaultmapCapturedByRef(
2134                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2135                 DSAStack->hasExplicitDSA(
2136                     D,
2137                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2138                       return K == OMPC_reduction && !AppliedToPointee;
2139                     },
2140                     Level);
2141     }
2142   }
2143 
2144   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2145     IsByRef =
2146         ((IsVariableUsedInMapClause &&
2147           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2148               OMPD_target) ||
2149          !(DSAStack->hasExplicitDSA(
2150                D,
2151                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2152                  return K == OMPC_firstprivate ||
2153                         (K == OMPC_reduction && AppliedToPointee);
2154                },
2155                Level, /*NotLastprivate=*/true) ||
2156            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2157         // If the variable is artificial and must be captured by value - try to
2158         // capture by value.
2159         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2160           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2161         // If the variable is implicitly firstprivate and scalar - capture by
2162         // copy
2163         !((DSAStack->getDefaultDSA() == DSA_firstprivate ||
2164            DSAStack->getDefaultDSA() == DSA_private) &&
2165           !DSAStack->hasExplicitDSA(
2166               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2167               Level) &&
2168           !DSAStack->isLoopControlVariable(D, Level).first);
2169   }
2170 
2171   // When passing data by copy, we need to make sure it fits the uintptr size
2172   // and alignment, because the runtime library only deals with uintptr types.
2173   // If it does not fit the uintptr size, we need to pass the data by reference
2174   // instead.
2175   if (!IsByRef &&
2176       (Ctx.getTypeSizeInChars(Ty) >
2177            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2178        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2179     IsByRef = true;
2180   }
2181 
2182   return IsByRef;
2183 }
2184 
2185 unsigned Sema::getOpenMPNestingLevel() const {
2186   assert(getLangOpts().OpenMP);
2187   return DSAStack->getNestingLevel();
2188 }
2189 
2190 bool Sema::isInOpenMPTaskUntiedContext() const {
2191   return isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2192          DSAStack->isUntiedRegion();
2193 }
2194 
2195 bool Sema::isInOpenMPTargetExecutionDirective() const {
2196   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2197           !DSAStack->isClauseParsingMode()) ||
2198          DSAStack->hasDirective(
2199              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2200                 SourceLocation) -> bool {
2201                return isOpenMPTargetExecutionDirective(K);
2202              },
2203              false);
2204 }
2205 
2206 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2207                                     unsigned StopAt) {
2208   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2209   D = getCanonicalDecl(D);
2210 
2211   auto *VD = dyn_cast<VarDecl>(D);
2212   // Do not capture constexpr variables.
2213   if (VD && VD->isConstexpr())
2214     return nullptr;
2215 
2216   // If we want to determine whether the variable should be captured from the
2217   // perspective of the current capturing scope, and we've already left all the
2218   // capturing scopes of the top directive on the stack, check from the
2219   // perspective of its parent directive (if any) instead.
2220   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2221       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2222 
2223   // If we are attempting to capture a global variable in a directive with
2224   // 'target' we return true so that this global is also mapped to the device.
2225   //
2226   if (VD && !VD->hasLocalStorage() &&
2227       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2228     if (isInOpenMPTargetExecutionDirective()) {
2229       DSAStackTy::DSAVarData DVarTop =
2230           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2231       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2232         return VD;
2233       // If the declaration is enclosed in a 'declare target' directive,
2234       // then it should not be captured.
2235       //
2236       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2237         return nullptr;
2238       CapturedRegionScopeInfo *CSI = nullptr;
2239       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2240                llvm::reverse(FunctionScopes),
2241                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2242         if (!isa<CapturingScopeInfo>(FSI))
2243           return nullptr;
2244         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2245           if (RSI->CapRegionKind == CR_OpenMP) {
2246             CSI = RSI;
2247             break;
2248           }
2249       }
2250       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2251       SmallVector<OpenMPDirectiveKind, 4> Regions;
2252       getOpenMPCaptureRegions(Regions,
2253                               DSAStack->getDirective(CSI->OpenMPLevel));
2254       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2255         return VD;
2256     }
2257     if (isInOpenMPDeclareTargetContext()) {
2258       // Try to mark variable as declare target if it is used in capturing
2259       // regions.
2260       if (LangOpts.OpenMP <= 45 &&
2261           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2262         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2263       return nullptr;
2264     }
2265   }
2266 
2267   if (CheckScopeInfo) {
2268     bool OpenMPFound = false;
2269     for (unsigned I = StopAt + 1; I > 0; --I) {
2270       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2271       if (!isa<CapturingScopeInfo>(FSI))
2272         return nullptr;
2273       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2274         if (RSI->CapRegionKind == CR_OpenMP) {
2275           OpenMPFound = true;
2276           break;
2277         }
2278     }
2279     if (!OpenMPFound)
2280       return nullptr;
2281   }
2282 
2283   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2284       (!DSAStack->isClauseParsingMode() ||
2285        DSAStack->getParentDirective() != OMPD_unknown)) {
2286     auto &&Info = DSAStack->isLoopControlVariable(D);
2287     if (Info.first ||
2288         (VD && VD->hasLocalStorage() &&
2289          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2290         (VD && DSAStack->isForceVarCapturing()))
2291       return VD ? VD : Info.second;
2292     DSAStackTy::DSAVarData DVarTop =
2293         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2294     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2295         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2296       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2297     // Threadprivate variables must not be captured.
2298     if (isOpenMPThreadPrivate(DVarTop.CKind))
2299       return nullptr;
2300     // The variable is not private or it is the variable in the directive with
2301     // default(none) clause and not used in any clause.
2302     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2303         D,
2304         [](OpenMPClauseKind C, bool AppliedToPointee) {
2305           return isOpenMPPrivate(C) && !AppliedToPointee;
2306         },
2307         [](OpenMPDirectiveKind) { return true; },
2308         DSAStack->isClauseParsingMode());
2309     // Global shared must not be captured.
2310     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2311         ((DSAStack->getDefaultDSA() != DSA_none &&
2312           DSAStack->getDefaultDSA() != DSA_private &&
2313           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2314          DVarTop.CKind == OMPC_shared))
2315       return nullptr;
2316     if (DVarPrivate.CKind != OMPC_unknown ||
2317         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2318                 DSAStack->getDefaultDSA() == DSA_private ||
2319                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2320       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2321   }
2322   return nullptr;
2323 }
2324 
2325 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2326                                         unsigned Level) const {
2327   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2328 }
2329 
2330 void Sema::startOpenMPLoop() {
2331   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2332   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2333     DSAStack->loopInit();
2334 }
2335 
2336 void Sema::startOpenMPCXXRangeFor() {
2337   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2338   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2339     DSAStack->resetPossibleLoopCounter();
2340     DSAStack->loopStart();
2341   }
2342 }
2343 
2344 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2345                                            unsigned CapLevel) const {
2346   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2347   if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
2348     bool IsTriviallyCopyable =
2349         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2350         !D->getType()
2351              .getNonReferenceType()
2352              .getCanonicalType()
2353              ->getAsCXXRecordDecl();
2354     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2355     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2356     getOpenMPCaptureRegions(CaptureRegions, DKind);
2357     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2358         (IsTriviallyCopyable ||
2359          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2360       if (DSAStack->hasExplicitDSA(
2361               D,
2362               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2363               Level, /*NotLastprivate=*/true))
2364         return OMPC_firstprivate;
2365       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2366       if (DVar.CKind != OMPC_shared &&
2367           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2368         DSAStack->addImplicitTaskFirstprivate(Level, D);
2369         return OMPC_firstprivate;
2370       }
2371     }
2372   }
2373   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2374     if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2375       DSAStack->resetPossibleLoopCounter(D);
2376       DSAStack->loopStart();
2377       return OMPC_private;
2378     }
2379     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2380          DSAStack->isLoopControlVariable(D).first) &&
2381         !DSAStack->hasExplicitDSA(
2382             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2383             Level) &&
2384         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2385       return OMPC_private;
2386   }
2387   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2388     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2389         DSAStack->isForceVarCapturing() &&
2390         !DSAStack->hasExplicitDSA(
2391             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2392             Level))
2393       return OMPC_private;
2394   }
2395   // User-defined allocators are private since they must be defined in the
2396   // context of target region.
2397   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2398       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2399           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2400           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2401     return OMPC_private;
2402   return (DSAStack->hasExplicitDSA(
2403               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2404               Level) ||
2405           (DSAStack->isClauseParsingMode() &&
2406            DSAStack->getClauseParsingMode() == OMPC_private) ||
2407           // Consider taskgroup reduction descriptor variable a private
2408           // to avoid possible capture in the region.
2409           (DSAStack->hasExplicitDirective(
2410                [](OpenMPDirectiveKind K) {
2411                  return K == OMPD_taskgroup ||
2412                         ((isOpenMPParallelDirective(K) ||
2413                           isOpenMPWorksharingDirective(K)) &&
2414                          !isOpenMPSimdDirective(K));
2415                },
2416                Level) &&
2417            DSAStack->isTaskgroupReductionRef(D, Level)))
2418              ? OMPC_private
2419              : OMPC_unknown;
2420 }
2421 
2422 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2423                                 unsigned Level) {
2424   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2425   D = getCanonicalDecl(D);
2426   OpenMPClauseKind OMPC = OMPC_unknown;
2427   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2428     const unsigned NewLevel = I - 1;
2429     if (DSAStack->hasExplicitDSA(
2430             D,
2431             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2432               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2433                 OMPC = K;
2434                 return true;
2435               }
2436               return false;
2437             },
2438             NewLevel))
2439       break;
2440     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2441             D, NewLevel,
2442             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2443                OpenMPClauseKind) { return true; })) {
2444       OMPC = OMPC_map;
2445       break;
2446     }
2447     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2448                                        NewLevel)) {
2449       OMPC = OMPC_map;
2450       if (DSAStack->mustBeFirstprivateAtLevel(
2451               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2452         OMPC = OMPC_firstprivate;
2453       break;
2454     }
2455   }
2456   if (OMPC != OMPC_unknown)
2457     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2458 }
2459 
2460 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2461                                       unsigned CaptureLevel) const {
2462   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2463   // Return true if the current level is no longer enclosed in a target region.
2464 
2465   SmallVector<OpenMPDirectiveKind, 4> Regions;
2466   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2467   const auto *VD = dyn_cast<VarDecl>(D);
2468   return VD && !VD->hasLocalStorage() &&
2469          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2470                                         Level) &&
2471          Regions[CaptureLevel] != OMPD_task;
2472 }
2473 
2474 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2475                                       unsigned CaptureLevel) const {
2476   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2477   // Return true if the current level is no longer enclosed in a target region.
2478 
2479   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2480     if (!VD->hasLocalStorage()) {
2481       if (isInOpenMPTargetExecutionDirective())
2482         return true;
2483       DSAStackTy::DSAVarData TopDVar =
2484           DSAStack->getTopDSA(D, /*FromParent=*/false);
2485       unsigned NumLevels =
2486           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2487       if (Level == 0)
2488         // non-file scope static variale with default(firstprivate)
2489         // should be gloabal captured.
2490         return (NumLevels == CaptureLevel + 1 &&
2491                 (TopDVar.CKind != OMPC_shared ||
2492                  DSAStack->getDefaultDSA() == DSA_firstprivate));
2493       do {
2494         --Level;
2495         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2496         if (DVar.CKind != OMPC_shared)
2497           return true;
2498       } while (Level > 0);
2499     }
2500   }
2501   return true;
2502 }
2503 
2504 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2505 
2506 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2507                                           OMPTraitInfo &TI) {
2508   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2509 }
2510 
2511 void Sema::ActOnOpenMPEndDeclareVariant() {
2512   assert(isInOpenMPDeclareVariantScope() &&
2513          "Not in OpenMP declare variant scope!");
2514 
2515   OMPDeclareVariantScopes.pop_back();
2516 }
2517 
2518 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2519                                          const FunctionDecl *Callee,
2520                                          SourceLocation Loc) {
2521   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2522   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2523       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2524   // Ignore host functions during device analyzis.
2525   if (LangOpts.OpenMPIsDevice &&
2526       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2527     return;
2528   // Ignore nohost functions during host analyzis.
2529   if (!LangOpts.OpenMPIsDevice && DevTy &&
2530       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2531     return;
2532   const FunctionDecl *FD = Callee->getMostRecentDecl();
2533   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2534   if (LangOpts.OpenMPIsDevice && DevTy &&
2535       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2536     // Diagnose host function called during device codegen.
2537     StringRef HostDevTy =
2538         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2539     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2540     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2541          diag::note_omp_marked_device_type_here)
2542         << HostDevTy;
2543     return;
2544   }
2545   if (!LangOpts.OpenMPIsDevice && !LangOpts.OpenMPOffloadMandatory && DevTy &&
2546       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2547     // Diagnose nohost function called during host codegen.
2548     StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2549         OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2550     Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2551     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2552          diag::note_omp_marked_device_type_here)
2553         << NoHostDevTy;
2554   }
2555 }
2556 
2557 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2558                                const DeclarationNameInfo &DirName,
2559                                Scope *CurScope, SourceLocation Loc) {
2560   DSAStack->push(DKind, DirName, CurScope, Loc);
2561   PushExpressionEvaluationContext(
2562       ExpressionEvaluationContext::PotentiallyEvaluated);
2563 }
2564 
2565 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2566   DSAStack->setClauseParsingMode(K);
2567 }
2568 
2569 void Sema::EndOpenMPClause() {
2570   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2571   CleanupVarDeclMarking();
2572 }
2573 
2574 static std::pair<ValueDecl *, bool>
2575 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2576                SourceRange &ERange, bool AllowArraySection = false);
2577 
2578 /// Check consistency of the reduction clauses.
2579 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2580                                   ArrayRef<OMPClause *> Clauses) {
2581   bool InscanFound = false;
2582   SourceLocation InscanLoc;
2583   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2584   // A reduction clause without the inscan reduction-modifier may not appear on
2585   // a construct on which a reduction clause with the inscan reduction-modifier
2586   // appears.
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       InscanFound = true;
2593       InscanLoc = RC->getModifierLoc();
2594       continue;
2595     }
2596     if (RC->getModifier() == OMPC_REDUCTION_task) {
2597       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2598       // A reduction clause with the task reduction-modifier may only appear on
2599       // a parallel construct, a worksharing construct or a combined or
2600       // composite construct for which any of the aforementioned constructs is a
2601       // constituent construct and simd or loop are not constituent constructs.
2602       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2603       if (!(isOpenMPParallelDirective(CurDir) ||
2604             isOpenMPWorksharingDirective(CurDir)) ||
2605           isOpenMPSimdDirective(CurDir))
2606         S.Diag(RC->getModifierLoc(),
2607                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2608       continue;
2609     }
2610   }
2611   if (InscanFound) {
2612     for (OMPClause *C : Clauses) {
2613       if (C->getClauseKind() != OMPC_reduction)
2614         continue;
2615       auto *RC = cast<OMPReductionClause>(C);
2616       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2617         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2618                    ? RC->getBeginLoc()
2619                    : RC->getModifierLoc(),
2620                diag::err_omp_inscan_reduction_expected);
2621         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2622         continue;
2623       }
2624       for (Expr *Ref : RC->varlists()) {
2625         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2626         SourceLocation ELoc;
2627         SourceRange ERange;
2628         Expr *SimpleRefExpr = Ref;
2629         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2630                                   /*AllowArraySection=*/true);
2631         ValueDecl *D = Res.first;
2632         if (!D)
2633           continue;
2634         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2635           S.Diag(Ref->getExprLoc(),
2636                  diag::err_omp_reduction_not_inclusive_exclusive)
2637               << Ref->getSourceRange();
2638         }
2639       }
2640     }
2641   }
2642 }
2643 
2644 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2645                                  ArrayRef<OMPClause *> Clauses);
2646 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2647                                  bool WithInit);
2648 
2649 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2650                               const ValueDecl *D,
2651                               const DSAStackTy::DSAVarData &DVar,
2652                               bool IsLoopIterVar = false);
2653 
2654 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2655   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2656   //  A variable of class type (or array thereof) that appears in a lastprivate
2657   //  clause requires an accessible, unambiguous default constructor for the
2658   //  class type, unless the list item is also specified in a firstprivate
2659   //  clause.
2660   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2661     for (OMPClause *C : D->clauses()) {
2662       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2663         SmallVector<Expr *, 8> PrivateCopies;
2664         for (Expr *DE : Clause->varlists()) {
2665           if (DE->isValueDependent() || DE->isTypeDependent()) {
2666             PrivateCopies.push_back(nullptr);
2667             continue;
2668           }
2669           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2670           auto *VD = cast<VarDecl>(DRE->getDecl());
2671           QualType Type = VD->getType().getNonReferenceType();
2672           const DSAStackTy::DSAVarData DVar =
2673               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2674           if (DVar.CKind == OMPC_lastprivate) {
2675             // Generate helper private variable and initialize it with the
2676             // default value. The address of the original variable is replaced
2677             // by the address of the new private variable in CodeGen. This new
2678             // variable is not added to IdResolver, so the code in the OpenMP
2679             // region uses original variable for proper diagnostics.
2680             VarDecl *VDPrivate = buildVarDecl(
2681                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2682                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2683             ActOnUninitializedDecl(VDPrivate);
2684             if (VDPrivate->isInvalidDecl()) {
2685               PrivateCopies.push_back(nullptr);
2686               continue;
2687             }
2688             PrivateCopies.push_back(buildDeclRefExpr(
2689                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2690           } else {
2691             // The variable is also a firstprivate, so initialization sequence
2692             // for private copy is generated already.
2693             PrivateCopies.push_back(nullptr);
2694           }
2695         }
2696         Clause->setPrivateCopies(PrivateCopies);
2697         continue;
2698       }
2699       // Finalize nontemporal clause by handling private copies, if any.
2700       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2701         SmallVector<Expr *, 8> PrivateRefs;
2702         for (Expr *RefExpr : Clause->varlists()) {
2703           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2704           SourceLocation ELoc;
2705           SourceRange ERange;
2706           Expr *SimpleRefExpr = RefExpr;
2707           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2708           if (Res.second)
2709             // It will be analyzed later.
2710             PrivateRefs.push_back(RefExpr);
2711           ValueDecl *D = Res.first;
2712           if (!D)
2713             continue;
2714 
2715           const DSAStackTy::DSAVarData DVar =
2716               DSAStack->getTopDSA(D, /*FromParent=*/false);
2717           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2718                                                  : SimpleRefExpr);
2719         }
2720         Clause->setPrivateRefs(PrivateRefs);
2721         continue;
2722       }
2723       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2724         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2725           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2726           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2727           if (!DRE)
2728             continue;
2729           ValueDecl *VD = DRE->getDecl();
2730           if (!VD || !isa<VarDecl>(VD))
2731             continue;
2732           DSAStackTy::DSAVarData DVar =
2733               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2734           // OpenMP [2.12.5, target Construct]
2735           // Memory allocators that appear in a uses_allocators clause cannot
2736           // appear in other data-sharing attribute clauses or data-mapping
2737           // attribute clauses in the same construct.
2738           Expr *MapExpr = nullptr;
2739           if (DVar.RefExpr ||
2740               DSAStack->checkMappableExprComponentListsForDecl(
2741                   VD, /*CurrentRegionOnly=*/true,
2742                   [VD, &MapExpr](
2743                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2744                           MapExprComponents,
2745                       OpenMPClauseKind C) {
2746                     auto MI = MapExprComponents.rbegin();
2747                     auto ME = MapExprComponents.rend();
2748                     if (MI != ME &&
2749                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2750                             VD->getCanonicalDecl()) {
2751                       MapExpr = MI->getAssociatedExpression();
2752                       return true;
2753                     }
2754                     return false;
2755                   })) {
2756             Diag(D.Allocator->getExprLoc(),
2757                  diag::err_omp_allocator_used_in_clauses)
2758                 << D.Allocator->getSourceRange();
2759             if (DVar.RefExpr)
2760               reportOriginalDsa(*this, DSAStack, VD, DVar);
2761             else
2762               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2763                   << MapExpr->getSourceRange();
2764           }
2765         }
2766         continue;
2767       }
2768     }
2769     // Check allocate clauses.
2770     if (!CurContext->isDependentContext())
2771       checkAllocateClauses(*this, DSAStack, D->clauses());
2772     checkReductionClauses(*this, DSAStack, D->clauses());
2773   }
2774 
2775   DSAStack->pop();
2776   DiscardCleanupsInEvaluationContext();
2777   PopExpressionEvaluationContext();
2778 }
2779 
2780 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2781                                      Expr *NumIterations, Sema &SemaRef,
2782                                      Scope *S, DSAStackTy *Stack);
2783 
2784 namespace {
2785 
2786 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2787 private:
2788   Sema &SemaRef;
2789 
2790 public:
2791   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2792   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2793     NamedDecl *ND = Candidate.getCorrectionDecl();
2794     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2795       return VD->hasGlobalStorage() &&
2796              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2797                                    SemaRef.getCurScope());
2798     }
2799     return false;
2800   }
2801 
2802   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2803     return std::make_unique<VarDeclFilterCCC>(*this);
2804   }
2805 };
2806 
2807 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2808 private:
2809   Sema &SemaRef;
2810 
2811 public:
2812   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2813   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2814     NamedDecl *ND = Candidate.getCorrectionDecl();
2815     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2816                isa<FunctionDecl>(ND))) {
2817       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2818                                    SemaRef.getCurScope());
2819     }
2820     return false;
2821   }
2822 
2823   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2824     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2825   }
2826 };
2827 
2828 } // namespace
2829 
2830 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2831                                          CXXScopeSpec &ScopeSpec,
2832                                          const DeclarationNameInfo &Id,
2833                                          OpenMPDirectiveKind Kind) {
2834   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2835   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2836 
2837   if (Lookup.isAmbiguous())
2838     return ExprError();
2839 
2840   VarDecl *VD;
2841   if (!Lookup.isSingleResult()) {
2842     VarDeclFilterCCC CCC(*this);
2843     if (TypoCorrection Corrected =
2844             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2845                         CTK_ErrorRecovery)) {
2846       diagnoseTypo(Corrected,
2847                    PDiag(Lookup.empty()
2848                              ? diag::err_undeclared_var_use_suggest
2849                              : diag::err_omp_expected_var_arg_suggest)
2850                        << Id.getName());
2851       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2852     } else {
2853       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2854                                        : diag::err_omp_expected_var_arg)
2855           << Id.getName();
2856       return ExprError();
2857     }
2858   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2859     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2860     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2861     return ExprError();
2862   }
2863   Lookup.suppressDiagnostics();
2864 
2865   // OpenMP [2.9.2, Syntax, C/C++]
2866   //   Variables must be file-scope, namespace-scope, or static block-scope.
2867   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2868     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2869         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2870     bool IsDecl =
2871         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2872     Diag(VD->getLocation(),
2873          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2874         << VD;
2875     return ExprError();
2876   }
2877 
2878   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2879   NamedDecl *ND = CanonicalVD;
2880   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2881   //   A threadprivate directive for file-scope variables must appear outside
2882   //   any definition or declaration.
2883   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2884       !getCurLexicalContext()->isTranslationUnit()) {
2885     Diag(Id.getLoc(), diag::err_omp_var_scope)
2886         << getOpenMPDirectiveName(Kind) << VD;
2887     bool IsDecl =
2888         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2889     Diag(VD->getLocation(),
2890          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2891         << VD;
2892     return ExprError();
2893   }
2894   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2895   //   A threadprivate directive for static class member variables must appear
2896   //   in the class definition, in the same scope in which the member
2897   //   variables are declared.
2898   if (CanonicalVD->isStaticDataMember() &&
2899       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2900     Diag(Id.getLoc(), diag::err_omp_var_scope)
2901         << getOpenMPDirectiveName(Kind) << VD;
2902     bool IsDecl =
2903         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2904     Diag(VD->getLocation(),
2905          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2906         << VD;
2907     return ExprError();
2908   }
2909   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2910   //   A threadprivate directive for namespace-scope variables must appear
2911   //   outside any definition or declaration other than the namespace
2912   //   definition itself.
2913   if (CanonicalVD->getDeclContext()->isNamespace() &&
2914       (!getCurLexicalContext()->isFileContext() ||
2915        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2916     Diag(Id.getLoc(), diag::err_omp_var_scope)
2917         << getOpenMPDirectiveName(Kind) << VD;
2918     bool IsDecl =
2919         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2920     Diag(VD->getLocation(),
2921          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2922         << VD;
2923     return ExprError();
2924   }
2925   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2926   //   A threadprivate directive for static block-scope variables must appear
2927   //   in the scope of the variable and not in a nested scope.
2928   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2929       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2930     Diag(Id.getLoc(), diag::err_omp_var_scope)
2931         << getOpenMPDirectiveName(Kind) << VD;
2932     bool IsDecl =
2933         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2934     Diag(VD->getLocation(),
2935          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2936         << VD;
2937     return ExprError();
2938   }
2939 
2940   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2941   //   A threadprivate directive must lexically precede all references to any
2942   //   of the variables in its list.
2943   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2944       !DSAStack->isThreadPrivate(VD)) {
2945     Diag(Id.getLoc(), diag::err_omp_var_used)
2946         << getOpenMPDirectiveName(Kind) << VD;
2947     return ExprError();
2948   }
2949 
2950   QualType ExprType = VD->getType().getNonReferenceType();
2951   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2952                              SourceLocation(), VD,
2953                              /*RefersToEnclosingVariableOrCapture=*/false,
2954                              Id.getLoc(), ExprType, VK_LValue);
2955 }
2956 
2957 Sema::DeclGroupPtrTy
2958 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2959                                         ArrayRef<Expr *> VarList) {
2960   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2961     CurContext->addDecl(D);
2962     return DeclGroupPtrTy::make(DeclGroupRef(D));
2963   }
2964   return nullptr;
2965 }
2966 
2967 namespace {
2968 class LocalVarRefChecker final
2969     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2970   Sema &SemaRef;
2971 
2972 public:
2973   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2974     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2975       if (VD->hasLocalStorage()) {
2976         SemaRef.Diag(E->getBeginLoc(),
2977                      diag::err_omp_local_var_in_threadprivate_init)
2978             << E->getSourceRange();
2979         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2980             << VD << VD->getSourceRange();
2981         return true;
2982       }
2983     }
2984     return false;
2985   }
2986   bool VisitStmt(const Stmt *S) {
2987     for (const Stmt *Child : S->children()) {
2988       if (Child && Visit(Child))
2989         return true;
2990     }
2991     return false;
2992   }
2993   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2994 };
2995 } // namespace
2996 
2997 OMPThreadPrivateDecl *
2998 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2999   SmallVector<Expr *, 8> Vars;
3000   for (Expr *RefExpr : VarList) {
3001     auto *DE = cast<DeclRefExpr>(RefExpr);
3002     auto *VD = cast<VarDecl>(DE->getDecl());
3003     SourceLocation ILoc = DE->getExprLoc();
3004 
3005     // Mark variable as used.
3006     VD->setReferenced();
3007     VD->markUsed(Context);
3008 
3009     QualType QType = VD->getType();
3010     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
3011       // It will be analyzed later.
3012       Vars.push_back(DE);
3013       continue;
3014     }
3015 
3016     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
3017     //   A threadprivate variable must not have an incomplete type.
3018     if (RequireCompleteType(ILoc, VD->getType(),
3019                             diag::err_omp_threadprivate_incomplete_type)) {
3020       continue;
3021     }
3022 
3023     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
3024     //   A threadprivate variable must not have a reference type.
3025     if (VD->getType()->isReferenceType()) {
3026       Diag(ILoc, diag::err_omp_ref_type_arg)
3027           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
3028       bool IsDecl =
3029           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3030       Diag(VD->getLocation(),
3031            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3032           << VD;
3033       continue;
3034     }
3035 
3036     // Check if this is a TLS variable. If TLS is not being supported, produce
3037     // the corresponding diagnostic.
3038     if ((VD->getTLSKind() != VarDecl::TLS_None &&
3039          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
3040            getLangOpts().OpenMPUseTLS &&
3041            getASTContext().getTargetInfo().isTLSSupported())) ||
3042         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3043          !VD->isLocalVarDecl())) {
3044       Diag(ILoc, diag::err_omp_var_thread_local)
3045           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3046       bool IsDecl =
3047           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3048       Diag(VD->getLocation(),
3049            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3050           << VD;
3051       continue;
3052     }
3053 
3054     // Check if initial value of threadprivate variable reference variable with
3055     // local storage (it is not supported by runtime).
3056     if (const Expr *Init = VD->getAnyInitializer()) {
3057       LocalVarRefChecker Checker(*this);
3058       if (Checker.Visit(Init))
3059         continue;
3060     }
3061 
3062     Vars.push_back(RefExpr);
3063     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3064     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3065         Context, SourceRange(Loc, Loc)));
3066     if (ASTMutationListener *ML = Context.getASTMutationListener())
3067       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3068   }
3069   OMPThreadPrivateDecl *D = nullptr;
3070   if (!Vars.empty()) {
3071     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3072                                      Vars);
3073     D->setAccess(AS_public);
3074   }
3075   return D;
3076 }
3077 
3078 static OMPAllocateDeclAttr::AllocatorTypeTy
3079 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3080   if (!Allocator)
3081     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3082   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3083       Allocator->isInstantiationDependent() ||
3084       Allocator->containsUnexpandedParameterPack())
3085     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3086   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3087   const Expr *AE = Allocator->IgnoreParenImpCasts();
3088   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3089     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3090     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3091     llvm::FoldingSetNodeID AEId, DAEId;
3092     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3093     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3094     if (AEId == DAEId) {
3095       AllocatorKindRes = AllocatorKind;
3096       break;
3097     }
3098   }
3099   return AllocatorKindRes;
3100 }
3101 
3102 static bool checkPreviousOMPAllocateAttribute(
3103     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3104     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3105   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3106     return false;
3107   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3108   Expr *PrevAllocator = A->getAllocator();
3109   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3110       getAllocatorKind(S, Stack, PrevAllocator);
3111   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3112   if (AllocatorsMatch &&
3113       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3114       Allocator && PrevAllocator) {
3115     const Expr *AE = Allocator->IgnoreParenImpCasts();
3116     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3117     llvm::FoldingSetNodeID AEId, PAEId;
3118     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3119     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3120     AllocatorsMatch = AEId == PAEId;
3121   }
3122   if (!AllocatorsMatch) {
3123     SmallString<256> AllocatorBuffer;
3124     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3125     if (Allocator)
3126       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3127     SmallString<256> PrevAllocatorBuffer;
3128     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3129     if (PrevAllocator)
3130       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3131                                  S.getPrintingPolicy());
3132 
3133     SourceLocation AllocatorLoc =
3134         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3135     SourceRange AllocatorRange =
3136         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3137     SourceLocation PrevAllocatorLoc =
3138         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3139     SourceRange PrevAllocatorRange =
3140         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3141     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3142         << (Allocator ? 1 : 0) << AllocatorStream.str()
3143         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3144         << AllocatorRange;
3145     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3146         << PrevAllocatorRange;
3147     return true;
3148   }
3149   return false;
3150 }
3151 
3152 static void
3153 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3154                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3155                           Expr *Allocator, Expr *Alignment, SourceRange SR) {
3156   if (VD->hasAttr<OMPAllocateDeclAttr>())
3157     return;
3158   if (Alignment &&
3159       (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3160        Alignment->isInstantiationDependent() ||
3161        Alignment->containsUnexpandedParameterPack()))
3162     // Apply later when we have a usable value.
3163     return;
3164   if (Allocator &&
3165       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3166        Allocator->isInstantiationDependent() ||
3167        Allocator->containsUnexpandedParameterPack()))
3168     return;
3169   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3170                                                 Allocator, Alignment, SR);
3171   VD->addAttr(A);
3172   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3173     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3174 }
3175 
3176 Sema::DeclGroupPtrTy
3177 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
3178                                    ArrayRef<OMPClause *> Clauses,
3179                                    DeclContext *Owner) {
3180   assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3181   Expr *Alignment = nullptr;
3182   Expr *Allocator = nullptr;
3183   if (Clauses.empty()) {
3184     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3185     // allocate directives that appear in a target region must specify an
3186     // allocator clause unless a requires directive with the dynamic_allocators
3187     // clause is present in the same compilation unit.
3188     if (LangOpts.OpenMPIsDevice &&
3189         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3190       targetDiag(Loc, diag::err_expected_allocator_clause);
3191   } else {
3192     for (const OMPClause *C : Clauses)
3193       if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3194         Allocator = AC->getAllocator();
3195       else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3196         Alignment = AC->getAlignment();
3197       else
3198         llvm_unreachable("Unexpected clause on allocate directive");
3199   }
3200   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3201       getAllocatorKind(*this, DSAStack, Allocator);
3202   SmallVector<Expr *, 8> Vars;
3203   for (Expr *RefExpr : VarList) {
3204     auto *DE = cast<DeclRefExpr>(RefExpr);
3205     auto *VD = cast<VarDecl>(DE->getDecl());
3206 
3207     // Check if this is a TLS variable or global register.
3208     if (VD->getTLSKind() != VarDecl::TLS_None ||
3209         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3210         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3211          !VD->isLocalVarDecl()))
3212       continue;
3213 
3214     // If the used several times in the allocate directive, the same allocator
3215     // must be used.
3216     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3217                                           AllocatorKind, Allocator))
3218       continue;
3219 
3220     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3221     // If a list item has a static storage type, the allocator expression in the
3222     // allocator clause must be a constant expression that evaluates to one of
3223     // the predefined memory allocator values.
3224     if (Allocator && VD->hasGlobalStorage()) {
3225       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3226         Diag(Allocator->getExprLoc(),
3227              diag::err_omp_expected_predefined_allocator)
3228             << Allocator->getSourceRange();
3229         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3230                       VarDecl::DeclarationOnly;
3231         Diag(VD->getLocation(),
3232              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3233             << VD;
3234         continue;
3235       }
3236     }
3237 
3238     Vars.push_back(RefExpr);
3239     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
3240                               DE->getSourceRange());
3241   }
3242   if (Vars.empty())
3243     return nullptr;
3244   if (!Owner)
3245     Owner = getCurLexicalContext();
3246   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3247   D->setAccess(AS_public);
3248   Owner->addDecl(D);
3249   return DeclGroupPtrTy::make(DeclGroupRef(D));
3250 }
3251 
3252 Sema::DeclGroupPtrTy
3253 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3254                                    ArrayRef<OMPClause *> ClauseList) {
3255   OMPRequiresDecl *D = nullptr;
3256   if (!CurContext->isFileContext()) {
3257     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3258   } else {
3259     D = CheckOMPRequiresDecl(Loc, ClauseList);
3260     if (D) {
3261       CurContext->addDecl(D);
3262       DSAStack->addRequiresDecl(D);
3263     }
3264   }
3265   return DeclGroupPtrTy::make(DeclGroupRef(D));
3266 }
3267 
3268 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3269                                        OpenMPDirectiveKind DKind,
3270                                        ArrayRef<std::string> Assumptions,
3271                                        bool SkippedClauses) {
3272   if (!SkippedClauses && Assumptions.empty())
3273     Diag(Loc, diag::err_omp_no_clause_for_directive)
3274         << llvm::omp::getAllAssumeClauseOptions()
3275         << llvm::omp::getOpenMPDirectiveName(DKind);
3276 
3277   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3278   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3279     OMPAssumeScoped.push_back(AA);
3280     return;
3281   }
3282 
3283   // Global assumes without assumption clauses are ignored.
3284   if (Assumptions.empty())
3285     return;
3286 
3287   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3288          "Unexpected omp assumption directive!");
3289   OMPAssumeGlobal.push_back(AA);
3290 
3291   // The OMPAssumeGlobal scope above will take care of new declarations but
3292   // we also want to apply the assumption to existing ones, e.g., to
3293   // declarations in included headers. To this end, we traverse all existing
3294   // declaration contexts and annotate function declarations here.
3295   SmallVector<DeclContext *, 8> DeclContexts;
3296   auto *Ctx = CurContext;
3297   while (Ctx->getLexicalParent())
3298     Ctx = Ctx->getLexicalParent();
3299   DeclContexts.push_back(Ctx);
3300   while (!DeclContexts.empty()) {
3301     DeclContext *DC = DeclContexts.pop_back_val();
3302     for (auto *SubDC : DC->decls()) {
3303       if (SubDC->isInvalidDecl())
3304         continue;
3305       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3306         DeclContexts.push_back(CTD->getTemplatedDecl());
3307         llvm::append_range(DeclContexts, CTD->specializations());
3308         continue;
3309       }
3310       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3311         DeclContexts.push_back(DC);
3312       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3313         F->addAttr(AA);
3314         continue;
3315       }
3316     }
3317   }
3318 }
3319 
3320 void Sema::ActOnOpenMPEndAssumesDirective() {
3321   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3322   OMPAssumeScoped.pop_back();
3323 }
3324 
3325 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3326                                             ArrayRef<OMPClause *> ClauseList) {
3327   /// For target specific clauses, the requires directive cannot be
3328   /// specified after the handling of any of the target regions in the
3329   /// current compilation unit.
3330   ArrayRef<SourceLocation> TargetLocations =
3331       DSAStack->getEncounteredTargetLocs();
3332   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3333   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3334     for (const OMPClause *CNew : ClauseList) {
3335       // Check if any of the requires clauses affect target regions.
3336       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3337           isa<OMPUnifiedAddressClause>(CNew) ||
3338           isa<OMPReverseOffloadClause>(CNew) ||
3339           isa<OMPDynamicAllocatorsClause>(CNew)) {
3340         Diag(Loc, diag::err_omp_directive_before_requires)
3341             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3342         for (SourceLocation TargetLoc : TargetLocations) {
3343           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3344               << "target";
3345         }
3346       } else if (!AtomicLoc.isInvalid() &&
3347                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3348         Diag(Loc, diag::err_omp_directive_before_requires)
3349             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3350         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3351             << "atomic";
3352       }
3353     }
3354   }
3355 
3356   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3357     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3358                                    ClauseList);
3359   return nullptr;
3360 }
3361 
3362 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3363                               const ValueDecl *D,
3364                               const DSAStackTy::DSAVarData &DVar,
3365                               bool IsLoopIterVar) {
3366   if (DVar.RefExpr) {
3367     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3368         << getOpenMPClauseName(DVar.CKind);
3369     return;
3370   }
3371   enum {
3372     PDSA_StaticMemberShared,
3373     PDSA_StaticLocalVarShared,
3374     PDSA_LoopIterVarPrivate,
3375     PDSA_LoopIterVarLinear,
3376     PDSA_LoopIterVarLastprivate,
3377     PDSA_ConstVarShared,
3378     PDSA_GlobalVarShared,
3379     PDSA_TaskVarFirstprivate,
3380     PDSA_LocalVarPrivate,
3381     PDSA_Implicit
3382   } Reason = PDSA_Implicit;
3383   bool ReportHint = false;
3384   auto ReportLoc = D->getLocation();
3385   auto *VD = dyn_cast<VarDecl>(D);
3386   if (IsLoopIterVar) {
3387     if (DVar.CKind == OMPC_private)
3388       Reason = PDSA_LoopIterVarPrivate;
3389     else if (DVar.CKind == OMPC_lastprivate)
3390       Reason = PDSA_LoopIterVarLastprivate;
3391     else
3392       Reason = PDSA_LoopIterVarLinear;
3393   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3394              DVar.CKind == OMPC_firstprivate) {
3395     Reason = PDSA_TaskVarFirstprivate;
3396     ReportLoc = DVar.ImplicitDSALoc;
3397   } else if (VD && VD->isStaticLocal())
3398     Reason = PDSA_StaticLocalVarShared;
3399   else if (VD && VD->isStaticDataMember())
3400     Reason = PDSA_StaticMemberShared;
3401   else if (VD && VD->isFileVarDecl())
3402     Reason = PDSA_GlobalVarShared;
3403   else if (D->getType().isConstant(SemaRef.getASTContext()))
3404     Reason = PDSA_ConstVarShared;
3405   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3406     ReportHint = true;
3407     Reason = PDSA_LocalVarPrivate;
3408   }
3409   if (Reason != PDSA_Implicit) {
3410     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3411         << Reason << ReportHint
3412         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3413   } else if (DVar.ImplicitDSALoc.isValid()) {
3414     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3415         << getOpenMPClauseName(DVar.CKind);
3416   }
3417 }
3418 
3419 static OpenMPMapClauseKind
3420 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3421                              bool IsAggregateOrDeclareTarget) {
3422   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3423   switch (M) {
3424   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3425     Kind = OMPC_MAP_alloc;
3426     break;
3427   case OMPC_DEFAULTMAP_MODIFIER_to:
3428     Kind = OMPC_MAP_to;
3429     break;
3430   case OMPC_DEFAULTMAP_MODIFIER_from:
3431     Kind = OMPC_MAP_from;
3432     break;
3433   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3434     Kind = OMPC_MAP_tofrom;
3435     break;
3436   case OMPC_DEFAULTMAP_MODIFIER_present:
3437     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3438     // If implicit-behavior is present, each variable referenced in the
3439     // construct in the category specified by variable-category is treated as if
3440     // it had been listed in a map clause with the map-type of alloc and
3441     // map-type-modifier of present.
3442     Kind = OMPC_MAP_alloc;
3443     break;
3444   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3445   case OMPC_DEFAULTMAP_MODIFIER_last:
3446     llvm_unreachable("Unexpected defaultmap implicit behavior");
3447   case OMPC_DEFAULTMAP_MODIFIER_none:
3448   case OMPC_DEFAULTMAP_MODIFIER_default:
3449   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3450     // IsAggregateOrDeclareTarget could be true if:
3451     // 1. the implicit behavior for aggregate is tofrom
3452     // 2. it's a declare target link
3453     if (IsAggregateOrDeclareTarget) {
3454       Kind = OMPC_MAP_tofrom;
3455       break;
3456     }
3457     llvm_unreachable("Unexpected defaultmap implicit behavior");
3458   }
3459   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3460   return Kind;
3461 }
3462 
3463 namespace {
3464 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3465   DSAStackTy *Stack;
3466   Sema &SemaRef;
3467   bool ErrorFound = false;
3468   bool TryCaptureCXXThisMembers = false;
3469   CapturedStmt *CS = nullptr;
3470   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3471   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3472   llvm::SmallVector<Expr *, 4> ImplicitPrivate;
3473   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3474   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3475       ImplicitMapModifier[DefaultmapKindNum];
3476   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3477   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3478 
3479   void VisitSubCaptures(OMPExecutableDirective *S) {
3480     // Check implicitly captured variables.
3481     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3482       return;
3483     if (S->getDirectiveKind() == OMPD_atomic ||
3484         S->getDirectiveKind() == OMPD_critical ||
3485         S->getDirectiveKind() == OMPD_section ||
3486         S->getDirectiveKind() == OMPD_master ||
3487         S->getDirectiveKind() == OMPD_masked ||
3488         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3489       Visit(S->getAssociatedStmt());
3490       return;
3491     }
3492     visitSubCaptures(S->getInnermostCapturedStmt());
3493     // Try to capture inner this->member references to generate correct mappings
3494     // and diagnostics.
3495     if (TryCaptureCXXThisMembers ||
3496         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3497          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3498                       [](const CapturedStmt::Capture &C) {
3499                         return C.capturesThis();
3500                       }))) {
3501       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3502       TryCaptureCXXThisMembers = true;
3503       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3504       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3505     }
3506     // In tasks firstprivates are not captured anymore, need to analyze them
3507     // explicitly.
3508     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3509         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3510       for (OMPClause *C : S->clauses())
3511         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3512           for (Expr *Ref : FC->varlists())
3513             Visit(Ref);
3514         }
3515     }
3516   }
3517 
3518 public:
3519   void VisitDeclRefExpr(DeclRefExpr *E) {
3520     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3521         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3522         E->isInstantiationDependent())
3523       return;
3524     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3525       // Check the datasharing rules for the expressions in the clauses.
3526       if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
3527                   !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
3528         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3529           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3530             Visit(CED->getInit());
3531             return;
3532           }
3533       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3534         // Do not analyze internal variables and do not enclose them into
3535         // implicit clauses.
3536         return;
3537       VD = VD->getCanonicalDecl();
3538       // Skip internally declared variables.
3539       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3540           !Stack->isImplicitTaskFirstprivate(VD))
3541         return;
3542       // Skip allocators in uses_allocators clauses.
3543       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3544         return;
3545 
3546       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3547       // Check if the variable has explicit DSA set and stop analysis if it so.
3548       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3549         return;
3550 
3551       // Skip internally declared static variables.
3552       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3553           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3554       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3555           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3556            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3557           !Stack->isImplicitTaskFirstprivate(VD))
3558         return;
3559 
3560       SourceLocation ELoc = E->getExprLoc();
3561       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3562       // The default(none) clause requires that each variable that is referenced
3563       // in the construct, and does not have a predetermined data-sharing
3564       // attribute, must have its data-sharing attribute explicitly determined
3565       // by being listed in a data-sharing attribute clause.
3566       if (DVar.CKind == OMPC_unknown &&
3567           (Stack->getDefaultDSA() == DSA_none ||
3568            Stack->getDefaultDSA() == DSA_private ||
3569            Stack->getDefaultDSA() == DSA_firstprivate) &&
3570           isImplicitOrExplicitTaskingRegion(DKind) &&
3571           VarsWithInheritedDSA.count(VD) == 0) {
3572         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3573         if (!InheritedDSA && (Stack->getDefaultDSA() == DSA_firstprivate ||
3574                               Stack->getDefaultDSA() == DSA_private)) {
3575           DSAStackTy::DSAVarData DVar =
3576               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3577           InheritedDSA = DVar.CKind == OMPC_unknown;
3578         }
3579         if (InheritedDSA)
3580           VarsWithInheritedDSA[VD] = E;
3581         if (Stack->getDefaultDSA() == DSA_none)
3582           return;
3583       }
3584 
3585       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3586       // If implicit-behavior is none, each variable referenced in the
3587       // construct that does not have a predetermined data-sharing attribute
3588       // and does not appear in a to or link clause on a declare target
3589       // directive must be listed in a data-mapping attribute clause, a
3590       // data-sharing attribute clause (including a data-sharing attribute
3591       // clause on a combined construct where target. is one of the
3592       // constituent constructs), or an is_device_ptr clause.
3593       OpenMPDefaultmapClauseKind ClauseKind =
3594           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3595       if (SemaRef.getLangOpts().OpenMP >= 50) {
3596         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3597                               OMPC_DEFAULTMAP_MODIFIER_none;
3598         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3599             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3600           // Only check for data-mapping attribute and is_device_ptr here
3601           // since we have already make sure that the declaration does not
3602           // have a data-sharing attribute above
3603           if (!Stack->checkMappableExprComponentListsForDecl(
3604                   VD, /*CurrentRegionOnly=*/true,
3605                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3606                            MapExprComponents,
3607                        OpenMPClauseKind) {
3608                     auto MI = MapExprComponents.rbegin();
3609                     auto ME = MapExprComponents.rend();
3610                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3611                   })) {
3612             VarsWithInheritedDSA[VD] = E;
3613             return;
3614           }
3615         }
3616       }
3617       if (SemaRef.getLangOpts().OpenMP > 50) {
3618         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3619                                  OMPC_DEFAULTMAP_MODIFIER_present;
3620         if (IsModifierPresent) {
3621           if (llvm::find(ImplicitMapModifier[ClauseKind],
3622                          OMPC_MAP_MODIFIER_present) ==
3623               std::end(ImplicitMapModifier[ClauseKind])) {
3624             ImplicitMapModifier[ClauseKind].push_back(
3625                 OMPC_MAP_MODIFIER_present);
3626           }
3627         }
3628       }
3629 
3630       if (isOpenMPTargetExecutionDirective(DKind) &&
3631           !Stack->isLoopControlVariable(VD).first) {
3632         if (!Stack->checkMappableExprComponentListsForDecl(
3633                 VD, /*CurrentRegionOnly=*/true,
3634                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3635                            StackComponents,
3636                        OpenMPClauseKind) {
3637                   if (SemaRef.LangOpts.OpenMP >= 50)
3638                     return !StackComponents.empty();
3639                   // Variable is used if it has been marked as an array, array
3640                   // section, array shaping or the variable iself.
3641                   return StackComponents.size() == 1 ||
3642                          std::all_of(
3643                              std::next(StackComponents.rbegin()),
3644                              StackComponents.rend(),
3645                              [](const OMPClauseMappableExprCommon::
3646                                     MappableComponent &MC) {
3647                                return MC.getAssociatedDeclaration() ==
3648                                           nullptr &&
3649                                       (isa<OMPArraySectionExpr>(
3650                                            MC.getAssociatedExpression()) ||
3651                                        isa<OMPArrayShapingExpr>(
3652                                            MC.getAssociatedExpression()) ||
3653                                        isa<ArraySubscriptExpr>(
3654                                            MC.getAssociatedExpression()));
3655                              });
3656                 })) {
3657           bool IsFirstprivate = false;
3658           // By default lambdas are captured as firstprivates.
3659           if (const auto *RD =
3660                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3661             IsFirstprivate = RD->isLambda();
3662           IsFirstprivate =
3663               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3664           if (IsFirstprivate) {
3665             ImplicitFirstprivate.emplace_back(E);
3666           } else {
3667             OpenMPDefaultmapClauseModifier M =
3668                 Stack->getDefaultmapModifier(ClauseKind);
3669             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3670                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3671             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3672           }
3673           return;
3674         }
3675       }
3676 
3677       // OpenMP [2.9.3.6, Restrictions, p.2]
3678       //  A list item that appears in a reduction clause of the innermost
3679       //  enclosing worksharing or parallel construct may not be accessed in an
3680       //  explicit task.
3681       DVar = Stack->hasInnermostDSA(
3682           VD,
3683           [](OpenMPClauseKind C, bool AppliedToPointee) {
3684             return C == OMPC_reduction && !AppliedToPointee;
3685           },
3686           [](OpenMPDirectiveKind K) {
3687             return isOpenMPParallelDirective(K) ||
3688                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3689           },
3690           /*FromParent=*/true);
3691       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3692         ErrorFound = true;
3693         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3694         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3695         return;
3696       }
3697 
3698       // Define implicit data-sharing attributes for task.
3699       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3700       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3701            (((Stack->getDefaultDSA() == DSA_firstprivate &&
3702               DVar.CKind == OMPC_firstprivate) ||
3703              (Stack->getDefaultDSA() == DSA_private &&
3704               DVar.CKind == OMPC_private)) &&
3705             !DVar.RefExpr)) &&
3706           !Stack->isLoopControlVariable(VD).first) {
3707         if (Stack->getDefaultDSA() == DSA_private)
3708           ImplicitPrivate.push_back(E);
3709         else
3710           ImplicitFirstprivate.push_back(E);
3711         return;
3712       }
3713 
3714       // Store implicitly used globals with declare target link for parent
3715       // target.
3716       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3717           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3718         Stack->addToParentTargetRegionLinkGlobals(E);
3719         return;
3720       }
3721     }
3722   }
3723   void VisitMemberExpr(MemberExpr *E) {
3724     if (E->isTypeDependent() || E->isValueDependent() ||
3725         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3726       return;
3727     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3728     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3729     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3730       if (!FD)
3731         return;
3732       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3733       // Check if the variable has explicit DSA set and stop analysis if it
3734       // so.
3735       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3736         return;
3737 
3738       if (isOpenMPTargetExecutionDirective(DKind) &&
3739           !Stack->isLoopControlVariable(FD).first &&
3740           !Stack->checkMappableExprComponentListsForDecl(
3741               FD, /*CurrentRegionOnly=*/true,
3742               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3743                      StackComponents,
3744                  OpenMPClauseKind) {
3745                 return isa<CXXThisExpr>(
3746                     cast<MemberExpr>(
3747                         StackComponents.back().getAssociatedExpression())
3748                         ->getBase()
3749                         ->IgnoreParens());
3750               })) {
3751         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3752         //  A bit-field cannot appear in a map clause.
3753         //
3754         if (FD->isBitField())
3755           return;
3756 
3757         // Check to see if the member expression is referencing a class that
3758         // has already been explicitly mapped
3759         if (Stack->isClassPreviouslyMapped(TE->getType()))
3760           return;
3761 
3762         OpenMPDefaultmapClauseModifier Modifier =
3763             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3764         OpenMPDefaultmapClauseKind ClauseKind =
3765             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3766         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3767             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3768         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3769         return;
3770       }
3771 
3772       SourceLocation ELoc = E->getExprLoc();
3773       // OpenMP [2.9.3.6, Restrictions, p.2]
3774       //  A list item that appears in a reduction clause of the innermost
3775       //  enclosing worksharing or parallel construct may not be accessed in
3776       //  an  explicit task.
3777       DVar = Stack->hasInnermostDSA(
3778           FD,
3779           [](OpenMPClauseKind C, bool AppliedToPointee) {
3780             return C == OMPC_reduction && !AppliedToPointee;
3781           },
3782           [](OpenMPDirectiveKind K) {
3783             return isOpenMPParallelDirective(K) ||
3784                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3785           },
3786           /*FromParent=*/true);
3787       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3788         ErrorFound = true;
3789         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3790         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3791         return;
3792       }
3793 
3794       // Define implicit data-sharing attributes for task.
3795       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3796       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3797           !Stack->isLoopControlVariable(FD).first) {
3798         // Check if there is a captured expression for the current field in the
3799         // region. Do not mark it as firstprivate unless there is no captured
3800         // expression.
3801         // TODO: try to make it firstprivate.
3802         if (DVar.CKind != OMPC_unknown)
3803           ImplicitFirstprivate.push_back(E);
3804       }
3805       return;
3806     }
3807     if (isOpenMPTargetExecutionDirective(DKind)) {
3808       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3809       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3810                                         Stack->getCurrentDirective(),
3811                                         /*NoDiagnose=*/true))
3812         return;
3813       const auto *VD = cast<ValueDecl>(
3814           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3815       if (!Stack->checkMappableExprComponentListsForDecl(
3816               VD, /*CurrentRegionOnly=*/true,
3817               [&CurComponents](
3818                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3819                       StackComponents,
3820                   OpenMPClauseKind) {
3821                 auto CCI = CurComponents.rbegin();
3822                 auto CCE = CurComponents.rend();
3823                 for (const auto &SC : llvm::reverse(StackComponents)) {
3824                   // Do both expressions have the same kind?
3825                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3826                       SC.getAssociatedExpression()->getStmtClass())
3827                     if (!((isa<OMPArraySectionExpr>(
3828                                SC.getAssociatedExpression()) ||
3829                            isa<OMPArrayShapingExpr>(
3830                                SC.getAssociatedExpression())) &&
3831                           isa<ArraySubscriptExpr>(
3832                               CCI->getAssociatedExpression())))
3833                       return false;
3834 
3835                   const Decl *CCD = CCI->getAssociatedDeclaration();
3836                   const Decl *SCD = SC.getAssociatedDeclaration();
3837                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3838                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3839                   if (SCD != CCD)
3840                     return false;
3841                   std::advance(CCI, 1);
3842                   if (CCI == CCE)
3843                     break;
3844                 }
3845                 return true;
3846               })) {
3847         Visit(E->getBase());
3848       }
3849     } else if (!TryCaptureCXXThisMembers) {
3850       Visit(E->getBase());
3851     }
3852   }
3853   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3854     for (OMPClause *C : S->clauses()) {
3855       // Skip analysis of arguments of private clauses for task|target
3856       // directives.
3857       if (isa_and_nonnull<OMPPrivateClause>(C))
3858         continue;
3859       // Skip analysis of arguments of implicitly defined firstprivate clause
3860       // for task|target directives.
3861       // Skip analysis of arguments of implicitly defined map clause for target
3862       // directives.
3863       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3864                  C->isImplicit() &&
3865                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3866         for (Stmt *CC : C->children()) {
3867           if (CC)
3868             Visit(CC);
3869         }
3870       }
3871     }
3872     // Check implicitly captured variables.
3873     VisitSubCaptures(S);
3874   }
3875 
3876   void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
3877     // Loop transformation directives do not introduce data sharing
3878     VisitStmt(S);
3879   }
3880 
3881   void VisitCallExpr(CallExpr *S) {
3882     for (Stmt *C : S->arguments()) {
3883       if (C) {
3884         // Check implicitly captured variables in the task-based directives to
3885         // check if they must be firstprivatized.
3886         Visit(C);
3887       }
3888     }
3889     if (Expr *Callee = S->getCallee())
3890       if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts()))
3891         Visit(CE->getBase());
3892   }
3893   void VisitStmt(Stmt *S) {
3894     for (Stmt *C : S->children()) {
3895       if (C) {
3896         // Check implicitly captured variables in the task-based directives to
3897         // check if they must be firstprivatized.
3898         Visit(C);
3899       }
3900     }
3901   }
3902 
3903   void visitSubCaptures(CapturedStmt *S) {
3904     for (const CapturedStmt::Capture &Cap : S->captures()) {
3905       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3906         continue;
3907       VarDecl *VD = Cap.getCapturedVar();
3908       // Do not try to map the variable if it or its sub-component was mapped
3909       // already.
3910       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3911           Stack->checkMappableExprComponentListsForDecl(
3912               VD, /*CurrentRegionOnly=*/true,
3913               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3914                  OpenMPClauseKind) { return true; }))
3915         continue;
3916       DeclRefExpr *DRE = buildDeclRefExpr(
3917           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3918           Cap.getLocation(), /*RefersToCapture=*/true);
3919       Visit(DRE);
3920     }
3921   }
3922   bool isErrorFound() const { return ErrorFound; }
3923   ArrayRef<Expr *> getImplicitFirstprivate() const {
3924     return ImplicitFirstprivate;
3925   }
3926   ArrayRef<Expr *> getImplicitPrivate() const { return ImplicitPrivate; }
3927   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3928                                   OpenMPMapClauseKind MK) const {
3929     return ImplicitMap[DK][MK];
3930   }
3931   ArrayRef<OpenMPMapModifierKind>
3932   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3933     return ImplicitMapModifier[Kind];
3934   }
3935   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3936     return VarsWithInheritedDSA;
3937   }
3938 
3939   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3940       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3941     // Process declare target link variables for the target directives.
3942     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3943       for (DeclRefExpr *E : Stack->getLinkGlobals())
3944         Visit(E);
3945     }
3946   }
3947 };
3948 } // namespace
3949 
3950 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
3951                                                OpenMPDirectiveKind DKind,
3952                                                bool ScopeEntry) {
3953   SmallVector<llvm::omp::TraitProperty, 8> Traits;
3954   if (isOpenMPTargetExecutionDirective(DKind))
3955     Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
3956   if (isOpenMPTeamsDirective(DKind))
3957     Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
3958   if (isOpenMPParallelDirective(DKind))
3959     Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
3960   if (isOpenMPWorksharingDirective(DKind))
3961     Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
3962   if (isOpenMPSimdDirective(DKind))
3963     Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
3964   Stack->handleConstructTrait(Traits, ScopeEntry);
3965 }
3966 
3967 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3968   switch (DKind) {
3969   case OMPD_parallel:
3970   case OMPD_parallel_for:
3971   case OMPD_parallel_for_simd:
3972   case OMPD_parallel_sections:
3973   case OMPD_parallel_master:
3974   case OMPD_parallel_loop:
3975   case OMPD_teams:
3976   case OMPD_teams_distribute:
3977   case OMPD_teams_distribute_simd: {
3978     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3979     QualType KmpInt32PtrTy =
3980         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3981     Sema::CapturedParamNameType Params[] = {
3982         std::make_pair(".global_tid.", KmpInt32PtrTy),
3983         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3984         std::make_pair(StringRef(), QualType()) // __context with shared vars
3985     };
3986     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3987                              Params);
3988     break;
3989   }
3990   case OMPD_target_teams:
3991   case OMPD_target_parallel:
3992   case OMPD_target_parallel_for:
3993   case OMPD_target_parallel_for_simd:
3994   case OMPD_target_teams_loop:
3995   case OMPD_target_parallel_loop:
3996   case OMPD_target_teams_distribute:
3997   case OMPD_target_teams_distribute_simd: {
3998     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3999     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4000     QualType KmpInt32PtrTy =
4001         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4002     QualType Args[] = {VoidPtrTy};
4003     FunctionProtoType::ExtProtoInfo EPI;
4004     EPI.Variadic = true;
4005     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4006     Sema::CapturedParamNameType Params[] = {
4007         std::make_pair(".global_tid.", KmpInt32Ty),
4008         std::make_pair(".part_id.", KmpInt32PtrTy),
4009         std::make_pair(".privates.", VoidPtrTy),
4010         std::make_pair(
4011             ".copy_fn.",
4012             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4013         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4014         std::make_pair(StringRef(), QualType()) // __context with shared vars
4015     };
4016     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4017                              Params, /*OpenMPCaptureLevel=*/0);
4018     // Mark this captured region as inlined, because we don't use outlined
4019     // function directly.
4020     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4021         AlwaysInlineAttr::CreateImplicit(
4022             Context, {}, AttributeCommonInfo::AS_Keyword,
4023             AlwaysInlineAttr::Keyword_forceinline));
4024     Sema::CapturedParamNameType ParamsTarget[] = {
4025         std::make_pair(StringRef(), QualType()) // __context with shared vars
4026     };
4027     // Start a captured region for 'target' with no implicit parameters.
4028     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4029                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4030     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
4031         std::make_pair(".global_tid.", KmpInt32PtrTy),
4032         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4033         std::make_pair(StringRef(), QualType()) // __context with shared vars
4034     };
4035     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4036     // the same implicit parameters.
4037     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4038                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
4039     break;
4040   }
4041   case OMPD_target:
4042   case OMPD_target_simd: {
4043     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4044     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4045     QualType KmpInt32PtrTy =
4046         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4047     QualType Args[] = {VoidPtrTy};
4048     FunctionProtoType::ExtProtoInfo EPI;
4049     EPI.Variadic = true;
4050     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4051     Sema::CapturedParamNameType Params[] = {
4052         std::make_pair(".global_tid.", KmpInt32Ty),
4053         std::make_pair(".part_id.", KmpInt32PtrTy),
4054         std::make_pair(".privates.", VoidPtrTy),
4055         std::make_pair(
4056             ".copy_fn.",
4057             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4058         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4059         std::make_pair(StringRef(), QualType()) // __context with shared vars
4060     };
4061     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4062                              Params, /*OpenMPCaptureLevel=*/0);
4063     // Mark this captured region as inlined, because we don't use outlined
4064     // function directly.
4065     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4066         AlwaysInlineAttr::CreateImplicit(
4067             Context, {}, AttributeCommonInfo::AS_Keyword,
4068             AlwaysInlineAttr::Keyword_forceinline));
4069     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4070                              std::make_pair(StringRef(), QualType()),
4071                              /*OpenMPCaptureLevel=*/1);
4072     break;
4073   }
4074   case OMPD_atomic:
4075   case OMPD_critical:
4076   case OMPD_section:
4077   case OMPD_master:
4078   case OMPD_masked:
4079   case OMPD_tile:
4080   case OMPD_unroll:
4081     break;
4082   case OMPD_loop:
4083     // TODO: 'loop' may require additional parameters depending on the binding.
4084     // Treat similar to OMPD_simd/OMPD_for for now.
4085   case OMPD_simd:
4086   case OMPD_for:
4087   case OMPD_for_simd:
4088   case OMPD_sections:
4089   case OMPD_single:
4090   case OMPD_taskgroup:
4091   case OMPD_distribute:
4092   case OMPD_distribute_simd:
4093   case OMPD_ordered:
4094   case OMPD_target_data:
4095   case OMPD_dispatch: {
4096     Sema::CapturedParamNameType Params[] = {
4097         std::make_pair(StringRef(), QualType()) // __context with shared vars
4098     };
4099     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4100                              Params);
4101     break;
4102   }
4103   case OMPD_task: {
4104     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4105     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4106     QualType KmpInt32PtrTy =
4107         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4108     QualType Args[] = {VoidPtrTy};
4109     FunctionProtoType::ExtProtoInfo EPI;
4110     EPI.Variadic = true;
4111     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4112     Sema::CapturedParamNameType Params[] = {
4113         std::make_pair(".global_tid.", KmpInt32Ty),
4114         std::make_pair(".part_id.", KmpInt32PtrTy),
4115         std::make_pair(".privates.", VoidPtrTy),
4116         std::make_pair(
4117             ".copy_fn.",
4118             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4119         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4120         std::make_pair(StringRef(), QualType()) // __context with shared vars
4121     };
4122     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4123                              Params);
4124     // Mark this captured region as inlined, because we don't use outlined
4125     // function directly.
4126     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4127         AlwaysInlineAttr::CreateImplicit(
4128             Context, {}, AttributeCommonInfo::AS_Keyword,
4129             AlwaysInlineAttr::Keyword_forceinline));
4130     break;
4131   }
4132   case OMPD_taskloop:
4133   case OMPD_taskloop_simd:
4134   case OMPD_master_taskloop:
4135   case OMPD_master_taskloop_simd: {
4136     QualType KmpInt32Ty =
4137         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4138             .withConst();
4139     QualType KmpUInt64Ty =
4140         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4141             .withConst();
4142     QualType KmpInt64Ty =
4143         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4144             .withConst();
4145     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4146     QualType KmpInt32PtrTy =
4147         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4148     QualType Args[] = {VoidPtrTy};
4149     FunctionProtoType::ExtProtoInfo EPI;
4150     EPI.Variadic = true;
4151     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4152     Sema::CapturedParamNameType Params[] = {
4153         std::make_pair(".global_tid.", KmpInt32Ty),
4154         std::make_pair(".part_id.", KmpInt32PtrTy),
4155         std::make_pair(".privates.", VoidPtrTy),
4156         std::make_pair(
4157             ".copy_fn.",
4158             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4159         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4160         std::make_pair(".lb.", KmpUInt64Ty),
4161         std::make_pair(".ub.", KmpUInt64Ty),
4162         std::make_pair(".st.", KmpInt64Ty),
4163         std::make_pair(".liter.", KmpInt32Ty),
4164         std::make_pair(".reductions.", VoidPtrTy),
4165         std::make_pair(StringRef(), QualType()) // __context with shared vars
4166     };
4167     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4168                              Params);
4169     // Mark this captured region as inlined, because we don't use outlined
4170     // function directly.
4171     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4172         AlwaysInlineAttr::CreateImplicit(
4173             Context, {}, AttributeCommonInfo::AS_Keyword,
4174             AlwaysInlineAttr::Keyword_forceinline));
4175     break;
4176   }
4177   case OMPD_parallel_master_taskloop:
4178   case OMPD_parallel_master_taskloop_simd: {
4179     QualType KmpInt32Ty =
4180         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4181             .withConst();
4182     QualType KmpUInt64Ty =
4183         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4184             .withConst();
4185     QualType KmpInt64Ty =
4186         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4187             .withConst();
4188     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4189     QualType KmpInt32PtrTy =
4190         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4191     Sema::CapturedParamNameType ParamsParallel[] = {
4192         std::make_pair(".global_tid.", KmpInt32PtrTy),
4193         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4194         std::make_pair(StringRef(), QualType()) // __context with shared vars
4195     };
4196     // Start a captured region for 'parallel'.
4197     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4198                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4199     QualType Args[] = {VoidPtrTy};
4200     FunctionProtoType::ExtProtoInfo EPI;
4201     EPI.Variadic = true;
4202     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4203     Sema::CapturedParamNameType Params[] = {
4204         std::make_pair(".global_tid.", KmpInt32Ty),
4205         std::make_pair(".part_id.", KmpInt32PtrTy),
4206         std::make_pair(".privates.", VoidPtrTy),
4207         std::make_pair(
4208             ".copy_fn.",
4209             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4210         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4211         std::make_pair(".lb.", KmpUInt64Ty),
4212         std::make_pair(".ub.", KmpUInt64Ty),
4213         std::make_pair(".st.", KmpInt64Ty),
4214         std::make_pair(".liter.", KmpInt32Ty),
4215         std::make_pair(".reductions.", VoidPtrTy),
4216         std::make_pair(StringRef(), QualType()) // __context with shared vars
4217     };
4218     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4219                              Params, /*OpenMPCaptureLevel=*/1);
4220     // Mark this captured region as inlined, because we don't use outlined
4221     // function directly.
4222     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4223         AlwaysInlineAttr::CreateImplicit(
4224             Context, {}, AttributeCommonInfo::AS_Keyword,
4225             AlwaysInlineAttr::Keyword_forceinline));
4226     break;
4227   }
4228   case OMPD_distribute_parallel_for_simd:
4229   case OMPD_distribute_parallel_for: {
4230     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4231     QualType KmpInt32PtrTy =
4232         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4233     Sema::CapturedParamNameType Params[] = {
4234         std::make_pair(".global_tid.", KmpInt32PtrTy),
4235         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4236         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4237         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4238         std::make_pair(StringRef(), QualType()) // __context with shared vars
4239     };
4240     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4241                              Params);
4242     break;
4243   }
4244   case OMPD_target_teams_distribute_parallel_for:
4245   case OMPD_target_teams_distribute_parallel_for_simd: {
4246     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4247     QualType KmpInt32PtrTy =
4248         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4249     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4250 
4251     QualType Args[] = {VoidPtrTy};
4252     FunctionProtoType::ExtProtoInfo EPI;
4253     EPI.Variadic = true;
4254     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4255     Sema::CapturedParamNameType Params[] = {
4256         std::make_pair(".global_tid.", KmpInt32Ty),
4257         std::make_pair(".part_id.", KmpInt32PtrTy),
4258         std::make_pair(".privates.", VoidPtrTy),
4259         std::make_pair(
4260             ".copy_fn.",
4261             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4262         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4263         std::make_pair(StringRef(), QualType()) // __context with shared vars
4264     };
4265     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4266                              Params, /*OpenMPCaptureLevel=*/0);
4267     // Mark this captured region as inlined, because we don't use outlined
4268     // function directly.
4269     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4270         AlwaysInlineAttr::CreateImplicit(
4271             Context, {}, AttributeCommonInfo::AS_Keyword,
4272             AlwaysInlineAttr::Keyword_forceinline));
4273     Sema::CapturedParamNameType ParamsTarget[] = {
4274         std::make_pair(StringRef(), QualType()) // __context with shared vars
4275     };
4276     // Start a captured region for 'target' with no implicit parameters.
4277     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4278                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4279 
4280     Sema::CapturedParamNameType ParamsTeams[] = {
4281         std::make_pair(".global_tid.", KmpInt32PtrTy),
4282         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4283         std::make_pair(StringRef(), QualType()) // __context with shared vars
4284     };
4285     // Start a captured region for 'target' with no implicit parameters.
4286     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4287                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4288 
4289     Sema::CapturedParamNameType ParamsParallel[] = {
4290         std::make_pair(".global_tid.", KmpInt32PtrTy),
4291         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4292         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4293         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4294         std::make_pair(StringRef(), QualType()) // __context with shared vars
4295     };
4296     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4297     // the same implicit parameters.
4298     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4299                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4300     break;
4301   }
4302 
4303   case OMPD_teams_loop: {
4304     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4305     QualType KmpInt32PtrTy =
4306         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4307 
4308     Sema::CapturedParamNameType ParamsTeams[] = {
4309         std::make_pair(".global_tid.", KmpInt32PtrTy),
4310         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4311         std::make_pair(StringRef(), QualType()) // __context with shared vars
4312     };
4313     // Start a captured region for 'teams'.
4314     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4315                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4316     break;
4317   }
4318 
4319   case OMPD_teams_distribute_parallel_for:
4320   case OMPD_teams_distribute_parallel_for_simd: {
4321     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4322     QualType KmpInt32PtrTy =
4323         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4324 
4325     Sema::CapturedParamNameType ParamsTeams[] = {
4326         std::make_pair(".global_tid.", KmpInt32PtrTy),
4327         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4328         std::make_pair(StringRef(), QualType()) // __context with shared vars
4329     };
4330     // Start a captured region for 'target' with no implicit parameters.
4331     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4332                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4333 
4334     Sema::CapturedParamNameType ParamsParallel[] = {
4335         std::make_pair(".global_tid.", KmpInt32PtrTy),
4336         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4337         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4338         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4339         std::make_pair(StringRef(), QualType()) // __context with shared vars
4340     };
4341     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4342     // the same implicit parameters.
4343     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4344                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4345     break;
4346   }
4347   case OMPD_target_update:
4348   case OMPD_target_enter_data:
4349   case OMPD_target_exit_data: {
4350     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4351     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4352     QualType KmpInt32PtrTy =
4353         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4354     QualType Args[] = {VoidPtrTy};
4355     FunctionProtoType::ExtProtoInfo EPI;
4356     EPI.Variadic = true;
4357     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4358     Sema::CapturedParamNameType Params[] = {
4359         std::make_pair(".global_tid.", KmpInt32Ty),
4360         std::make_pair(".part_id.", KmpInt32PtrTy),
4361         std::make_pair(".privates.", VoidPtrTy),
4362         std::make_pair(
4363             ".copy_fn.",
4364             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4365         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4366         std::make_pair(StringRef(), QualType()) // __context with shared vars
4367     };
4368     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4369                              Params);
4370     // Mark this captured region as inlined, because we don't use outlined
4371     // function directly.
4372     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4373         AlwaysInlineAttr::CreateImplicit(
4374             Context, {}, AttributeCommonInfo::AS_Keyword,
4375             AlwaysInlineAttr::Keyword_forceinline));
4376     break;
4377   }
4378   case OMPD_threadprivate:
4379   case OMPD_allocate:
4380   case OMPD_taskyield:
4381   case OMPD_barrier:
4382   case OMPD_taskwait:
4383   case OMPD_cancellation_point:
4384   case OMPD_cancel:
4385   case OMPD_flush:
4386   case OMPD_depobj:
4387   case OMPD_scan:
4388   case OMPD_declare_reduction:
4389   case OMPD_declare_mapper:
4390   case OMPD_declare_simd:
4391   case OMPD_declare_target:
4392   case OMPD_end_declare_target:
4393   case OMPD_requires:
4394   case OMPD_declare_variant:
4395   case OMPD_begin_declare_variant:
4396   case OMPD_end_declare_variant:
4397   case OMPD_metadirective:
4398     llvm_unreachable("OpenMP Directive is not allowed");
4399   case OMPD_unknown:
4400   default:
4401     llvm_unreachable("Unknown OpenMP directive");
4402   }
4403   DSAStack->setContext(CurContext);
4404   handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
4405 }
4406 
4407 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4408   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4409 }
4410 
4411 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4412   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4413   getOpenMPCaptureRegions(CaptureRegions, DKind);
4414   return CaptureRegions.size();
4415 }
4416 
4417 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4418                                              Expr *CaptureExpr, bool WithInit,
4419                                              bool AsExpression) {
4420   assert(CaptureExpr);
4421   ASTContext &C = S.getASTContext();
4422   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4423   QualType Ty = Init->getType();
4424   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4425     if (S.getLangOpts().CPlusPlus) {
4426       Ty = C.getLValueReferenceType(Ty);
4427     } else {
4428       Ty = C.getPointerType(Ty);
4429       ExprResult Res =
4430           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4431       if (!Res.isUsable())
4432         return nullptr;
4433       Init = Res.get();
4434     }
4435     WithInit = true;
4436   }
4437   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4438                                           CaptureExpr->getBeginLoc());
4439   if (!WithInit)
4440     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4441   S.CurContext->addHiddenDecl(CED);
4442   Sema::TentativeAnalysisScope Trap(S);
4443   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4444   return CED;
4445 }
4446 
4447 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4448                                  bool WithInit) {
4449   OMPCapturedExprDecl *CD;
4450   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4451     CD = cast<OMPCapturedExprDecl>(VD);
4452   else
4453     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4454                           /*AsExpression=*/false);
4455   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4456                           CaptureExpr->getExprLoc());
4457 }
4458 
4459 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4460   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4461   if (!Ref) {
4462     OMPCapturedExprDecl *CD = buildCaptureDecl(
4463         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4464         /*WithInit=*/true, /*AsExpression=*/true);
4465     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4466                            CaptureExpr->getExprLoc());
4467   }
4468   ExprResult Res = Ref;
4469   if (!S.getLangOpts().CPlusPlus &&
4470       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4471       Ref->getType()->isPointerType()) {
4472     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4473     if (!Res.isUsable())
4474       return ExprError();
4475   }
4476   return S.DefaultLvalueConversion(Res.get());
4477 }
4478 
4479 namespace {
4480 // OpenMP directives parsed in this section are represented as a
4481 // CapturedStatement with an associated statement.  If a syntax error
4482 // is detected during the parsing of the associated statement, the
4483 // compiler must abort processing and close the CapturedStatement.
4484 //
4485 // Combined directives such as 'target parallel' have more than one
4486 // nested CapturedStatements.  This RAII ensures that we unwind out
4487 // of all the nested CapturedStatements when an error is found.
4488 class CaptureRegionUnwinderRAII {
4489 private:
4490   Sema &S;
4491   bool &ErrorFound;
4492   OpenMPDirectiveKind DKind = OMPD_unknown;
4493 
4494 public:
4495   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4496                             OpenMPDirectiveKind DKind)
4497       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4498   ~CaptureRegionUnwinderRAII() {
4499     if (ErrorFound) {
4500       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4501       while (--ThisCaptureLevel >= 0)
4502         S.ActOnCapturedRegionError();
4503     }
4504   }
4505 };
4506 } // namespace
4507 
4508 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4509   // Capture variables captured by reference in lambdas for target-based
4510   // directives.
4511   if (!CurContext->isDependentContext() &&
4512       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4513        isOpenMPTargetDataManagementDirective(
4514            DSAStack->getCurrentDirective()))) {
4515     QualType Type = V->getType();
4516     if (const auto *RD = Type.getCanonicalType()
4517                              .getNonReferenceType()
4518                              ->getAsCXXRecordDecl()) {
4519       bool SavedForceCaptureByReferenceInTargetExecutable =
4520           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4521       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4522           /*V=*/true);
4523       if (RD->isLambda()) {
4524         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4525         FieldDecl *ThisCapture;
4526         RD->getCaptureFields(Captures, ThisCapture);
4527         for (const LambdaCapture &LC : RD->captures()) {
4528           if (LC.getCaptureKind() == LCK_ByRef) {
4529             VarDecl *VD = LC.getCapturedVar();
4530             DeclContext *VDC = VD->getDeclContext();
4531             if (!VDC->Encloses(CurContext))
4532               continue;
4533             MarkVariableReferenced(LC.getLocation(), VD);
4534           } else if (LC.getCaptureKind() == LCK_This) {
4535             QualType ThisTy = getCurrentThisType();
4536             if (!ThisTy.isNull() &&
4537                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4538               CheckCXXThisCapture(LC.getLocation());
4539           }
4540         }
4541       }
4542       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4543           SavedForceCaptureByReferenceInTargetExecutable);
4544     }
4545   }
4546 }
4547 
4548 static bool checkOrderedOrderSpecified(Sema &S,
4549                                        const ArrayRef<OMPClause *> Clauses) {
4550   const OMPOrderedClause *Ordered = nullptr;
4551   const OMPOrderClause *Order = nullptr;
4552 
4553   for (const OMPClause *Clause : Clauses) {
4554     if (Clause->getClauseKind() == OMPC_ordered)
4555       Ordered = cast<OMPOrderedClause>(Clause);
4556     else if (Clause->getClauseKind() == OMPC_order) {
4557       Order = cast<OMPOrderClause>(Clause);
4558       if (Order->getKind() != OMPC_ORDER_concurrent)
4559         Order = nullptr;
4560     }
4561     if (Ordered && Order)
4562       break;
4563   }
4564 
4565   if (Ordered && Order) {
4566     S.Diag(Order->getKindKwLoc(),
4567            diag::err_omp_simple_clause_incompatible_with_ordered)
4568         << getOpenMPClauseName(OMPC_order)
4569         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4570         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4571     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4572         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4573     return true;
4574   }
4575   return false;
4576 }
4577 
4578 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4579                                       ArrayRef<OMPClause *> Clauses) {
4580   handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
4581                                      /* ScopeEntry */ false);
4582   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4583       DSAStack->getCurrentDirective() == OMPD_critical ||
4584       DSAStack->getCurrentDirective() == OMPD_section ||
4585       DSAStack->getCurrentDirective() == OMPD_master ||
4586       DSAStack->getCurrentDirective() == OMPD_masked)
4587     return S;
4588 
4589   bool ErrorFound = false;
4590   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4591       *this, ErrorFound, DSAStack->getCurrentDirective());
4592   if (!S.isUsable()) {
4593     ErrorFound = true;
4594     return StmtError();
4595   }
4596 
4597   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4598   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4599   OMPOrderedClause *OC = nullptr;
4600   OMPScheduleClause *SC = nullptr;
4601   SmallVector<const OMPLinearClause *, 4> LCs;
4602   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4603   // This is required for proper codegen.
4604   for (OMPClause *Clause : Clauses) {
4605     if (!LangOpts.OpenMPSimd &&
4606         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4607         Clause->getClauseKind() == OMPC_in_reduction) {
4608       // Capture taskgroup task_reduction descriptors inside the tasking regions
4609       // with the corresponding in_reduction items.
4610       auto *IRC = cast<OMPInReductionClause>(Clause);
4611       for (Expr *E : IRC->taskgroup_descriptors())
4612         if (E)
4613           MarkDeclarationsReferencedInExpr(E);
4614     }
4615     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4616         Clause->getClauseKind() == OMPC_copyprivate ||
4617         (getLangOpts().OpenMPUseTLS &&
4618          getASTContext().getTargetInfo().isTLSSupported() &&
4619          Clause->getClauseKind() == OMPC_copyin)) {
4620       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4621       // Mark all variables in private list clauses as used in inner region.
4622       for (Stmt *VarRef : Clause->children()) {
4623         if (auto *E = cast_or_null<Expr>(VarRef)) {
4624           MarkDeclarationsReferencedInExpr(E);
4625         }
4626       }
4627       DSAStack->setForceVarCapturing(/*V=*/false);
4628     } else if (isOpenMPLoopTransformationDirective(
4629                    DSAStack->getCurrentDirective())) {
4630       assert(CaptureRegions.empty() &&
4631              "No captured regions in loop transformation directives.");
4632     } else if (CaptureRegions.size() > 1 ||
4633                CaptureRegions.back() != OMPD_unknown) {
4634       if (auto *C = OMPClauseWithPreInit::get(Clause))
4635         PICs.push_back(C);
4636       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4637         if (Expr *E = C->getPostUpdateExpr())
4638           MarkDeclarationsReferencedInExpr(E);
4639       }
4640     }
4641     if (Clause->getClauseKind() == OMPC_schedule)
4642       SC = cast<OMPScheduleClause>(Clause);
4643     else if (Clause->getClauseKind() == OMPC_ordered)
4644       OC = cast<OMPOrderedClause>(Clause);
4645     else if (Clause->getClauseKind() == OMPC_linear)
4646       LCs.push_back(cast<OMPLinearClause>(Clause));
4647   }
4648   // Capture allocator expressions if used.
4649   for (Expr *E : DSAStack->getInnerAllocators())
4650     MarkDeclarationsReferencedInExpr(E);
4651   // OpenMP, 2.7.1 Loop Construct, Restrictions
4652   // The nonmonotonic modifier cannot be specified if an ordered clause is
4653   // specified.
4654   if (SC &&
4655       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4656        SC->getSecondScheduleModifier() ==
4657            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4658       OC) {
4659     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4660              ? SC->getFirstScheduleModifierLoc()
4661              : SC->getSecondScheduleModifierLoc(),
4662          diag::err_omp_simple_clause_incompatible_with_ordered)
4663         << getOpenMPClauseName(OMPC_schedule)
4664         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4665                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4666         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4667     ErrorFound = true;
4668   }
4669   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4670   // If an order(concurrent) clause is present, an ordered clause may not appear
4671   // on the same directive.
4672   if (checkOrderedOrderSpecified(*this, Clauses))
4673     ErrorFound = true;
4674   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4675     for (const OMPLinearClause *C : LCs) {
4676       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4677           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4678     }
4679     ErrorFound = true;
4680   }
4681   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4682       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4683       OC->getNumForLoops()) {
4684     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4685         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4686     ErrorFound = true;
4687   }
4688   if (ErrorFound) {
4689     return StmtError();
4690   }
4691   StmtResult SR = S;
4692   unsigned CompletedRegions = 0;
4693   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4694     // Mark all variables in private list clauses as used in inner region.
4695     // Required for proper codegen of combined directives.
4696     // TODO: add processing for other clauses.
4697     if (ThisCaptureRegion != OMPD_unknown) {
4698       for (const clang::OMPClauseWithPreInit *C : PICs) {
4699         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4700         // Find the particular capture region for the clause if the
4701         // directive is a combined one with multiple capture regions.
4702         // If the directive is not a combined one, the capture region
4703         // associated with the clause is OMPD_unknown and is generated
4704         // only once.
4705         if (CaptureRegion == ThisCaptureRegion ||
4706             CaptureRegion == OMPD_unknown) {
4707           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4708             for (Decl *D : DS->decls())
4709               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4710           }
4711         }
4712       }
4713     }
4714     if (ThisCaptureRegion == OMPD_target) {
4715       // Capture allocator traits in the target region. They are used implicitly
4716       // and, thus, are not captured by default.
4717       for (OMPClause *C : Clauses) {
4718         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4719           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4720                ++I) {
4721             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4722             if (Expr *E = D.AllocatorTraits)
4723               MarkDeclarationsReferencedInExpr(E);
4724           }
4725           continue;
4726         }
4727       }
4728     }
4729     if (ThisCaptureRegion == OMPD_parallel) {
4730       // Capture temp arrays for inscan reductions and locals in aligned
4731       // clauses.
4732       for (OMPClause *C : Clauses) {
4733         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4734           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4735             continue;
4736           for (Expr *E : RC->copy_array_temps())
4737             MarkDeclarationsReferencedInExpr(E);
4738         }
4739         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4740           for (Expr *E : AC->varlists())
4741             MarkDeclarationsReferencedInExpr(E);
4742         }
4743       }
4744     }
4745     if (++CompletedRegions == CaptureRegions.size())
4746       DSAStack->setBodyComplete();
4747     SR = ActOnCapturedRegionEnd(SR.get());
4748   }
4749   return SR;
4750 }
4751 
4752 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4753                               OpenMPDirectiveKind CancelRegion,
4754                               SourceLocation StartLoc) {
4755   // CancelRegion is only needed for cancel and cancellation_point.
4756   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4757     return false;
4758 
4759   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4760       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4761     return false;
4762 
4763   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4764       << getOpenMPDirectiveName(CancelRegion);
4765   return true;
4766 }
4767 
4768 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4769                                   OpenMPDirectiveKind CurrentRegion,
4770                                   const DeclarationNameInfo &CurrentName,
4771                                   OpenMPDirectiveKind CancelRegion,
4772                                   OpenMPBindClauseKind BindKind,
4773                                   SourceLocation StartLoc) {
4774   if (Stack->getCurScope()) {
4775     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4776     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4777     bool NestingProhibited = false;
4778     bool CloseNesting = true;
4779     bool OrphanSeen = false;
4780     enum {
4781       NoRecommend,
4782       ShouldBeInParallelRegion,
4783       ShouldBeInOrderedRegion,
4784       ShouldBeInTargetRegion,
4785       ShouldBeInTeamsRegion,
4786       ShouldBeInLoopSimdRegion,
4787     } Recommend = NoRecommend;
4788     if (isOpenMPSimdDirective(ParentRegion) &&
4789         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4790          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4791           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4792           CurrentRegion != OMPD_scan))) {
4793       // OpenMP [2.16, Nesting of Regions]
4794       // OpenMP constructs may not be nested inside a simd region.
4795       // OpenMP [2.8.1,simd Construct, Restrictions]
4796       // An ordered construct with the simd clause is the only OpenMP
4797       // construct that can appear in the simd region.
4798       // Allowing a SIMD construct nested in another SIMD construct is an
4799       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4800       // message.
4801       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4802       // The only OpenMP constructs that can be encountered during execution of
4803       // a simd region are the atomic construct, the loop construct, the simd
4804       // construct and the ordered construct with the simd clause.
4805       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4806                                  ? diag::err_omp_prohibited_region_simd
4807                                  : diag::warn_omp_nesting_simd)
4808           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4809       return CurrentRegion != OMPD_simd;
4810     }
4811     if (ParentRegion == OMPD_atomic) {
4812       // OpenMP [2.16, Nesting of Regions]
4813       // OpenMP constructs may not be nested inside an atomic region.
4814       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4815       return true;
4816     }
4817     if (CurrentRegion == OMPD_section) {
4818       // OpenMP [2.7.2, sections Construct, Restrictions]
4819       // Orphaned section directives are prohibited. That is, the section
4820       // directives must appear within the sections construct and must not be
4821       // encountered elsewhere in the sections region.
4822       if (ParentRegion != OMPD_sections &&
4823           ParentRegion != OMPD_parallel_sections) {
4824         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4825             << (ParentRegion != OMPD_unknown)
4826             << getOpenMPDirectiveName(ParentRegion);
4827         return true;
4828       }
4829       return false;
4830     }
4831     // Allow some constructs (except teams and cancellation constructs) to be
4832     // orphaned (they could be used in functions, called from OpenMP regions
4833     // with the required preconditions).
4834     if (ParentRegion == OMPD_unknown &&
4835         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4836         CurrentRegion != OMPD_cancellation_point &&
4837         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4838       return false;
4839     if (CurrentRegion == OMPD_cancellation_point ||
4840         CurrentRegion == OMPD_cancel) {
4841       // OpenMP [2.16, Nesting of Regions]
4842       // A cancellation point construct for which construct-type-clause is
4843       // taskgroup must be nested inside a task construct. A cancellation
4844       // point construct for which construct-type-clause is not taskgroup must
4845       // be closely nested inside an OpenMP construct that matches the type
4846       // specified in construct-type-clause.
4847       // A cancel construct for which construct-type-clause is taskgroup must be
4848       // nested inside a task construct. A cancel construct for which
4849       // construct-type-clause is not taskgroup must be closely nested inside an
4850       // OpenMP construct that matches the type specified in
4851       // construct-type-clause.
4852       NestingProhibited =
4853           !((CancelRegion == OMPD_parallel &&
4854              (ParentRegion == OMPD_parallel ||
4855               ParentRegion == OMPD_target_parallel)) ||
4856             (CancelRegion == OMPD_for &&
4857              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4858               ParentRegion == OMPD_target_parallel_for ||
4859               ParentRegion == OMPD_distribute_parallel_for ||
4860               ParentRegion == OMPD_teams_distribute_parallel_for ||
4861               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4862             (CancelRegion == OMPD_taskgroup &&
4863              (ParentRegion == OMPD_task ||
4864               (SemaRef.getLangOpts().OpenMP >= 50 &&
4865                (ParentRegion == OMPD_taskloop ||
4866                 ParentRegion == OMPD_master_taskloop ||
4867                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4868             (CancelRegion == OMPD_sections &&
4869              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4870               ParentRegion == OMPD_parallel_sections)));
4871       OrphanSeen = ParentRegion == OMPD_unknown;
4872     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4873       // OpenMP 5.1 [2.22, Nesting of Regions]
4874       // A masked region may not be closely nested inside a worksharing, loop,
4875       // atomic, task, or taskloop region.
4876       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4877                           isOpenMPGenericLoopDirective(ParentRegion) ||
4878                           isOpenMPTaskingDirective(ParentRegion);
4879     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4880       // OpenMP [2.16, Nesting of Regions]
4881       // A critical region may not be nested (closely or otherwise) inside a
4882       // critical region with the same name. Note that this restriction is not
4883       // sufficient to prevent deadlock.
4884       SourceLocation PreviousCriticalLoc;
4885       bool DeadLock = Stack->hasDirective(
4886           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4887                                               const DeclarationNameInfo &DNI,
4888                                               SourceLocation Loc) {
4889             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4890               PreviousCriticalLoc = Loc;
4891               return true;
4892             }
4893             return false;
4894           },
4895           false /* skip top directive */);
4896       if (DeadLock) {
4897         SemaRef.Diag(StartLoc,
4898                      diag::err_omp_prohibited_region_critical_same_name)
4899             << CurrentName.getName();
4900         if (PreviousCriticalLoc.isValid())
4901           SemaRef.Diag(PreviousCriticalLoc,
4902                        diag::note_omp_previous_critical_region);
4903         return true;
4904       }
4905     } else if (CurrentRegion == OMPD_barrier) {
4906       // OpenMP 5.1 [2.22, Nesting of Regions]
4907       // A barrier region may not be closely nested inside a worksharing, loop,
4908       // task, taskloop, critical, ordered, atomic, or masked region.
4909       NestingProhibited =
4910           isOpenMPWorksharingDirective(ParentRegion) ||
4911           isOpenMPGenericLoopDirective(ParentRegion) ||
4912           isOpenMPTaskingDirective(ParentRegion) ||
4913           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4914           ParentRegion == OMPD_parallel_master ||
4915           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4916     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4917                !isOpenMPParallelDirective(CurrentRegion) &&
4918                !isOpenMPTeamsDirective(CurrentRegion)) {
4919       // OpenMP 5.1 [2.22, Nesting of Regions]
4920       // A loop region that binds to a parallel region or a worksharing region
4921       // may not be closely nested inside a worksharing, loop, task, taskloop,
4922       // critical, ordered, atomic, or masked region.
4923       NestingProhibited =
4924           isOpenMPWorksharingDirective(ParentRegion) ||
4925           isOpenMPGenericLoopDirective(ParentRegion) ||
4926           isOpenMPTaskingDirective(ParentRegion) ||
4927           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4928           ParentRegion == OMPD_parallel_master ||
4929           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4930       Recommend = ShouldBeInParallelRegion;
4931     } else if (CurrentRegion == OMPD_ordered) {
4932       // OpenMP [2.16, Nesting of Regions]
4933       // An ordered region may not be closely nested inside a critical,
4934       // atomic, or explicit task region.
4935       // An ordered region must be closely nested inside a loop region (or
4936       // parallel loop region) with an ordered clause.
4937       // OpenMP [2.8.1,simd Construct, Restrictions]
4938       // An ordered construct with the simd clause is the only OpenMP construct
4939       // that can appear in the simd region.
4940       NestingProhibited = ParentRegion == OMPD_critical ||
4941                           isOpenMPTaskingDirective(ParentRegion) ||
4942                           !(isOpenMPSimdDirective(ParentRegion) ||
4943                             Stack->isParentOrderedRegion());
4944       Recommend = ShouldBeInOrderedRegion;
4945     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4946       // OpenMP [2.16, Nesting of Regions]
4947       // If specified, a teams construct must be contained within a target
4948       // construct.
4949       NestingProhibited =
4950           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4951           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4952            ParentRegion != OMPD_target);
4953       OrphanSeen = ParentRegion == OMPD_unknown;
4954       Recommend = ShouldBeInTargetRegion;
4955     } else if (CurrentRegion == OMPD_scan) {
4956       // OpenMP [2.16, Nesting of Regions]
4957       // If specified, a teams construct must be contained within a target
4958       // construct.
4959       NestingProhibited =
4960           SemaRef.LangOpts.OpenMP < 50 ||
4961           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4962            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4963            ParentRegion != OMPD_parallel_for_simd);
4964       OrphanSeen = ParentRegion == OMPD_unknown;
4965       Recommend = ShouldBeInLoopSimdRegion;
4966     }
4967     if (!NestingProhibited &&
4968         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4969         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4970         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4971       // OpenMP [5.1, 2.22, Nesting of Regions]
4972       // distribute, distribute simd, distribute parallel worksharing-loop,
4973       // distribute parallel worksharing-loop SIMD, loop, parallel regions,
4974       // including any parallel regions arising from combined constructs,
4975       // omp_get_num_teams() regions, and omp_get_team_num() regions are the
4976       // only OpenMP regions that may be strictly nested inside the teams
4977       // region.
4978       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4979                           !isOpenMPDistributeDirective(CurrentRegion) &&
4980                           CurrentRegion != OMPD_loop;
4981       Recommend = ShouldBeInParallelRegion;
4982     }
4983     if (!NestingProhibited && CurrentRegion == OMPD_loop) {
4984       // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
4985       // If the bind clause is present on the loop construct and binding is
4986       // teams then the corresponding loop region must be strictly nested inside
4987       // a teams region.
4988       NestingProhibited = BindKind == OMPC_BIND_teams &&
4989                           ParentRegion != OMPD_teams &&
4990                           ParentRegion != OMPD_target_teams;
4991       Recommend = ShouldBeInTeamsRegion;
4992     }
4993     if (!NestingProhibited &&
4994         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4995       // OpenMP 4.5 [2.17 Nesting of Regions]
4996       // The region associated with the distribute construct must be strictly
4997       // nested inside a teams region
4998       NestingProhibited =
4999           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
5000       Recommend = ShouldBeInTeamsRegion;
5001     }
5002     if (!NestingProhibited &&
5003         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
5004          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
5005       // OpenMP 4.5 [2.17 Nesting of Regions]
5006       // If a target, target update, target data, target enter data, or
5007       // target exit data construct is encountered during execution of a
5008       // target region, the behavior is unspecified.
5009       NestingProhibited = Stack->hasDirective(
5010           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
5011                              SourceLocation) {
5012             if (isOpenMPTargetExecutionDirective(K)) {
5013               OffendingRegion = K;
5014               return true;
5015             }
5016             return false;
5017           },
5018           false /* don't skip top directive */);
5019       CloseNesting = false;
5020     }
5021     if (NestingProhibited) {
5022       if (OrphanSeen) {
5023         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
5024             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
5025       } else {
5026         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
5027             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
5028             << Recommend << getOpenMPDirectiveName(CurrentRegion);
5029       }
5030       return true;
5031     }
5032   }
5033   return false;
5034 }
5035 
5036 struct Kind2Unsigned {
5037   using argument_type = OpenMPDirectiveKind;
5038   unsigned operator()(argument_type DK) { return unsigned(DK); }
5039 };
5040 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
5041                            ArrayRef<OMPClause *> Clauses,
5042                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
5043   bool ErrorFound = false;
5044   unsigned NamedModifiersNumber = 0;
5045   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
5046   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
5047   SmallVector<SourceLocation, 4> NameModifierLoc;
5048   for (const OMPClause *C : Clauses) {
5049     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
5050       // At most one if clause without a directive-name-modifier can appear on
5051       // the directive.
5052       OpenMPDirectiveKind CurNM = IC->getNameModifier();
5053       if (FoundNameModifiers[CurNM]) {
5054         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
5055             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
5056             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
5057         ErrorFound = true;
5058       } else if (CurNM != OMPD_unknown) {
5059         NameModifierLoc.push_back(IC->getNameModifierLoc());
5060         ++NamedModifiersNumber;
5061       }
5062       FoundNameModifiers[CurNM] = IC;
5063       if (CurNM == OMPD_unknown)
5064         continue;
5065       // Check if the specified name modifier is allowed for the current
5066       // directive.
5067       // At most one if clause with the particular directive-name-modifier can
5068       // appear on the directive.
5069       if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
5070         S.Diag(IC->getNameModifierLoc(),
5071                diag::err_omp_wrong_if_directive_name_modifier)
5072             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
5073         ErrorFound = true;
5074       }
5075     }
5076   }
5077   // If any if clause on the directive includes a directive-name-modifier then
5078   // all if clauses on the directive must include a directive-name-modifier.
5079   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5080     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5081       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5082              diag::err_omp_no_more_if_clause);
5083     } else {
5084       std::string Values;
5085       std::string Sep(", ");
5086       unsigned AllowedCnt = 0;
5087       unsigned TotalAllowedNum =
5088           AllowedNameModifiers.size() - NamedModifiersNumber;
5089       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5090            ++Cnt) {
5091         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5092         if (!FoundNameModifiers[NM]) {
5093           Values += "'";
5094           Values += getOpenMPDirectiveName(NM);
5095           Values += "'";
5096           if (AllowedCnt + 2 == TotalAllowedNum)
5097             Values += " or ";
5098           else if (AllowedCnt + 1 != TotalAllowedNum)
5099             Values += Sep;
5100           ++AllowedCnt;
5101         }
5102       }
5103       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5104              diag::err_omp_unnamed_if_clause)
5105           << (TotalAllowedNum > 1) << Values;
5106     }
5107     for (SourceLocation Loc : NameModifierLoc) {
5108       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5109     }
5110     ErrorFound = true;
5111   }
5112   return ErrorFound;
5113 }
5114 
5115 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
5116                                                    SourceLocation &ELoc,
5117                                                    SourceRange &ERange,
5118                                                    bool AllowArraySection) {
5119   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5120       RefExpr->containsUnexpandedParameterPack())
5121     return std::make_pair(nullptr, true);
5122 
5123   // OpenMP [3.1, C/C++]
5124   //  A list item is a variable name.
5125   // OpenMP  [2.9.3.3, Restrictions, p.1]
5126   //  A variable that is part of another variable (as an array or
5127   //  structure element) cannot appear in a private clause.
5128   RefExpr = RefExpr->IgnoreParens();
5129   enum {
5130     NoArrayExpr = -1,
5131     ArraySubscript = 0,
5132     OMPArraySection = 1
5133   } IsArrayExpr = NoArrayExpr;
5134   if (AllowArraySection) {
5135     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5136       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5137       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5138         Base = TempASE->getBase()->IgnoreParenImpCasts();
5139       RefExpr = Base;
5140       IsArrayExpr = ArraySubscript;
5141     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5142       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5143       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5144         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5145       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5146         Base = TempASE->getBase()->IgnoreParenImpCasts();
5147       RefExpr = Base;
5148       IsArrayExpr = OMPArraySection;
5149     }
5150   }
5151   ELoc = RefExpr->getExprLoc();
5152   ERange = RefExpr->getSourceRange();
5153   RefExpr = RefExpr->IgnoreParenImpCasts();
5154   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5155   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5156   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5157       (S.getCurrentThisType().isNull() || !ME ||
5158        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5159        !isa<FieldDecl>(ME->getMemberDecl()))) {
5160     if (IsArrayExpr != NoArrayExpr) {
5161       S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5162           << IsArrayExpr << ERange;
5163     } else {
5164       S.Diag(ELoc,
5165              AllowArraySection
5166                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5167                  : diag::err_omp_expected_var_name_member_expr)
5168           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5169     }
5170     return std::make_pair(nullptr, false);
5171   }
5172   return std::make_pair(
5173       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5174 }
5175 
5176 namespace {
5177 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5178 /// target regions.
5179 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5180   DSAStackTy *S = nullptr;
5181 
5182 public:
5183   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5184     return S->isUsesAllocatorsDecl(E->getDecl())
5185                .getValueOr(
5186                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5187            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5188   }
5189   bool VisitStmt(const Stmt *S) {
5190     for (const Stmt *Child : S->children()) {
5191       if (Child && Visit(Child))
5192         return true;
5193     }
5194     return false;
5195   }
5196   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5197 };
5198 } // namespace
5199 
5200 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5201                                  ArrayRef<OMPClause *> Clauses) {
5202   assert(!S.CurContext->isDependentContext() &&
5203          "Expected non-dependent context.");
5204   auto AllocateRange =
5205       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5206   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5207   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5208     return isOpenMPPrivate(C->getClauseKind());
5209   });
5210   for (OMPClause *Cl : PrivateRange) {
5211     MutableArrayRef<Expr *>::iterator I, It, Et;
5212     if (Cl->getClauseKind() == OMPC_private) {
5213       auto *PC = cast<OMPPrivateClause>(Cl);
5214       I = PC->private_copies().begin();
5215       It = PC->varlist_begin();
5216       Et = PC->varlist_end();
5217     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5218       auto *PC = cast<OMPFirstprivateClause>(Cl);
5219       I = PC->private_copies().begin();
5220       It = PC->varlist_begin();
5221       Et = PC->varlist_end();
5222     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5223       auto *PC = cast<OMPLastprivateClause>(Cl);
5224       I = PC->private_copies().begin();
5225       It = PC->varlist_begin();
5226       Et = PC->varlist_end();
5227     } else if (Cl->getClauseKind() == OMPC_linear) {
5228       auto *PC = cast<OMPLinearClause>(Cl);
5229       I = PC->privates().begin();
5230       It = PC->varlist_begin();
5231       Et = PC->varlist_end();
5232     } else if (Cl->getClauseKind() == OMPC_reduction) {
5233       auto *PC = cast<OMPReductionClause>(Cl);
5234       I = PC->privates().begin();
5235       It = PC->varlist_begin();
5236       Et = PC->varlist_end();
5237     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5238       auto *PC = cast<OMPTaskReductionClause>(Cl);
5239       I = PC->privates().begin();
5240       It = PC->varlist_begin();
5241       Et = PC->varlist_end();
5242     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5243       auto *PC = cast<OMPInReductionClause>(Cl);
5244       I = PC->privates().begin();
5245       It = PC->varlist_begin();
5246       Et = PC->varlist_end();
5247     } else {
5248       llvm_unreachable("Expected private clause.");
5249     }
5250     for (Expr *E : llvm::make_range(It, Et)) {
5251       if (!*I) {
5252         ++I;
5253         continue;
5254       }
5255       SourceLocation ELoc;
5256       SourceRange ERange;
5257       Expr *SimpleRefExpr = E;
5258       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5259                                 /*AllowArraySection=*/true);
5260       DeclToCopy.try_emplace(Res.first,
5261                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5262       ++I;
5263     }
5264   }
5265   for (OMPClause *C : AllocateRange) {
5266     auto *AC = cast<OMPAllocateClause>(C);
5267     if (S.getLangOpts().OpenMP >= 50 &&
5268         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5269         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5270         AC->getAllocator()) {
5271       Expr *Allocator = AC->getAllocator();
5272       // OpenMP, 2.12.5 target Construct
5273       // Memory allocators that do not appear in a uses_allocators clause cannot
5274       // appear as an allocator in an allocate clause or be used in the target
5275       // region unless a requires directive with the dynamic_allocators clause
5276       // is present in the same compilation unit.
5277       AllocatorChecker Checker(Stack);
5278       if (Checker.Visit(Allocator))
5279         S.Diag(Allocator->getExprLoc(),
5280                diag::err_omp_allocator_not_in_uses_allocators)
5281             << Allocator->getSourceRange();
5282     }
5283     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5284         getAllocatorKind(S, Stack, AC->getAllocator());
5285     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5286     // For task, taskloop or target directives, allocation requests to memory
5287     // allocators with the trait access set to thread result in unspecified
5288     // behavior.
5289     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5290         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5291          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5292       S.Diag(AC->getAllocator()->getExprLoc(),
5293              diag::warn_omp_allocate_thread_on_task_target_directive)
5294           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5295     }
5296     for (Expr *E : AC->varlists()) {
5297       SourceLocation ELoc;
5298       SourceRange ERange;
5299       Expr *SimpleRefExpr = E;
5300       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5301       ValueDecl *VD = Res.first;
5302       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5303       if (!isOpenMPPrivate(Data.CKind)) {
5304         S.Diag(E->getExprLoc(),
5305                diag::err_omp_expected_private_copy_for_allocate);
5306         continue;
5307       }
5308       VarDecl *PrivateVD = DeclToCopy[VD];
5309       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5310                                             AllocatorKind, AC->getAllocator()))
5311         continue;
5312       // Placeholder until allocate clause supports align modifier.
5313       Expr *Alignment = nullptr;
5314       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5315                                 Alignment, E->getSourceRange());
5316     }
5317   }
5318 }
5319 
5320 namespace {
5321 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5322 ///
5323 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5324 /// context. DeclRefExpr used inside the new context are changed to refer to the
5325 /// captured variable instead.
5326 class CaptureVars : public TreeTransform<CaptureVars> {
5327   using BaseTransform = TreeTransform<CaptureVars>;
5328 
5329 public:
5330   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5331 
5332   bool AlwaysRebuild() { return true; }
5333 };
5334 } // namespace
5335 
5336 static VarDecl *precomputeExpr(Sema &Actions,
5337                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5338                                StringRef Name) {
5339   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5340   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5341                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5342   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5343       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5344   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5345   BodyStmts.push_back(NewDeclStmt);
5346   return NewVar;
5347 }
5348 
5349 /// Create a closure that computes the number of iterations of a loop.
5350 ///
5351 /// \param Actions   The Sema object.
5352 /// \param LogicalTy Type for the logical iteration number.
5353 /// \param Rel       Comparison operator of the loop condition.
5354 /// \param StartExpr Value of the loop counter at the first iteration.
5355 /// \param StopExpr  Expression the loop counter is compared against in the loop
5356 /// condition. \param StepExpr      Amount of increment after each iteration.
5357 ///
5358 /// \return Closure (CapturedStmt) of the distance calculation.
5359 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5360                                        BinaryOperator::Opcode Rel,
5361                                        Expr *StartExpr, Expr *StopExpr,
5362                                        Expr *StepExpr) {
5363   ASTContext &Ctx = Actions.getASTContext();
5364   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5365 
5366   // Captured regions currently don't support return values, we use an
5367   // out-parameter instead. All inputs are implicit captures.
5368   // TODO: Instead of capturing each DeclRefExpr occurring in
5369   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5370   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5371   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5372                                           {StringRef(), QualType()}};
5373   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5374 
5375   Stmt *Body;
5376   {
5377     Sema::CompoundScopeRAII CompoundScope(Actions);
5378     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5379 
5380     // Get the LValue expression for the result.
5381     ImplicitParamDecl *DistParam = CS->getParam(0);
5382     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5383         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5384 
5385     SmallVector<Stmt *, 4> BodyStmts;
5386 
5387     // Capture all referenced variable references.
5388     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5389     // CapturedStmt, we could compute them before and capture the result, to be
5390     // used jointly with the LoopVar function.
5391     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5392     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5393     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5394     auto BuildVarRef = [&](VarDecl *VD) {
5395       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5396     };
5397 
5398     IntegerLiteral *Zero = IntegerLiteral::Create(
5399         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5400     IntegerLiteral *One = IntegerLiteral::Create(
5401         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5402     Expr *Dist;
5403     if (Rel == BO_NE) {
5404       // When using a != comparison, the increment can be +1 or -1. This can be
5405       // dynamic at runtime, so we need to check for the direction.
5406       Expr *IsNegStep = AssertSuccess(
5407           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5408 
5409       // Positive increment.
5410       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5411           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5412       ForwardRange = AssertSuccess(
5413           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5414       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5415           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5416 
5417       // Negative increment.
5418       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5419           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5420       BackwardRange = AssertSuccess(
5421           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5422       Expr *NegIncAmount = AssertSuccess(
5423           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5424       Expr *BackwardDist = AssertSuccess(
5425           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5426 
5427       // Use the appropriate case.
5428       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5429           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5430     } else {
5431       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5432              "Expected one of these relational operators");
5433 
5434       // We can derive the direction from any other comparison operator. It is
5435       // non well-formed OpenMP if Step increments/decrements in the other
5436       // directions. Whether at least the first iteration passes the loop
5437       // condition.
5438       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5439           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5440 
5441       // Compute the range between first and last counter value.
5442       Expr *Range;
5443       if (Rel == BO_GE || Rel == BO_GT)
5444         Range = AssertSuccess(Actions.BuildBinOp(
5445             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5446       else
5447         Range = AssertSuccess(Actions.BuildBinOp(
5448             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5449 
5450       // Ensure unsigned range space.
5451       Range =
5452           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5453 
5454       if (Rel == BO_LE || Rel == BO_GE) {
5455         // Add one to the range if the relational operator is inclusive.
5456         Range =
5457             AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One));
5458       }
5459 
5460       // Divide by the absolute step amount. If the range is not a multiple of
5461       // the step size, rounding-up the effective upper bound ensures that the
5462       // last iteration is included.
5463       // Note that the rounding-up may cause an overflow in a temporry that
5464       // could be avoided, but would have occurred in a C-style for-loop as well.
5465       Expr *Divisor = BuildVarRef(NewStep);
5466       if (Rel == BO_GE || Rel == BO_GT)
5467         Divisor =
5468             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5469       Expr *DivisorMinusOne =
5470           AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One));
5471       Expr *RangeRoundUp = AssertSuccess(
5472           Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne));
5473       Dist = AssertSuccess(
5474           Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor));
5475 
5476       // If there is not at least one iteration, the range contains garbage. Fix
5477       // to zero in this case.
5478       Dist = AssertSuccess(
5479           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5480     }
5481 
5482     // Assign the result to the out-parameter.
5483     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5484         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5485     BodyStmts.push_back(ResultAssign);
5486 
5487     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5488   }
5489 
5490   return cast<CapturedStmt>(
5491       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5492 }
5493 
5494 /// Create a closure that computes the loop variable from the logical iteration
5495 /// number.
5496 ///
5497 /// \param Actions   The Sema object.
5498 /// \param LoopVarTy Type for the loop variable used for result value.
5499 /// \param LogicalTy Type for the logical iteration number.
5500 /// \param StartExpr Value of the loop counter at the first iteration.
5501 /// \param Step      Amount of increment after each iteration.
5502 /// \param Deref     Whether the loop variable is a dereference of the loop
5503 /// counter variable.
5504 ///
5505 /// \return Closure (CapturedStmt) of the loop value calculation.
5506 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5507                                       QualType LogicalTy,
5508                                       DeclRefExpr *StartExpr, Expr *Step,
5509                                       bool Deref) {
5510   ASTContext &Ctx = Actions.getASTContext();
5511 
5512   // Pass the result as an out-parameter. Passing as return value would require
5513   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5514   // invoke a copy constructor.
5515   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5516   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5517                                           {"Logical", LogicalTy},
5518                                           {StringRef(), QualType()}};
5519   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5520 
5521   // Capture the initial iterator which represents the LoopVar value at the
5522   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5523   // it in every iteration, capture it by value before it is modified.
5524   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5525   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5526                                             Sema::TryCapture_ExplicitByVal, {});
5527   (void)Invalid;
5528   assert(!Invalid && "Expecting capture-by-value to work.");
5529 
5530   Expr *Body;
5531   {
5532     Sema::CompoundScopeRAII CompoundScope(Actions);
5533     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5534 
5535     ImplicitParamDecl *TargetParam = CS->getParam(0);
5536     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5537         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5538     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5539     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5540         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5541 
5542     // Capture the Start expression.
5543     CaptureVars Recap(Actions);
5544     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5545     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5546 
5547     Expr *Skip = AssertSuccess(
5548         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5549     // TODO: Explicitly cast to the iterator's difference_type instead of
5550     // relying on implicit conversion.
5551     Expr *Advanced =
5552         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5553 
5554     if (Deref) {
5555       // For range-based for-loops convert the loop counter value to a concrete
5556       // loop variable value by dereferencing the iterator.
5557       Advanced =
5558           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5559     }
5560 
5561     // Assign the result to the output parameter.
5562     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5563                                             BO_Assign, TargetRef, Advanced));
5564   }
5565   return cast<CapturedStmt>(
5566       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5567 }
5568 
5569 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5570   ASTContext &Ctx = getASTContext();
5571 
5572   // Extract the common elements of ForStmt and CXXForRangeStmt:
5573   // Loop variable, repeat condition, increment
5574   Expr *Cond, *Inc;
5575   VarDecl *LIVDecl, *LUVDecl;
5576   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5577     Stmt *Init = For->getInit();
5578     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5579       // For statement declares loop variable.
5580       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5581     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5582       // For statement reuses variable.
5583       assert(LCAssign->getOpcode() == BO_Assign &&
5584              "init part must be a loop variable assignment");
5585       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5586       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5587     } else
5588       llvm_unreachable("Cannot determine loop variable");
5589     LUVDecl = LIVDecl;
5590 
5591     Cond = For->getCond();
5592     Inc = For->getInc();
5593   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5594     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5595     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5596     LUVDecl = RangeFor->getLoopVariable();
5597 
5598     Cond = RangeFor->getCond();
5599     Inc = RangeFor->getInc();
5600   } else
5601     llvm_unreachable("unhandled kind of loop");
5602 
5603   QualType CounterTy = LIVDecl->getType();
5604   QualType LVTy = LUVDecl->getType();
5605 
5606   // Analyze the loop condition.
5607   Expr *LHS, *RHS;
5608   BinaryOperator::Opcode CondRel;
5609   Cond = Cond->IgnoreImplicit();
5610   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5611     LHS = CondBinExpr->getLHS();
5612     RHS = CondBinExpr->getRHS();
5613     CondRel = CondBinExpr->getOpcode();
5614   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5615     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5616     LHS = CondCXXOp->getArg(0);
5617     RHS = CondCXXOp->getArg(1);
5618     switch (CondCXXOp->getOperator()) {
5619     case OO_ExclaimEqual:
5620       CondRel = BO_NE;
5621       break;
5622     case OO_Less:
5623       CondRel = BO_LT;
5624       break;
5625     case OO_LessEqual:
5626       CondRel = BO_LE;
5627       break;
5628     case OO_Greater:
5629       CondRel = BO_GT;
5630       break;
5631     case OO_GreaterEqual:
5632       CondRel = BO_GE;
5633       break;
5634     default:
5635       llvm_unreachable("unexpected iterator operator");
5636     }
5637   } else
5638     llvm_unreachable("unexpected loop condition");
5639 
5640   // Normalize such that the loop counter is on the LHS.
5641   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5642       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5643     std::swap(LHS, RHS);
5644     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5645   }
5646   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5647 
5648   // Decide the bit width for the logical iteration counter. By default use the
5649   // unsigned ptrdiff_t integer size (for iterators and pointers).
5650   // TODO: For iterators, use iterator::difference_type,
5651   // std::iterator_traits<>::difference_type or decltype(it - end).
5652   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5653   if (CounterTy->isIntegerType()) {
5654     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5655     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5656   }
5657 
5658   // Analyze the loop increment.
5659   Expr *Step;
5660   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5661     int Direction;
5662     switch (IncUn->getOpcode()) {
5663     case UO_PreInc:
5664     case UO_PostInc:
5665       Direction = 1;
5666       break;
5667     case UO_PreDec:
5668     case UO_PostDec:
5669       Direction = -1;
5670       break;
5671     default:
5672       llvm_unreachable("unhandled unary increment operator");
5673     }
5674     Step = IntegerLiteral::Create(
5675         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5676   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5677     if (IncBin->getOpcode() == BO_AddAssign) {
5678       Step = IncBin->getRHS();
5679     } else if (IncBin->getOpcode() == BO_SubAssign) {
5680       Step =
5681           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5682     } else
5683       llvm_unreachable("unhandled binary increment operator");
5684   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5685     switch (CondCXXOp->getOperator()) {
5686     case OO_PlusPlus:
5687       Step = IntegerLiteral::Create(
5688           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5689       break;
5690     case OO_MinusMinus:
5691       Step = IntegerLiteral::Create(
5692           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5693       break;
5694     case OO_PlusEqual:
5695       Step = CondCXXOp->getArg(1);
5696       break;
5697     case OO_MinusEqual:
5698       Step = AssertSuccess(
5699           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5700       break;
5701     default:
5702       llvm_unreachable("unhandled overloaded increment operator");
5703     }
5704   } else
5705     llvm_unreachable("unknown increment expression");
5706 
5707   CapturedStmt *DistanceFunc =
5708       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5709   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5710       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5711   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5712                                         {}, nullptr, nullptr, {}, nullptr);
5713   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5714                                   LoopVarFunc, LVRef);
5715 }
5716 
5717 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
5718   // Handle a literal loop.
5719   if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
5720     return ActOnOpenMPCanonicalLoop(AStmt);
5721 
5722   // If not a literal loop, it must be the result of a loop transformation.
5723   OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
5724   assert(
5725       isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
5726       "Loop transformation directive expected");
5727   return LoopTransform;
5728 }
5729 
5730 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5731                                             CXXScopeSpec &MapperIdScopeSpec,
5732                                             const DeclarationNameInfo &MapperId,
5733                                             QualType Type,
5734                                             Expr *UnresolvedMapper);
5735 
5736 /// Perform DFS through the structure/class data members trying to find
5737 /// member(s) with user-defined 'default' mapper and generate implicit map
5738 /// clauses for such members with the found 'default' mapper.
5739 static void
5740 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5741                                       SmallVectorImpl<OMPClause *> &Clauses) {
5742   // Check for the deault mapper for data members.
5743   if (S.getLangOpts().OpenMP < 50)
5744     return;
5745   SmallVector<OMPClause *, 4> ImplicitMaps;
5746   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5747     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5748     if (!C)
5749       continue;
5750     SmallVector<Expr *, 4> SubExprs;
5751     auto *MI = C->mapperlist_begin();
5752     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5753          ++I, ++MI) {
5754       // Expression is mapped using mapper - skip it.
5755       if (*MI)
5756         continue;
5757       Expr *E = *I;
5758       // Expression is dependent - skip it, build the mapper when it gets
5759       // instantiated.
5760       if (E->isTypeDependent() || E->isValueDependent() ||
5761           E->containsUnexpandedParameterPack())
5762         continue;
5763       // Array section - need to check for the mapping of the array section
5764       // element.
5765       QualType CanonType = E->getType().getCanonicalType();
5766       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5767         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5768         QualType BaseType =
5769             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5770         QualType ElemType;
5771         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5772           ElemType = ATy->getElementType();
5773         else
5774           ElemType = BaseType->getPointeeType();
5775         CanonType = ElemType;
5776       }
5777 
5778       // DFS over data members in structures/classes.
5779       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5780           1, {CanonType, nullptr});
5781       llvm::DenseMap<const Type *, Expr *> Visited;
5782       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5783           1, {nullptr, 1});
5784       while (!Types.empty()) {
5785         QualType BaseType;
5786         FieldDecl *CurFD;
5787         std::tie(BaseType, CurFD) = Types.pop_back_val();
5788         while (ParentChain.back().second == 0)
5789           ParentChain.pop_back();
5790         --ParentChain.back().second;
5791         if (BaseType.isNull())
5792           continue;
5793         // Only structs/classes are allowed to have mappers.
5794         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5795         if (!RD)
5796           continue;
5797         auto It = Visited.find(BaseType.getTypePtr());
5798         if (It == Visited.end()) {
5799           // Try to find the associated user-defined mapper.
5800           CXXScopeSpec MapperIdScopeSpec;
5801           DeclarationNameInfo DefaultMapperId;
5802           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5803               &S.Context.Idents.get("default")));
5804           DefaultMapperId.setLoc(E->getExprLoc());
5805           ExprResult ER = buildUserDefinedMapperRef(
5806               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5807               BaseType, /*UnresolvedMapper=*/nullptr);
5808           if (ER.isInvalid())
5809             continue;
5810           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5811         }
5812         // Found default mapper.
5813         if (It->second) {
5814           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5815                                                      VK_LValue, OK_Ordinary, E);
5816           OE->setIsUnique(/*V=*/true);
5817           Expr *BaseExpr = OE;
5818           for (const auto &P : ParentChain) {
5819             if (P.first) {
5820               BaseExpr = S.BuildMemberExpr(
5821                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5822                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5823                   DeclAccessPair::make(P.first, P.first->getAccess()),
5824                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5825                   P.first->getType(), VK_LValue, OK_Ordinary);
5826               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5827             }
5828           }
5829           if (CurFD)
5830             BaseExpr = S.BuildMemberExpr(
5831                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5832                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5833                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5834                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5835                 CurFD->getType(), VK_LValue, OK_Ordinary);
5836           SubExprs.push_back(BaseExpr);
5837           continue;
5838         }
5839         // Check for the "default" mapper for data members.
5840         bool FirstIter = true;
5841         for (FieldDecl *FD : RD->fields()) {
5842           if (!FD)
5843             continue;
5844           QualType FieldTy = FD->getType();
5845           if (FieldTy.isNull() ||
5846               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5847             continue;
5848           if (FirstIter) {
5849             FirstIter = false;
5850             ParentChain.emplace_back(CurFD, 1);
5851           } else {
5852             ++ParentChain.back().second;
5853           }
5854           Types.emplace_back(FieldTy, FD);
5855         }
5856       }
5857     }
5858     if (SubExprs.empty())
5859       continue;
5860     CXXScopeSpec MapperIdScopeSpec;
5861     DeclarationNameInfo MapperId;
5862     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5863             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5864             MapperIdScopeSpec, MapperId, C->getMapType(),
5865             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5866             SubExprs, OMPVarListLocTy()))
5867       Clauses.push_back(NewClause);
5868   }
5869 }
5870 
5871 StmtResult Sema::ActOnOpenMPExecutableDirective(
5872     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5873     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5874     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5875   StmtResult Res = StmtError();
5876   OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
5877   if (const OMPBindClause *BC =
5878           OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
5879     BindKind = BC->getBindKind();
5880   // First check CancelRegion which is then used in checkNestingOfRegions.
5881   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5882       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5883                             BindKind, StartLoc))
5884     return StmtError();
5885 
5886   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5887   VarsWithInheritedDSAType VarsWithInheritedDSA;
5888   bool ErrorFound = false;
5889   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5890   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5891       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5892       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5893     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5894 
5895     // Check default data sharing attributes for referenced variables.
5896     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5897     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5898     Stmt *S = AStmt;
5899     while (--ThisCaptureLevel >= 0)
5900       S = cast<CapturedStmt>(S)->getCapturedStmt();
5901     DSAChecker.Visit(S);
5902     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5903         !isOpenMPTaskingDirective(Kind)) {
5904       // Visit subcaptures to generate implicit clauses for captured vars.
5905       auto *CS = cast<CapturedStmt>(AStmt);
5906       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5907       getOpenMPCaptureRegions(CaptureRegions, Kind);
5908       // Ignore outer tasking regions for target directives.
5909       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5910         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5911       DSAChecker.visitSubCaptures(CS);
5912     }
5913     if (DSAChecker.isErrorFound())
5914       return StmtError();
5915     // Generate list of implicitly defined firstprivate variables.
5916     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5917 
5918     SmallVector<Expr *, 4> ImplicitFirstprivates(
5919         DSAChecker.getImplicitFirstprivate().begin(),
5920         DSAChecker.getImplicitFirstprivate().end());
5921     SmallVector<Expr *, 4> ImplicitPrivates(
5922         DSAChecker.getImplicitPrivate().begin(),
5923         DSAChecker.getImplicitPrivate().end());
5924     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5925     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5926     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5927         ImplicitMapModifiers[DefaultmapKindNum];
5928     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5929         ImplicitMapModifiersLoc[DefaultmapKindNum];
5930     // Get the original location of present modifier from Defaultmap clause.
5931     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5932     for (OMPClause *C : Clauses) {
5933       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5934         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5935           PresentModifierLocs[DMC->getDefaultmapKind()] =
5936               DMC->getDefaultmapModifierLoc();
5937     }
5938     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5939       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5940       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5941         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5942             Kind, static_cast<OpenMPMapClauseKind>(I));
5943         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5944       }
5945       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5946           DSAChecker.getImplicitMapModifier(Kind);
5947       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5948                                       ImplicitModifier.end());
5949       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5950                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5951     }
5952     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5953     for (OMPClause *C : Clauses) {
5954       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5955         for (Expr *E : IRC->taskgroup_descriptors())
5956           if (E)
5957             ImplicitFirstprivates.emplace_back(E);
5958       }
5959       // OpenMP 5.0, 2.10.1 task Construct
5960       // [detach clause]... The event-handle will be considered as if it was
5961       // specified on a firstprivate clause.
5962       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5963         ImplicitFirstprivates.push_back(DC->getEventHandler());
5964     }
5965     if (!ImplicitFirstprivates.empty()) {
5966       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5967               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5968               SourceLocation())) {
5969         ClausesWithImplicit.push_back(Implicit);
5970         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5971                      ImplicitFirstprivates.size();
5972       } else {
5973         ErrorFound = true;
5974       }
5975     }
5976     if (!ImplicitPrivates.empty()) {
5977       if (OMPClause *Implicit =
5978               ActOnOpenMPPrivateClause(ImplicitPrivates, SourceLocation(),
5979                                        SourceLocation(), SourceLocation())) {
5980         ClausesWithImplicit.push_back(Implicit);
5981         ErrorFound = cast<OMPPrivateClause>(Implicit)->varlist_size() !=
5982                      ImplicitPrivates.size();
5983       } else {
5984         ErrorFound = true;
5985       }
5986     }
5987     // OpenMP 5.0 [2.19.7]
5988     // If a list item appears in a reduction, lastprivate or linear
5989     // clause on a combined target construct then it is treated as
5990     // if it also appears in a map clause with a map-type of tofrom
5991     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5992         isOpenMPTargetExecutionDirective(Kind)) {
5993       SmallVector<Expr *, 4> ImplicitExprs;
5994       for (OMPClause *C : Clauses) {
5995         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5996           for (Expr *E : RC->varlists())
5997             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5998               ImplicitExprs.emplace_back(E);
5999       }
6000       if (!ImplicitExprs.empty()) {
6001         ArrayRef<Expr *> Exprs = ImplicitExprs;
6002         CXXScopeSpec MapperIdScopeSpec;
6003         DeclarationNameInfo MapperId;
6004         if (OMPClause *Implicit = ActOnOpenMPMapClause(
6005                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
6006                 MapperId, OMPC_MAP_tofrom,
6007                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
6008                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
6009           ClausesWithImplicit.emplace_back(Implicit);
6010       }
6011     }
6012     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
6013       int ClauseKindCnt = -1;
6014       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
6015         ++ClauseKindCnt;
6016         if (ImplicitMap.empty())
6017           continue;
6018         CXXScopeSpec MapperIdScopeSpec;
6019         DeclarationNameInfo MapperId;
6020         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
6021         if (OMPClause *Implicit = ActOnOpenMPMapClause(
6022                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
6023                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
6024                 SourceLocation(), SourceLocation(), ImplicitMap,
6025                 OMPVarListLocTy())) {
6026           ClausesWithImplicit.emplace_back(Implicit);
6027           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
6028                         ImplicitMap.size();
6029         } else {
6030           ErrorFound = true;
6031         }
6032       }
6033     }
6034     // Build expressions for implicit maps of data members with 'default'
6035     // mappers.
6036     if (LangOpts.OpenMP >= 50)
6037       processImplicitMapsWithDefaultMappers(*this, DSAStack,
6038                                             ClausesWithImplicit);
6039   }
6040 
6041   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
6042   switch (Kind) {
6043   case OMPD_parallel:
6044     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
6045                                        EndLoc);
6046     AllowedNameModifiers.push_back(OMPD_parallel);
6047     break;
6048   case OMPD_simd:
6049     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
6050                                    VarsWithInheritedDSA);
6051     if (LangOpts.OpenMP >= 50)
6052       AllowedNameModifiers.push_back(OMPD_simd);
6053     break;
6054   case OMPD_tile:
6055     Res =
6056         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6057     break;
6058   case OMPD_unroll:
6059     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
6060                                      EndLoc);
6061     break;
6062   case OMPD_for:
6063     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
6064                                   VarsWithInheritedDSA);
6065     break;
6066   case OMPD_for_simd:
6067     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6068                                       EndLoc, VarsWithInheritedDSA);
6069     if (LangOpts.OpenMP >= 50)
6070       AllowedNameModifiers.push_back(OMPD_simd);
6071     break;
6072   case OMPD_sections:
6073     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
6074                                        EndLoc);
6075     break;
6076   case OMPD_section:
6077     assert(ClausesWithImplicit.empty() &&
6078            "No clauses are allowed for 'omp section' directive");
6079     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
6080     break;
6081   case OMPD_single:
6082     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
6083                                      EndLoc);
6084     break;
6085   case OMPD_master:
6086     assert(ClausesWithImplicit.empty() &&
6087            "No clauses are allowed for 'omp master' directive");
6088     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
6089     break;
6090   case OMPD_masked:
6091     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
6092                                      EndLoc);
6093     break;
6094   case OMPD_critical:
6095     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
6096                                        StartLoc, EndLoc);
6097     break;
6098   case OMPD_parallel_for:
6099     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
6100                                           EndLoc, VarsWithInheritedDSA);
6101     AllowedNameModifiers.push_back(OMPD_parallel);
6102     break;
6103   case OMPD_parallel_for_simd:
6104     Res = ActOnOpenMPParallelForSimdDirective(
6105         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6106     AllowedNameModifiers.push_back(OMPD_parallel);
6107     if (LangOpts.OpenMP >= 50)
6108       AllowedNameModifiers.push_back(OMPD_simd);
6109     break;
6110   case OMPD_parallel_master:
6111     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
6112                                              StartLoc, EndLoc);
6113     AllowedNameModifiers.push_back(OMPD_parallel);
6114     break;
6115   case OMPD_parallel_sections:
6116     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
6117                                                StartLoc, EndLoc);
6118     AllowedNameModifiers.push_back(OMPD_parallel);
6119     break;
6120   case OMPD_task:
6121     Res =
6122         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6123     AllowedNameModifiers.push_back(OMPD_task);
6124     break;
6125   case OMPD_taskyield:
6126     assert(ClausesWithImplicit.empty() &&
6127            "No clauses are allowed for 'omp taskyield' directive");
6128     assert(AStmt == nullptr &&
6129            "No associated statement allowed for 'omp taskyield' directive");
6130     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
6131     break;
6132   case OMPD_barrier:
6133     assert(ClausesWithImplicit.empty() &&
6134            "No clauses are allowed for 'omp barrier' directive");
6135     assert(AStmt == nullptr &&
6136            "No associated statement allowed for 'omp barrier' directive");
6137     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
6138     break;
6139   case OMPD_taskwait:
6140     assert(AStmt == nullptr &&
6141            "No associated statement allowed for 'omp taskwait' directive");
6142     Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
6143     break;
6144   case OMPD_taskgroup:
6145     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
6146                                         EndLoc);
6147     break;
6148   case OMPD_flush:
6149     assert(AStmt == nullptr &&
6150            "No associated statement allowed for 'omp flush' directive");
6151     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
6152     break;
6153   case OMPD_depobj:
6154     assert(AStmt == nullptr &&
6155            "No associated statement allowed for 'omp depobj' directive");
6156     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
6157     break;
6158   case OMPD_scan:
6159     assert(AStmt == nullptr &&
6160            "No associated statement allowed for 'omp scan' directive");
6161     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
6162     break;
6163   case OMPD_ordered:
6164     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
6165                                       EndLoc);
6166     break;
6167   case OMPD_atomic:
6168     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
6169                                      EndLoc);
6170     break;
6171   case OMPD_teams:
6172     Res =
6173         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6174     break;
6175   case OMPD_target:
6176     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6177                                      EndLoc);
6178     AllowedNameModifiers.push_back(OMPD_target);
6179     break;
6180   case OMPD_target_parallel:
6181     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6182                                              StartLoc, EndLoc);
6183     AllowedNameModifiers.push_back(OMPD_target);
6184     AllowedNameModifiers.push_back(OMPD_parallel);
6185     break;
6186   case OMPD_target_parallel_for:
6187     Res = ActOnOpenMPTargetParallelForDirective(
6188         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6189     AllowedNameModifiers.push_back(OMPD_target);
6190     AllowedNameModifiers.push_back(OMPD_parallel);
6191     break;
6192   case OMPD_cancellation_point:
6193     assert(ClausesWithImplicit.empty() &&
6194            "No clauses are allowed for 'omp cancellation point' directive");
6195     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6196                                "cancellation point' directive");
6197     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6198     break;
6199   case OMPD_cancel:
6200     assert(AStmt == nullptr &&
6201            "No associated statement allowed for 'omp cancel' directive");
6202     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6203                                      CancelRegion);
6204     AllowedNameModifiers.push_back(OMPD_cancel);
6205     break;
6206   case OMPD_target_data:
6207     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6208                                          EndLoc);
6209     AllowedNameModifiers.push_back(OMPD_target_data);
6210     break;
6211   case OMPD_target_enter_data:
6212     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6213                                               EndLoc, AStmt);
6214     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6215     break;
6216   case OMPD_target_exit_data:
6217     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6218                                              EndLoc, AStmt);
6219     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6220     break;
6221   case OMPD_taskloop:
6222     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6223                                        EndLoc, VarsWithInheritedDSA);
6224     AllowedNameModifiers.push_back(OMPD_taskloop);
6225     break;
6226   case OMPD_taskloop_simd:
6227     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6228                                            EndLoc, VarsWithInheritedDSA);
6229     AllowedNameModifiers.push_back(OMPD_taskloop);
6230     if (LangOpts.OpenMP >= 50)
6231       AllowedNameModifiers.push_back(OMPD_simd);
6232     break;
6233   case OMPD_master_taskloop:
6234     Res = ActOnOpenMPMasterTaskLoopDirective(
6235         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6236     AllowedNameModifiers.push_back(OMPD_taskloop);
6237     break;
6238   case OMPD_master_taskloop_simd:
6239     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6240         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6241     AllowedNameModifiers.push_back(OMPD_taskloop);
6242     if (LangOpts.OpenMP >= 50)
6243       AllowedNameModifiers.push_back(OMPD_simd);
6244     break;
6245   case OMPD_parallel_master_taskloop:
6246     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6247         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6248     AllowedNameModifiers.push_back(OMPD_taskloop);
6249     AllowedNameModifiers.push_back(OMPD_parallel);
6250     break;
6251   case OMPD_parallel_master_taskloop_simd:
6252     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6253         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6254     AllowedNameModifiers.push_back(OMPD_taskloop);
6255     AllowedNameModifiers.push_back(OMPD_parallel);
6256     if (LangOpts.OpenMP >= 50)
6257       AllowedNameModifiers.push_back(OMPD_simd);
6258     break;
6259   case OMPD_distribute:
6260     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6261                                          EndLoc, VarsWithInheritedDSA);
6262     break;
6263   case OMPD_target_update:
6264     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6265                                            EndLoc, AStmt);
6266     AllowedNameModifiers.push_back(OMPD_target_update);
6267     break;
6268   case OMPD_distribute_parallel_for:
6269     Res = ActOnOpenMPDistributeParallelForDirective(
6270         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6271     AllowedNameModifiers.push_back(OMPD_parallel);
6272     break;
6273   case OMPD_distribute_parallel_for_simd:
6274     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6275         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6276     AllowedNameModifiers.push_back(OMPD_parallel);
6277     if (LangOpts.OpenMP >= 50)
6278       AllowedNameModifiers.push_back(OMPD_simd);
6279     break;
6280   case OMPD_distribute_simd:
6281     Res = ActOnOpenMPDistributeSimdDirective(
6282         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6283     if (LangOpts.OpenMP >= 50)
6284       AllowedNameModifiers.push_back(OMPD_simd);
6285     break;
6286   case OMPD_target_parallel_for_simd:
6287     Res = ActOnOpenMPTargetParallelForSimdDirective(
6288         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6289     AllowedNameModifiers.push_back(OMPD_target);
6290     AllowedNameModifiers.push_back(OMPD_parallel);
6291     if (LangOpts.OpenMP >= 50)
6292       AllowedNameModifiers.push_back(OMPD_simd);
6293     break;
6294   case OMPD_target_simd:
6295     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6296                                          EndLoc, VarsWithInheritedDSA);
6297     AllowedNameModifiers.push_back(OMPD_target);
6298     if (LangOpts.OpenMP >= 50)
6299       AllowedNameModifiers.push_back(OMPD_simd);
6300     break;
6301   case OMPD_teams_distribute:
6302     Res = ActOnOpenMPTeamsDistributeDirective(
6303         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6304     break;
6305   case OMPD_teams_distribute_simd:
6306     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6307         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6308     if (LangOpts.OpenMP >= 50)
6309       AllowedNameModifiers.push_back(OMPD_simd);
6310     break;
6311   case OMPD_teams_distribute_parallel_for_simd:
6312     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6313         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6314     AllowedNameModifiers.push_back(OMPD_parallel);
6315     if (LangOpts.OpenMP >= 50)
6316       AllowedNameModifiers.push_back(OMPD_simd);
6317     break;
6318   case OMPD_teams_distribute_parallel_for:
6319     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6320         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6321     AllowedNameModifiers.push_back(OMPD_parallel);
6322     break;
6323   case OMPD_target_teams:
6324     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6325                                           EndLoc);
6326     AllowedNameModifiers.push_back(OMPD_target);
6327     break;
6328   case OMPD_target_teams_distribute:
6329     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6330         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6331     AllowedNameModifiers.push_back(OMPD_target);
6332     break;
6333   case OMPD_target_teams_distribute_parallel_for:
6334     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6335         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6336     AllowedNameModifiers.push_back(OMPD_target);
6337     AllowedNameModifiers.push_back(OMPD_parallel);
6338     break;
6339   case OMPD_target_teams_distribute_parallel_for_simd:
6340     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6341         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6342     AllowedNameModifiers.push_back(OMPD_target);
6343     AllowedNameModifiers.push_back(OMPD_parallel);
6344     if (LangOpts.OpenMP >= 50)
6345       AllowedNameModifiers.push_back(OMPD_simd);
6346     break;
6347   case OMPD_target_teams_distribute_simd:
6348     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6349         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6350     AllowedNameModifiers.push_back(OMPD_target);
6351     if (LangOpts.OpenMP >= 50)
6352       AllowedNameModifiers.push_back(OMPD_simd);
6353     break;
6354   case OMPD_interop:
6355     assert(AStmt == nullptr &&
6356            "No associated statement allowed for 'omp interop' directive");
6357     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6358     break;
6359   case OMPD_dispatch:
6360     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6361                                        EndLoc);
6362     break;
6363   case OMPD_loop:
6364     Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6365                                           EndLoc, VarsWithInheritedDSA);
6366     break;
6367   case OMPD_teams_loop:
6368     Res = ActOnOpenMPTeamsGenericLoopDirective(
6369         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6370     break;
6371   case OMPD_target_teams_loop:
6372     Res = ActOnOpenMPTargetTeamsGenericLoopDirective(
6373         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6374     break;
6375   case OMPD_parallel_loop:
6376     Res = ActOnOpenMPParallelGenericLoopDirective(
6377         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6378     break;
6379   case OMPD_target_parallel_loop:
6380     Res = ActOnOpenMPTargetParallelGenericLoopDirective(
6381         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6382     break;
6383   case OMPD_declare_target:
6384   case OMPD_end_declare_target:
6385   case OMPD_threadprivate:
6386   case OMPD_allocate:
6387   case OMPD_declare_reduction:
6388   case OMPD_declare_mapper:
6389   case OMPD_declare_simd:
6390   case OMPD_requires:
6391   case OMPD_declare_variant:
6392   case OMPD_begin_declare_variant:
6393   case OMPD_end_declare_variant:
6394     llvm_unreachable("OpenMP Directive is not allowed");
6395   case OMPD_unknown:
6396   default:
6397     llvm_unreachable("Unknown OpenMP directive");
6398   }
6399 
6400   ErrorFound = Res.isInvalid() || ErrorFound;
6401 
6402   // Check variables in the clauses if default(none) or
6403   // default(firstprivate) was specified.
6404   if (DSAStack->getDefaultDSA() == DSA_none ||
6405       DSAStack->getDefaultDSA() == DSA_private ||
6406       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6407     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6408     for (OMPClause *C : Clauses) {
6409       switch (C->getClauseKind()) {
6410       case OMPC_num_threads:
6411       case OMPC_dist_schedule:
6412         // Do not analyse if no parent teams directive.
6413         if (isOpenMPTeamsDirective(Kind))
6414           break;
6415         continue;
6416       case OMPC_if:
6417         if (isOpenMPTeamsDirective(Kind) &&
6418             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6419           break;
6420         if (isOpenMPParallelDirective(Kind) &&
6421             isOpenMPTaskLoopDirective(Kind) &&
6422             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6423           break;
6424         continue;
6425       case OMPC_schedule:
6426       case OMPC_detach:
6427         break;
6428       case OMPC_grainsize:
6429       case OMPC_num_tasks:
6430       case OMPC_final:
6431       case OMPC_priority:
6432       case OMPC_novariants:
6433       case OMPC_nocontext:
6434         // Do not analyze if no parent parallel directive.
6435         if (isOpenMPParallelDirective(Kind))
6436           break;
6437         continue;
6438       case OMPC_ordered:
6439       case OMPC_device:
6440       case OMPC_num_teams:
6441       case OMPC_thread_limit:
6442       case OMPC_hint:
6443       case OMPC_collapse:
6444       case OMPC_safelen:
6445       case OMPC_simdlen:
6446       case OMPC_sizes:
6447       case OMPC_default:
6448       case OMPC_proc_bind:
6449       case OMPC_private:
6450       case OMPC_firstprivate:
6451       case OMPC_lastprivate:
6452       case OMPC_shared:
6453       case OMPC_reduction:
6454       case OMPC_task_reduction:
6455       case OMPC_in_reduction:
6456       case OMPC_linear:
6457       case OMPC_aligned:
6458       case OMPC_copyin:
6459       case OMPC_copyprivate:
6460       case OMPC_nowait:
6461       case OMPC_untied:
6462       case OMPC_mergeable:
6463       case OMPC_allocate:
6464       case OMPC_read:
6465       case OMPC_write:
6466       case OMPC_update:
6467       case OMPC_capture:
6468       case OMPC_compare:
6469       case OMPC_seq_cst:
6470       case OMPC_acq_rel:
6471       case OMPC_acquire:
6472       case OMPC_release:
6473       case OMPC_relaxed:
6474       case OMPC_depend:
6475       case OMPC_threads:
6476       case OMPC_simd:
6477       case OMPC_map:
6478       case OMPC_nogroup:
6479       case OMPC_defaultmap:
6480       case OMPC_to:
6481       case OMPC_from:
6482       case OMPC_use_device_ptr:
6483       case OMPC_use_device_addr:
6484       case OMPC_is_device_ptr:
6485       case OMPC_has_device_addr:
6486       case OMPC_nontemporal:
6487       case OMPC_order:
6488       case OMPC_destroy:
6489       case OMPC_inclusive:
6490       case OMPC_exclusive:
6491       case OMPC_uses_allocators:
6492       case OMPC_affinity:
6493       case OMPC_bind:
6494         continue;
6495       case OMPC_allocator:
6496       case OMPC_flush:
6497       case OMPC_depobj:
6498       case OMPC_threadprivate:
6499       case OMPC_uniform:
6500       case OMPC_unknown:
6501       case OMPC_unified_address:
6502       case OMPC_unified_shared_memory:
6503       case OMPC_reverse_offload:
6504       case OMPC_dynamic_allocators:
6505       case OMPC_atomic_default_mem_order:
6506       case OMPC_device_type:
6507       case OMPC_match:
6508       case OMPC_when:
6509       default:
6510         llvm_unreachable("Unexpected clause");
6511       }
6512       for (Stmt *CC : C->children()) {
6513         if (CC)
6514           DSAChecker.Visit(CC);
6515       }
6516     }
6517     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6518       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6519   }
6520   for (const auto &P : VarsWithInheritedDSA) {
6521     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6522       continue;
6523     ErrorFound = true;
6524     if (DSAStack->getDefaultDSA() == DSA_none ||
6525         DSAStack->getDefaultDSA() == DSA_private ||
6526         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6527       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6528           << P.first << P.second->getSourceRange();
6529       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6530     } else if (getLangOpts().OpenMP >= 50) {
6531       Diag(P.second->getExprLoc(),
6532            diag::err_omp_defaultmap_no_attr_for_variable)
6533           << P.first << P.second->getSourceRange();
6534       Diag(DSAStack->getDefaultDSALocation(),
6535            diag::note_omp_defaultmap_attr_none);
6536     }
6537   }
6538 
6539   if (!AllowedNameModifiers.empty())
6540     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6541                  ErrorFound;
6542 
6543   if (ErrorFound)
6544     return StmtError();
6545 
6546   if (!CurContext->isDependentContext() &&
6547       isOpenMPTargetExecutionDirective(Kind) &&
6548       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6549         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6550         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6551         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6552     // Register target to DSA Stack.
6553     DSAStack->addTargetDirLocation(StartLoc);
6554   }
6555 
6556   return Res;
6557 }
6558 
6559 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6560     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6561     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6562     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6563     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6564   assert(Aligneds.size() == Alignments.size());
6565   assert(Linears.size() == LinModifiers.size());
6566   assert(Linears.size() == Steps.size());
6567   if (!DG || DG.get().isNull())
6568     return DeclGroupPtrTy();
6569 
6570   const int SimdId = 0;
6571   if (!DG.get().isSingleDecl()) {
6572     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6573         << SimdId;
6574     return DG;
6575   }
6576   Decl *ADecl = DG.get().getSingleDecl();
6577   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6578     ADecl = FTD->getTemplatedDecl();
6579 
6580   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6581   if (!FD) {
6582     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6583     return DeclGroupPtrTy();
6584   }
6585 
6586   // OpenMP [2.8.2, declare simd construct, Description]
6587   // The parameter of the simdlen clause must be a constant positive integer
6588   // expression.
6589   ExprResult SL;
6590   if (Simdlen)
6591     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6592   // OpenMP [2.8.2, declare simd construct, Description]
6593   // The special this pointer can be used as if was one of the arguments to the
6594   // function in any of the linear, aligned, or uniform clauses.
6595   // The uniform clause declares one or more arguments to have an invariant
6596   // value for all concurrent invocations of the function in the execution of a
6597   // single SIMD loop.
6598   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6599   const Expr *UniformedLinearThis = nullptr;
6600   for (const Expr *E : Uniforms) {
6601     E = E->IgnoreParenImpCasts();
6602     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6603       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6604         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6605             FD->getParamDecl(PVD->getFunctionScopeIndex())
6606                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6607           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6608           continue;
6609         }
6610     if (isa<CXXThisExpr>(E)) {
6611       UniformedLinearThis = E;
6612       continue;
6613     }
6614     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6615         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6616   }
6617   // OpenMP [2.8.2, declare simd construct, Description]
6618   // The aligned clause declares that the object to which each list item points
6619   // is aligned to the number of bytes expressed in the optional parameter of
6620   // the aligned clause.
6621   // The special this pointer can be used as if was one of the arguments to the
6622   // function in any of the linear, aligned, or uniform clauses.
6623   // The type of list items appearing in the aligned clause must be array,
6624   // pointer, reference to array, or reference to pointer.
6625   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6626   const Expr *AlignedThis = nullptr;
6627   for (const Expr *E : Aligneds) {
6628     E = E->IgnoreParenImpCasts();
6629     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6630       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6631         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6632         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6633             FD->getParamDecl(PVD->getFunctionScopeIndex())
6634                     ->getCanonicalDecl() == CanonPVD) {
6635           // OpenMP  [2.8.1, simd construct, Restrictions]
6636           // A list-item cannot appear in more than one aligned clause.
6637           if (AlignedArgs.count(CanonPVD) > 0) {
6638             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6639                 << 1 << getOpenMPClauseName(OMPC_aligned)
6640                 << E->getSourceRange();
6641             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6642                  diag::note_omp_explicit_dsa)
6643                 << getOpenMPClauseName(OMPC_aligned);
6644             continue;
6645           }
6646           AlignedArgs[CanonPVD] = E;
6647           QualType QTy = PVD->getType()
6648                              .getNonReferenceType()
6649                              .getUnqualifiedType()
6650                              .getCanonicalType();
6651           const Type *Ty = QTy.getTypePtrOrNull();
6652           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6653             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6654                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6655             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6656           }
6657           continue;
6658         }
6659       }
6660     if (isa<CXXThisExpr>(E)) {
6661       if (AlignedThis) {
6662         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6663             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6664         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6665             << getOpenMPClauseName(OMPC_aligned);
6666       }
6667       AlignedThis = E;
6668       continue;
6669     }
6670     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6671         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6672   }
6673   // The optional parameter of the aligned clause, alignment, must be a constant
6674   // positive integer expression. If no optional parameter is specified,
6675   // implementation-defined default alignments for SIMD instructions on the
6676   // target platforms are assumed.
6677   SmallVector<const Expr *, 4> NewAligns;
6678   for (Expr *E : Alignments) {
6679     ExprResult Align;
6680     if (E)
6681       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6682     NewAligns.push_back(Align.get());
6683   }
6684   // OpenMP [2.8.2, declare simd construct, Description]
6685   // The linear clause declares one or more list items to be private to a SIMD
6686   // lane and to have a linear relationship with respect to the iteration space
6687   // of a loop.
6688   // The special this pointer can be used as if was one of the arguments to the
6689   // function in any of the linear, aligned, or uniform clauses.
6690   // When a linear-step expression is specified in a linear clause it must be
6691   // either a constant integer expression or an integer-typed parameter that is
6692   // specified in a uniform clause on the directive.
6693   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6694   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6695   auto MI = LinModifiers.begin();
6696   for (const Expr *E : Linears) {
6697     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6698     ++MI;
6699     E = E->IgnoreParenImpCasts();
6700     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6701       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6702         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6703         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6704             FD->getParamDecl(PVD->getFunctionScopeIndex())
6705                     ->getCanonicalDecl() == CanonPVD) {
6706           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6707           // A list-item cannot appear in more than one linear clause.
6708           if (LinearArgs.count(CanonPVD) > 0) {
6709             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6710                 << getOpenMPClauseName(OMPC_linear)
6711                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6712             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6713                  diag::note_omp_explicit_dsa)
6714                 << getOpenMPClauseName(OMPC_linear);
6715             continue;
6716           }
6717           // Each argument can appear in at most one uniform or linear clause.
6718           if (UniformedArgs.count(CanonPVD) > 0) {
6719             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6720                 << getOpenMPClauseName(OMPC_linear)
6721                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6722             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6723                  diag::note_omp_explicit_dsa)
6724                 << getOpenMPClauseName(OMPC_uniform);
6725             continue;
6726           }
6727           LinearArgs[CanonPVD] = E;
6728           if (E->isValueDependent() || E->isTypeDependent() ||
6729               E->isInstantiationDependent() ||
6730               E->containsUnexpandedParameterPack())
6731             continue;
6732           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6733                                       PVD->getOriginalType(),
6734                                       /*IsDeclareSimd=*/true);
6735           continue;
6736         }
6737       }
6738     if (isa<CXXThisExpr>(E)) {
6739       if (UniformedLinearThis) {
6740         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6741             << getOpenMPClauseName(OMPC_linear)
6742             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6743             << E->getSourceRange();
6744         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6745             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6746                                                    : OMPC_linear);
6747         continue;
6748       }
6749       UniformedLinearThis = E;
6750       if (E->isValueDependent() || E->isTypeDependent() ||
6751           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6752         continue;
6753       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6754                                   E->getType(), /*IsDeclareSimd=*/true);
6755       continue;
6756     }
6757     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6758         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6759   }
6760   Expr *Step = nullptr;
6761   Expr *NewStep = nullptr;
6762   SmallVector<Expr *, 4> NewSteps;
6763   for (Expr *E : Steps) {
6764     // Skip the same step expression, it was checked already.
6765     if (Step == E || !E) {
6766       NewSteps.push_back(E ? NewStep : nullptr);
6767       continue;
6768     }
6769     Step = E;
6770     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6771       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6772         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6773         if (UniformedArgs.count(CanonPVD) == 0) {
6774           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6775               << Step->getSourceRange();
6776         } else if (E->isValueDependent() || E->isTypeDependent() ||
6777                    E->isInstantiationDependent() ||
6778                    E->containsUnexpandedParameterPack() ||
6779                    CanonPVD->getType()->hasIntegerRepresentation()) {
6780           NewSteps.push_back(Step);
6781         } else {
6782           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6783               << Step->getSourceRange();
6784         }
6785         continue;
6786       }
6787     NewStep = Step;
6788     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6789         !Step->isInstantiationDependent() &&
6790         !Step->containsUnexpandedParameterPack()) {
6791       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6792                     .get();
6793       if (NewStep)
6794         NewStep =
6795             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6796     }
6797     NewSteps.push_back(NewStep);
6798   }
6799   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6800       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6801       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6802       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6803       const_cast<Expr **>(Linears.data()), Linears.size(),
6804       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6805       NewSteps.data(), NewSteps.size(), SR);
6806   ADecl->addAttr(NewAttr);
6807   return DG;
6808 }
6809 
6810 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6811                          QualType NewType) {
6812   assert(NewType->isFunctionProtoType() &&
6813          "Expected function type with prototype.");
6814   assert(FD->getType()->isFunctionNoProtoType() &&
6815          "Expected function with type with no prototype.");
6816   assert(FDWithProto->getType()->isFunctionProtoType() &&
6817          "Expected function with prototype.");
6818   // Synthesize parameters with the same types.
6819   FD->setType(NewType);
6820   SmallVector<ParmVarDecl *, 16> Params;
6821   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6822     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6823                                       SourceLocation(), nullptr, P->getType(),
6824                                       /*TInfo=*/nullptr, SC_None, nullptr);
6825     Param->setScopeInfo(0, Params.size());
6826     Param->setImplicit();
6827     Params.push_back(Param);
6828   }
6829 
6830   FD->setParams(Params);
6831 }
6832 
6833 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6834   if (D->isInvalidDecl())
6835     return;
6836   FunctionDecl *FD = nullptr;
6837   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6838     FD = UTemplDecl->getTemplatedDecl();
6839   else
6840     FD = cast<FunctionDecl>(D);
6841   assert(FD && "Expected a function declaration!");
6842 
6843   // If we are instantiating templates we do *not* apply scoped assumptions but
6844   // only global ones. We apply scoped assumption to the template definition
6845   // though.
6846   if (!inTemplateInstantiation()) {
6847     for (AssumptionAttr *AA : OMPAssumeScoped)
6848       FD->addAttr(AA);
6849   }
6850   for (AssumptionAttr *AA : OMPAssumeGlobal)
6851     FD->addAttr(AA);
6852 }
6853 
6854 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6855     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6856 
6857 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6858     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6859     SmallVectorImpl<FunctionDecl *> &Bases) {
6860   if (!D.getIdentifier())
6861     return;
6862 
6863   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6864 
6865   // Template specialization is an extension, check if we do it.
6866   bool IsTemplated = !TemplateParamLists.empty();
6867   if (IsTemplated &
6868       !DVScope.TI->isExtensionActive(
6869           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6870     return;
6871 
6872   IdentifierInfo *BaseII = D.getIdentifier();
6873   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6874                       LookupOrdinaryName);
6875   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6876 
6877   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6878   QualType FType = TInfo->getType();
6879 
6880   bool IsConstexpr =
6881       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6882   bool IsConsteval =
6883       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6884 
6885   for (auto *Candidate : Lookup) {
6886     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6887     FunctionDecl *UDecl = nullptr;
6888     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
6889       auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
6890       if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
6891         UDecl = FTD->getTemplatedDecl();
6892     } else if (!IsTemplated)
6893       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6894     if (!UDecl)
6895       continue;
6896 
6897     // Don't specialize constexpr/consteval functions with
6898     // non-constexpr/consteval functions.
6899     if (UDecl->isConstexpr() && !IsConstexpr)
6900       continue;
6901     if (UDecl->isConsteval() && !IsConsteval)
6902       continue;
6903 
6904     QualType UDeclTy = UDecl->getType();
6905     if (!UDeclTy->isDependentType()) {
6906       QualType NewType = Context.mergeFunctionTypes(
6907           FType, UDeclTy, /* OfBlockPointer */ false,
6908           /* Unqualified */ false, /* AllowCXX */ true);
6909       if (NewType.isNull())
6910         continue;
6911     }
6912 
6913     // Found a base!
6914     Bases.push_back(UDecl);
6915   }
6916 
6917   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6918       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6919   // If no base was found we create a declaration that we use as base.
6920   if (Bases.empty() && UseImplicitBase) {
6921     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6922     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6923     BaseD->setImplicit(true);
6924     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6925       Bases.push_back(BaseTemplD->getTemplatedDecl());
6926     else
6927       Bases.push_back(cast<FunctionDecl>(BaseD));
6928   }
6929 
6930   std::string MangledName;
6931   MangledName += D.getIdentifier()->getName();
6932   MangledName += getOpenMPVariantManglingSeparatorStr();
6933   MangledName += DVScope.NameSuffix;
6934   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6935 
6936   VariantII.setMangledOpenMPVariantName(true);
6937   D.SetIdentifier(&VariantII, D.getBeginLoc());
6938 }
6939 
6940 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6941     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6942   // Do not mark function as is used to prevent its emission if this is the
6943   // only place where it is used.
6944   EnterExpressionEvaluationContext Unevaluated(
6945       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6946 
6947   FunctionDecl *FD = nullptr;
6948   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6949     FD = UTemplDecl->getTemplatedDecl();
6950   else
6951     FD = cast<FunctionDecl>(D);
6952   auto *VariantFuncRef = DeclRefExpr::Create(
6953       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6954       /* RefersToEnclosingVariableOrCapture */ false,
6955       /* NameLoc */ FD->getLocation(), FD->getType(),
6956       ExprValueKind::VK_PRValue);
6957 
6958   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6959   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6960       Context, VariantFuncRef, DVScope.TI,
6961       /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
6962       /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
6963       /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
6964   for (FunctionDecl *BaseFD : Bases)
6965     BaseFD->addAttr(OMPDeclareVariantA);
6966 }
6967 
6968 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6969                                  SourceLocation LParenLoc,
6970                                  MultiExprArg ArgExprs,
6971                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6972   // The common case is a regular call we do not want to specialize at all. Try
6973   // to make that case fast by bailing early.
6974   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6975   if (!CE)
6976     return Call;
6977 
6978   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6979   if (!CalleeFnDecl)
6980     return Call;
6981 
6982   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6983     return Call;
6984 
6985   ASTContext &Context = getASTContext();
6986   std::function<void(StringRef)> DiagUnknownTrait = [this,
6987                                                      CE](StringRef ISATrait) {
6988     // TODO Track the selector locations in a way that is accessible here to
6989     // improve the diagnostic location.
6990     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6991         << ISATrait;
6992   };
6993   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6994                           getCurFunctionDecl(), DSAStack->getConstructTraits());
6995 
6996   QualType CalleeFnType = CalleeFnDecl->getType();
6997 
6998   SmallVector<Expr *, 4> Exprs;
6999   SmallVector<VariantMatchInfo, 4> VMIs;
7000   while (CalleeFnDecl) {
7001     for (OMPDeclareVariantAttr *A :
7002          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
7003       Expr *VariantRef = A->getVariantFuncRef();
7004 
7005       VariantMatchInfo VMI;
7006       OMPTraitInfo &TI = A->getTraitInfo();
7007       TI.getAsVariantMatchInfo(Context, VMI);
7008       if (!isVariantApplicableInContext(VMI, OMPCtx,
7009                                         /* DeviceSetOnly */ false))
7010         continue;
7011 
7012       VMIs.push_back(VMI);
7013       Exprs.push_back(VariantRef);
7014     }
7015 
7016     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
7017   }
7018 
7019   ExprResult NewCall;
7020   do {
7021     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
7022     if (BestIdx < 0)
7023       return Call;
7024     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
7025     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
7026 
7027     {
7028       // Try to build a (member) call expression for the current best applicable
7029       // variant expression. We allow this to fail in which case we continue
7030       // with the next best variant expression. The fail case is part of the
7031       // implementation defined behavior in the OpenMP standard when it talks
7032       // about what differences in the function prototypes: "Any differences
7033       // that the specific OpenMP context requires in the prototype of the
7034       // variant from the base function prototype are implementation defined."
7035       // This wording is there to allow the specialized variant to have a
7036       // different type than the base function. This is intended and OK but if
7037       // we cannot create a call the difference is not in the "implementation
7038       // defined range" we allow.
7039       Sema::TentativeAnalysisScope Trap(*this);
7040 
7041       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
7042         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
7043         BestExpr = MemberExpr::CreateImplicit(
7044             Context, MemberCall->getImplicitObjectArgument(),
7045             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
7046             MemberCall->getValueKind(), MemberCall->getObjectKind());
7047       }
7048       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
7049                               ExecConfig);
7050       if (NewCall.isUsable()) {
7051         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
7052           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
7053           QualType NewType = Context.mergeFunctionTypes(
7054               CalleeFnType, NewCalleeFnDecl->getType(),
7055               /* OfBlockPointer */ false,
7056               /* Unqualified */ false, /* AllowCXX */ true);
7057           if (!NewType.isNull())
7058             break;
7059           // Don't use the call if the function type was not compatible.
7060           NewCall = nullptr;
7061         }
7062       }
7063     }
7064 
7065     VMIs.erase(VMIs.begin() + BestIdx);
7066     Exprs.erase(Exprs.begin() + BestIdx);
7067   } while (!VMIs.empty());
7068 
7069   if (!NewCall.isUsable())
7070     return Call;
7071   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
7072 }
7073 
7074 Optional<std::pair<FunctionDecl *, Expr *>>
7075 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
7076                                         Expr *VariantRef, OMPTraitInfo &TI,
7077                                         unsigned NumAppendArgs,
7078                                         SourceRange SR) {
7079   if (!DG || DG.get().isNull())
7080     return None;
7081 
7082   const int VariantId = 1;
7083   // Must be applied only to single decl.
7084   if (!DG.get().isSingleDecl()) {
7085     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
7086         << VariantId << SR;
7087     return None;
7088   }
7089   Decl *ADecl = DG.get().getSingleDecl();
7090   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
7091     ADecl = FTD->getTemplatedDecl();
7092 
7093   // Decl must be a function.
7094   auto *FD = dyn_cast<FunctionDecl>(ADecl);
7095   if (!FD) {
7096     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
7097         << VariantId << SR;
7098     return None;
7099   }
7100 
7101   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
7102     // The 'target' attribute needs to be separately checked because it does
7103     // not always signify a multiversion function declaration.
7104     return FD->isMultiVersion() || FD->hasAttr<TargetAttr>();
7105   };
7106   // OpenMP is not compatible with multiversion function attributes.
7107   if (HasMultiVersionAttributes(FD)) {
7108     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
7109         << SR;
7110     return None;
7111   }
7112 
7113   // Allow #pragma omp declare variant only if the function is not used.
7114   if (FD->isUsed(false))
7115     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
7116         << FD->getLocation();
7117 
7118   // Check if the function was emitted already.
7119   const FunctionDecl *Definition;
7120   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
7121       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
7122     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
7123         << FD->getLocation();
7124 
7125   // The VariantRef must point to function.
7126   if (!VariantRef) {
7127     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
7128     return None;
7129   }
7130 
7131   auto ShouldDelayChecks = [](Expr *&E, bool) {
7132     return E && (E->isTypeDependent() || E->isValueDependent() ||
7133                  E->containsUnexpandedParameterPack() ||
7134                  E->isInstantiationDependent());
7135   };
7136   // Do not check templates, wait until instantiation.
7137   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
7138       TI.anyScoreOrCondition(ShouldDelayChecks))
7139     return std::make_pair(FD, VariantRef);
7140 
7141   // Deal with non-constant score and user condition expressions.
7142   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
7143                                                      bool IsScore) -> bool {
7144     if (!E || E->isIntegerConstantExpr(Context))
7145       return false;
7146 
7147     if (IsScore) {
7148       // We warn on non-constant scores and pretend they were not present.
7149       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
7150           << E;
7151       E = nullptr;
7152     } else {
7153       // We could replace a non-constant user condition with "false" but we
7154       // will soon need to handle these anyway for the dynamic version of
7155       // OpenMP context selectors.
7156       Diag(E->getExprLoc(),
7157            diag::err_omp_declare_variant_user_condition_not_constant)
7158           << E;
7159     }
7160     return true;
7161   };
7162   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
7163     return None;
7164 
7165   QualType AdjustedFnType = FD->getType();
7166   if (NumAppendArgs) {
7167     const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
7168     if (!PTy) {
7169       Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
7170           << SR;
7171       return None;
7172     }
7173     // Adjust the function type to account for an extra omp_interop_t for each
7174     // specified in the append_args clause.
7175     const TypeDecl *TD = nullptr;
7176     LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
7177                         SR.getBegin(), Sema::LookupOrdinaryName);
7178     if (LookupName(Result, getCurScope())) {
7179       NamedDecl *ND = Result.getFoundDecl();
7180       TD = dyn_cast_or_null<TypeDecl>(ND);
7181     }
7182     if (!TD) {
7183       Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
7184       return None;
7185     }
7186     QualType InteropType = Context.getTypeDeclType(TD);
7187     if (PTy->isVariadic()) {
7188       Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
7189       return None;
7190     }
7191     llvm::SmallVector<QualType, 8> Params;
7192     Params.append(PTy->param_type_begin(), PTy->param_type_end());
7193     Params.insert(Params.end(), NumAppendArgs, InteropType);
7194     AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
7195                                              PTy->getExtProtoInfo());
7196   }
7197 
7198   // Convert VariantRef expression to the type of the original function to
7199   // resolve possible conflicts.
7200   ExprResult VariantRefCast = VariantRef;
7201   if (LangOpts.CPlusPlus) {
7202     QualType FnPtrType;
7203     auto *Method = dyn_cast<CXXMethodDecl>(FD);
7204     if (Method && !Method->isStatic()) {
7205       const Type *ClassType =
7206           Context.getTypeDeclType(Method->getParent()).getTypePtr();
7207       FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
7208       ExprResult ER;
7209       {
7210         // Build adrr_of unary op to correctly handle type checks for member
7211         // functions.
7212         Sema::TentativeAnalysisScope Trap(*this);
7213         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
7214                                   VariantRef);
7215       }
7216       if (!ER.isUsable()) {
7217         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7218             << VariantId << VariantRef->getSourceRange();
7219         return None;
7220       }
7221       VariantRef = ER.get();
7222     } else {
7223       FnPtrType = Context.getPointerType(AdjustedFnType);
7224     }
7225     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
7226     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
7227       ImplicitConversionSequence ICS = TryImplicitConversion(
7228           VariantRef, FnPtrType.getUnqualifiedType(),
7229           /*SuppressUserConversions=*/false, AllowedExplicit::None,
7230           /*InOverloadResolution=*/false,
7231           /*CStyle=*/false,
7232           /*AllowObjCWritebackConversion=*/false);
7233       if (ICS.isFailure()) {
7234         Diag(VariantRef->getExprLoc(),
7235              diag::err_omp_declare_variant_incompat_types)
7236             << VariantRef->getType()
7237             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7238             << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
7239         return None;
7240       }
7241       VariantRefCast = PerformImplicitConversion(
7242           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7243       if (!VariantRefCast.isUsable())
7244         return None;
7245     }
7246     // Drop previously built artificial addr_of unary op for member functions.
7247     if (Method && !Method->isStatic()) {
7248       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7249       if (auto *UO = dyn_cast<UnaryOperator>(
7250               PossibleAddrOfVariantRef->IgnoreImplicit()))
7251         VariantRefCast = UO->getSubExpr();
7252     }
7253   }
7254 
7255   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7256   if (!ER.isUsable() ||
7257       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7258     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7259         << VariantId << VariantRef->getSourceRange();
7260     return None;
7261   }
7262 
7263   // The VariantRef must point to function.
7264   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7265   if (!DRE) {
7266     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7267         << VariantId << VariantRef->getSourceRange();
7268     return None;
7269   }
7270   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7271   if (!NewFD) {
7272     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7273         << VariantId << VariantRef->getSourceRange();
7274     return None;
7275   }
7276 
7277   if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) {
7278     Diag(VariantRef->getExprLoc(),
7279          diag::err_omp_declare_variant_same_base_function)
7280         << VariantRef->getSourceRange();
7281     return None;
7282   }
7283 
7284   // Check if function types are compatible in C.
7285   if (!LangOpts.CPlusPlus) {
7286     QualType NewType =
7287         Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
7288     if (NewType.isNull()) {
7289       Diag(VariantRef->getExprLoc(),
7290            diag::err_omp_declare_variant_incompat_types)
7291           << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
7292           << VariantRef->getSourceRange();
7293       return None;
7294     }
7295     if (NewType->isFunctionProtoType()) {
7296       if (FD->getType()->isFunctionNoProtoType())
7297         setPrototype(*this, FD, NewFD, NewType);
7298       else if (NewFD->getType()->isFunctionNoProtoType())
7299         setPrototype(*this, NewFD, FD, NewType);
7300     }
7301   }
7302 
7303   // Check if variant function is not marked with declare variant directive.
7304   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7305     Diag(VariantRef->getExprLoc(),
7306          diag::warn_omp_declare_variant_marked_as_declare_variant)
7307         << VariantRef->getSourceRange();
7308     SourceRange SR =
7309         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7310     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7311     return None;
7312   }
7313 
7314   enum DoesntSupport {
7315     VirtFuncs = 1,
7316     Constructors = 3,
7317     Destructors = 4,
7318     DeletedFuncs = 5,
7319     DefaultedFuncs = 6,
7320     ConstexprFuncs = 7,
7321     ConstevalFuncs = 8,
7322   };
7323   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7324     if (CXXFD->isVirtual()) {
7325       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7326           << VirtFuncs;
7327       return None;
7328     }
7329 
7330     if (isa<CXXConstructorDecl>(FD)) {
7331       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7332           << Constructors;
7333       return None;
7334     }
7335 
7336     if (isa<CXXDestructorDecl>(FD)) {
7337       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7338           << Destructors;
7339       return None;
7340     }
7341   }
7342 
7343   if (FD->isDeleted()) {
7344     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7345         << DeletedFuncs;
7346     return None;
7347   }
7348 
7349   if (FD->isDefaulted()) {
7350     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7351         << DefaultedFuncs;
7352     return None;
7353   }
7354 
7355   if (FD->isConstexpr()) {
7356     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7357         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7358     return None;
7359   }
7360 
7361   // Check general compatibility.
7362   if (areMultiversionVariantFunctionsCompatible(
7363           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7364           PartialDiagnosticAt(SourceLocation(),
7365                               PartialDiagnostic::NullDiagnostic()),
7366           PartialDiagnosticAt(
7367               VariantRef->getExprLoc(),
7368               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7369           PartialDiagnosticAt(VariantRef->getExprLoc(),
7370                               PDiag(diag::err_omp_declare_variant_diff)
7371                                   << FD->getLocation()),
7372           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7373           /*CLinkageMayDiffer=*/true))
7374     return None;
7375   return std::make_pair(FD, cast<Expr>(DRE));
7376 }
7377 
7378 void Sema::ActOnOpenMPDeclareVariantDirective(
7379     FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
7380     ArrayRef<Expr *> AdjustArgsNothing,
7381     ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
7382     ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
7383     SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
7384     SourceRange SR) {
7385 
7386   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7387   // An adjust_args clause or append_args clause can only be specified if the
7388   // dispatch selector of the construct selector set appears in the match
7389   // clause.
7390 
7391   SmallVector<Expr *, 8> AllAdjustArgs;
7392   llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
7393   llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
7394 
7395   if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
7396     VariantMatchInfo VMI;
7397     TI.getAsVariantMatchInfo(Context, VMI);
7398     if (!llvm::is_contained(
7399             VMI.ConstructTraits,
7400             llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
7401       if (!AllAdjustArgs.empty())
7402         Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7403             << getOpenMPClauseName(OMPC_adjust_args);
7404       if (!AppendArgs.empty())
7405         Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7406             << getOpenMPClauseName(OMPC_append_args);
7407       return;
7408     }
7409   }
7410 
7411   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7412   // Each argument can only appear in a single adjust_args clause for each
7413   // declare variant directive.
7414   llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
7415 
7416   for (Expr *E : AllAdjustArgs) {
7417     E = E->IgnoreParenImpCasts();
7418     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
7419       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7420         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7421         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7422             FD->getParamDecl(PVD->getFunctionScopeIndex())
7423                     ->getCanonicalDecl() == CanonPVD) {
7424           // It's a parameter of the function, check duplicates.
7425           if (!AdjustVars.insert(CanonPVD).second) {
7426             Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
7427                 << PVD;
7428             return;
7429           }
7430           continue;
7431         }
7432       }
7433     }
7434     // Anything that is not a function parameter is an error.
7435     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
7436     return;
7437   }
7438 
7439   auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
7440       Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
7441       AdjustArgsNothing.size(),
7442       const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
7443       AdjustArgsNeedDevicePtr.size(),
7444       const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
7445       AppendArgs.size(), SR);
7446   FD->addAttr(NewAttr);
7447 }
7448 
7449 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7450                                               Stmt *AStmt,
7451                                               SourceLocation StartLoc,
7452                                               SourceLocation EndLoc) {
7453   if (!AStmt)
7454     return StmtError();
7455 
7456   auto *CS = cast<CapturedStmt>(AStmt);
7457   // 1.2.2 OpenMP Language Terminology
7458   // Structured block - An executable statement with a single entry at the
7459   // top and a single exit at the bottom.
7460   // The point of exit cannot be a branch out of the structured block.
7461   // longjmp() and throw() must not violate the entry/exit criteria.
7462   CS->getCapturedDecl()->setNothrow();
7463 
7464   setFunctionHasBranchProtectedScope();
7465 
7466   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7467                                       DSAStack->getTaskgroupReductionRef(),
7468                                       DSAStack->isCancelRegion());
7469 }
7470 
7471 namespace {
7472 /// Iteration space of a single for loop.
7473 struct LoopIterationSpace final {
7474   /// True if the condition operator is the strict compare operator (<, > or
7475   /// !=).
7476   bool IsStrictCompare = false;
7477   /// Condition of the loop.
7478   Expr *PreCond = nullptr;
7479   /// This expression calculates the number of iterations in the loop.
7480   /// It is always possible to calculate it before starting the loop.
7481   Expr *NumIterations = nullptr;
7482   /// The loop counter variable.
7483   Expr *CounterVar = nullptr;
7484   /// Private loop counter variable.
7485   Expr *PrivateCounterVar = nullptr;
7486   /// This is initializer for the initial value of #CounterVar.
7487   Expr *CounterInit = nullptr;
7488   /// This is step for the #CounterVar used to generate its update:
7489   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7490   Expr *CounterStep = nullptr;
7491   /// Should step be subtracted?
7492   bool Subtract = false;
7493   /// Source range of the loop init.
7494   SourceRange InitSrcRange;
7495   /// Source range of the loop condition.
7496   SourceRange CondSrcRange;
7497   /// Source range of the loop increment.
7498   SourceRange IncSrcRange;
7499   /// Minimum value that can have the loop control variable. Used to support
7500   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7501   /// since only such variables can be used in non-loop invariant expressions.
7502   Expr *MinValue = nullptr;
7503   /// Maximum value that can have the loop control variable. Used to support
7504   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7505   /// since only such variables can be used in non-loop invariant expressions.
7506   Expr *MaxValue = nullptr;
7507   /// true, if the lower bound depends on the outer loop control var.
7508   bool IsNonRectangularLB = false;
7509   /// true, if the upper bound depends on the outer loop control var.
7510   bool IsNonRectangularUB = false;
7511   /// Index of the loop this loop depends on and forms non-rectangular loop
7512   /// nest.
7513   unsigned LoopDependentIdx = 0;
7514   /// Final condition for the non-rectangular loop nest support. It is used to
7515   /// check that the number of iterations for this particular counter must be
7516   /// finished.
7517   Expr *FinalCondition = nullptr;
7518 };
7519 
7520 /// Helper class for checking canonical form of the OpenMP loops and
7521 /// extracting iteration space of each loop in the loop nest, that will be used
7522 /// for IR generation.
7523 class OpenMPIterationSpaceChecker {
7524   /// Reference to Sema.
7525   Sema &SemaRef;
7526   /// Does the loop associated directive support non-rectangular loops?
7527   bool SupportsNonRectangular;
7528   /// Data-sharing stack.
7529   DSAStackTy &Stack;
7530   /// A location for diagnostics (when there is no some better location).
7531   SourceLocation DefaultLoc;
7532   /// A location for diagnostics (when increment is not compatible).
7533   SourceLocation ConditionLoc;
7534   /// A source location for referring to loop init later.
7535   SourceRange InitSrcRange;
7536   /// A source location for referring to condition later.
7537   SourceRange ConditionSrcRange;
7538   /// A source location for referring to increment later.
7539   SourceRange IncrementSrcRange;
7540   /// Loop variable.
7541   ValueDecl *LCDecl = nullptr;
7542   /// Reference to loop variable.
7543   Expr *LCRef = nullptr;
7544   /// Lower bound (initializer for the var).
7545   Expr *LB = nullptr;
7546   /// Upper bound.
7547   Expr *UB = nullptr;
7548   /// Loop step (increment).
7549   Expr *Step = nullptr;
7550   /// This flag is true when condition is one of:
7551   ///   Var <  UB
7552   ///   Var <= UB
7553   ///   UB  >  Var
7554   ///   UB  >= Var
7555   /// This will have no value when the condition is !=
7556   llvm::Optional<bool> TestIsLessOp;
7557   /// This flag is true when condition is strict ( < or > ).
7558   bool TestIsStrictOp = false;
7559   /// This flag is true when step is subtracted on each iteration.
7560   bool SubtractStep = false;
7561   /// The outer loop counter this loop depends on (if any).
7562   const ValueDecl *DepDecl = nullptr;
7563   /// Contains number of loop (starts from 1) on which loop counter init
7564   /// expression of this loop depends on.
7565   Optional<unsigned> InitDependOnLC;
7566   /// Contains number of loop (starts from 1) on which loop counter condition
7567   /// expression of this loop depends on.
7568   Optional<unsigned> CondDependOnLC;
7569   /// Checks if the provide statement depends on the loop counter.
7570   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7571   /// Original condition required for checking of the exit condition for
7572   /// non-rectangular loop.
7573   Expr *Condition = nullptr;
7574 
7575 public:
7576   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7577                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7578       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7579         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7580   /// Check init-expr for canonical loop form and save loop counter
7581   /// variable - #Var and its initialization value - #LB.
7582   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7583   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7584   /// for less/greater and for strict/non-strict comparison.
7585   bool checkAndSetCond(Expr *S);
7586   /// Check incr-expr for canonical loop form and return true if it
7587   /// does not conform, otherwise save loop step (#Step).
7588   bool checkAndSetInc(Expr *S);
7589   /// Return the loop counter variable.
7590   ValueDecl *getLoopDecl() const { return LCDecl; }
7591   /// Return the reference expression to loop counter variable.
7592   Expr *getLoopDeclRefExpr() const { return LCRef; }
7593   /// Source range of the loop init.
7594   SourceRange getInitSrcRange() const { return InitSrcRange; }
7595   /// Source range of the loop condition.
7596   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7597   /// Source range of the loop increment.
7598   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7599   /// True if the step should be subtracted.
7600   bool shouldSubtractStep() const { return SubtractStep; }
7601   /// True, if the compare operator is strict (<, > or !=).
7602   bool isStrictTestOp() const { return TestIsStrictOp; }
7603   /// Build the expression to calculate the number of iterations.
7604   Expr *buildNumIterations(
7605       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7606       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7607   /// Build the precondition expression for the loops.
7608   Expr *
7609   buildPreCond(Scope *S, Expr *Cond,
7610                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7611   /// Build reference expression to the counter be used for codegen.
7612   DeclRefExpr *
7613   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7614                   DSAStackTy &DSA) const;
7615   /// Build reference expression to the private counter be used for
7616   /// codegen.
7617   Expr *buildPrivateCounterVar() const;
7618   /// Build initialization of the counter be used for codegen.
7619   Expr *buildCounterInit() const;
7620   /// Build step of the counter be used for codegen.
7621   Expr *buildCounterStep() const;
7622   /// Build loop data with counter value for depend clauses in ordered
7623   /// directives.
7624   Expr *
7625   buildOrderedLoopData(Scope *S, Expr *Counter,
7626                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7627                        SourceLocation Loc, Expr *Inc = nullptr,
7628                        OverloadedOperatorKind OOK = OO_Amp);
7629   /// Builds the minimum value for the loop counter.
7630   std::pair<Expr *, Expr *> buildMinMaxValues(
7631       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7632   /// Builds final condition for the non-rectangular loops.
7633   Expr *buildFinalCondition(Scope *S) const;
7634   /// Return true if any expression is dependent.
7635   bool dependent() const;
7636   /// Returns true if the initializer forms non-rectangular loop.
7637   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7638   /// Returns true if the condition forms non-rectangular loop.
7639   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7640   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7641   unsigned getLoopDependentIdx() const {
7642     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7643   }
7644 
7645 private:
7646   /// Check the right-hand side of an assignment in the increment
7647   /// expression.
7648   bool checkAndSetIncRHS(Expr *RHS);
7649   /// Helper to set loop counter variable and its initializer.
7650   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7651                       bool EmitDiags);
7652   /// Helper to set upper bound.
7653   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7654              SourceRange SR, SourceLocation SL);
7655   /// Helper to set loop increment.
7656   bool setStep(Expr *NewStep, bool Subtract);
7657 };
7658 
7659 bool OpenMPIterationSpaceChecker::dependent() const {
7660   if (!LCDecl) {
7661     assert(!LB && !UB && !Step);
7662     return false;
7663   }
7664   return LCDecl->getType()->isDependentType() ||
7665          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7666          (Step && Step->isValueDependent());
7667 }
7668 
7669 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7670                                                  Expr *NewLCRefExpr,
7671                                                  Expr *NewLB, bool EmitDiags) {
7672   // State consistency checking to ensure correct usage.
7673   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7674          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7675   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7676     return true;
7677   LCDecl = getCanonicalDecl(NewLCDecl);
7678   LCRef = NewLCRefExpr;
7679   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7680     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7681       if ((Ctor->isCopyOrMoveConstructor() ||
7682            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7683           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7684         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7685   LB = NewLB;
7686   if (EmitDiags)
7687     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7688   return false;
7689 }
7690 
7691 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7692                                         llvm::Optional<bool> LessOp,
7693                                         bool StrictOp, SourceRange SR,
7694                                         SourceLocation SL) {
7695   // State consistency checking to ensure correct usage.
7696   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7697          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7698   if (!NewUB || NewUB->containsErrors())
7699     return true;
7700   UB = NewUB;
7701   if (LessOp)
7702     TestIsLessOp = LessOp;
7703   TestIsStrictOp = StrictOp;
7704   ConditionSrcRange = SR;
7705   ConditionLoc = SL;
7706   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7707   return false;
7708 }
7709 
7710 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7711   // State consistency checking to ensure correct usage.
7712   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7713   if (!NewStep || NewStep->containsErrors())
7714     return true;
7715   if (!NewStep->isValueDependent()) {
7716     // Check that the step is integer expression.
7717     SourceLocation StepLoc = NewStep->getBeginLoc();
7718     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7719         StepLoc, getExprAsWritten(NewStep));
7720     if (Val.isInvalid())
7721       return true;
7722     NewStep = Val.get();
7723 
7724     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7725     //  If test-expr is of form var relational-op b and relational-op is < or
7726     //  <= then incr-expr must cause var to increase on each iteration of the
7727     //  loop. If test-expr is of form var relational-op b and relational-op is
7728     //  > or >= then incr-expr must cause var to decrease on each iteration of
7729     //  the loop.
7730     //  If test-expr is of form b relational-op var and relational-op is < or
7731     //  <= then incr-expr must cause var to decrease on each iteration of the
7732     //  loop. If test-expr is of form b relational-op var and relational-op is
7733     //  > or >= then incr-expr must cause var to increase on each iteration of
7734     //  the loop.
7735     Optional<llvm::APSInt> Result =
7736         NewStep->getIntegerConstantExpr(SemaRef.Context);
7737     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7738     bool IsConstNeg =
7739         Result && Result->isSigned() && (Subtract != Result->isNegative());
7740     bool IsConstPos =
7741         Result && Result->isSigned() && (Subtract == Result->isNegative());
7742     bool IsConstZero = Result && !Result->getBoolValue();
7743 
7744     // != with increment is treated as <; != with decrement is treated as >
7745     if (!TestIsLessOp.hasValue())
7746       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7747     if (UB &&
7748         (IsConstZero || (TestIsLessOp.getValue()
7749                              ? (IsConstNeg || (IsUnsigned && Subtract))
7750                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
7751       SemaRef.Diag(NewStep->getExprLoc(),
7752                    diag::err_omp_loop_incr_not_compatible)
7753           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7754       SemaRef.Diag(ConditionLoc,
7755                    diag::note_omp_loop_cond_requres_compatible_incr)
7756           << TestIsLessOp.getValue() << ConditionSrcRange;
7757       return true;
7758     }
7759     if (TestIsLessOp.getValue() == Subtract) {
7760       NewStep =
7761           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7762               .get();
7763       Subtract = !Subtract;
7764     }
7765   }
7766 
7767   Step = NewStep;
7768   SubtractStep = Subtract;
7769   return false;
7770 }
7771 
7772 namespace {
7773 /// Checker for the non-rectangular loops. Checks if the initializer or
7774 /// condition expression references loop counter variable.
7775 class LoopCounterRefChecker final
7776     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7777   Sema &SemaRef;
7778   DSAStackTy &Stack;
7779   const ValueDecl *CurLCDecl = nullptr;
7780   const ValueDecl *DepDecl = nullptr;
7781   const ValueDecl *PrevDepDecl = nullptr;
7782   bool IsInitializer = true;
7783   bool SupportsNonRectangular;
7784   unsigned BaseLoopId = 0;
7785   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7786     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7787       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7788           << (IsInitializer ? 0 : 1);
7789       return false;
7790     }
7791     const auto &&Data = Stack.isLoopControlVariable(VD);
7792     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7793     // The type of the loop iterator on which we depend may not have a random
7794     // access iterator type.
7795     if (Data.first && VD->getType()->isRecordType()) {
7796       SmallString<128> Name;
7797       llvm::raw_svector_ostream OS(Name);
7798       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7799                                /*Qualified=*/true);
7800       SemaRef.Diag(E->getExprLoc(),
7801                    diag::err_omp_wrong_dependency_iterator_type)
7802           << OS.str();
7803       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7804       return false;
7805     }
7806     if (Data.first && !SupportsNonRectangular) {
7807       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7808       return false;
7809     }
7810     if (Data.first &&
7811         (DepDecl || (PrevDepDecl &&
7812                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7813       if (!DepDecl && PrevDepDecl)
7814         DepDecl = PrevDepDecl;
7815       SmallString<128> Name;
7816       llvm::raw_svector_ostream OS(Name);
7817       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7818                                     /*Qualified=*/true);
7819       SemaRef.Diag(E->getExprLoc(),
7820                    diag::err_omp_invariant_or_linear_dependency)
7821           << OS.str();
7822       return false;
7823     }
7824     if (Data.first) {
7825       DepDecl = VD;
7826       BaseLoopId = Data.first;
7827     }
7828     return Data.first;
7829   }
7830 
7831 public:
7832   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7833     const ValueDecl *VD = E->getDecl();
7834     if (isa<VarDecl>(VD))
7835       return checkDecl(E, VD);
7836     return false;
7837   }
7838   bool VisitMemberExpr(const MemberExpr *E) {
7839     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7840       const ValueDecl *VD = E->getMemberDecl();
7841       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7842         return checkDecl(E, VD);
7843     }
7844     return false;
7845   }
7846   bool VisitStmt(const Stmt *S) {
7847     bool Res = false;
7848     for (const Stmt *Child : S->children())
7849       Res = (Child && Visit(Child)) || Res;
7850     return Res;
7851   }
7852   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7853                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7854                                  const ValueDecl *PrevDepDecl = nullptr,
7855                                  bool SupportsNonRectangular = true)
7856       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7857         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7858         SupportsNonRectangular(SupportsNonRectangular) {}
7859   unsigned getBaseLoopId() const {
7860     assert(CurLCDecl && "Expected loop dependency.");
7861     return BaseLoopId;
7862   }
7863   const ValueDecl *getDepDecl() const {
7864     assert(CurLCDecl && "Expected loop dependency.");
7865     return DepDecl;
7866   }
7867 };
7868 } // namespace
7869 
7870 Optional<unsigned>
7871 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7872                                                      bool IsInitializer) {
7873   // Check for the non-rectangular loops.
7874   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7875                                         DepDecl, SupportsNonRectangular);
7876   if (LoopStmtChecker.Visit(S)) {
7877     DepDecl = LoopStmtChecker.getDepDecl();
7878     return LoopStmtChecker.getBaseLoopId();
7879   }
7880   return llvm::None;
7881 }
7882 
7883 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7884   // Check init-expr for canonical loop form and save loop counter
7885   // variable - #Var and its initialization value - #LB.
7886   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7887   //   var = lb
7888   //   integer-type var = lb
7889   //   random-access-iterator-type var = lb
7890   //   pointer-type var = lb
7891   //
7892   if (!S) {
7893     if (EmitDiags) {
7894       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7895     }
7896     return true;
7897   }
7898   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7899     if (!ExprTemp->cleanupsHaveSideEffects())
7900       S = ExprTemp->getSubExpr();
7901 
7902   InitSrcRange = S->getSourceRange();
7903   if (Expr *E = dyn_cast<Expr>(S))
7904     S = E->IgnoreParens();
7905   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7906     if (BO->getOpcode() == BO_Assign) {
7907       Expr *LHS = BO->getLHS()->IgnoreParens();
7908       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7909         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7910           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7911             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7912                                   EmitDiags);
7913         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7914       }
7915       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7916         if (ME->isArrow() &&
7917             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7918           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7919                                 EmitDiags);
7920       }
7921     }
7922   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7923     if (DS->isSingleDecl()) {
7924       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7925         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7926           // Accept non-canonical init form here but emit ext. warning.
7927           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7928             SemaRef.Diag(S->getBeginLoc(),
7929                          diag::ext_omp_loop_not_canonical_init)
7930                 << S->getSourceRange();
7931           return setLCDeclAndLB(
7932               Var,
7933               buildDeclRefExpr(SemaRef, Var,
7934                                Var->getType().getNonReferenceType(),
7935                                DS->getBeginLoc()),
7936               Var->getInit(), EmitDiags);
7937         }
7938       }
7939     }
7940   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7941     if (CE->getOperator() == OO_Equal) {
7942       Expr *LHS = CE->getArg(0);
7943       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7944         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7945           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7946             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7947                                   EmitDiags);
7948         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7949       }
7950       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7951         if (ME->isArrow() &&
7952             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7953           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7954                                 EmitDiags);
7955       }
7956     }
7957   }
7958 
7959   if (dependent() || SemaRef.CurContext->isDependentContext())
7960     return false;
7961   if (EmitDiags) {
7962     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7963         << S->getSourceRange();
7964   }
7965   return true;
7966 }
7967 
7968 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7969 /// variable (which may be the loop variable) if possible.
7970 static const ValueDecl *getInitLCDecl(const Expr *E) {
7971   if (!E)
7972     return nullptr;
7973   E = getExprAsWritten(E);
7974   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7975     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7976       if ((Ctor->isCopyOrMoveConstructor() ||
7977            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7978           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7979         E = CE->getArg(0)->IgnoreParenImpCasts();
7980   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7981     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7982       return getCanonicalDecl(VD);
7983   }
7984   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7985     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7986       return getCanonicalDecl(ME->getMemberDecl());
7987   return nullptr;
7988 }
7989 
7990 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7991   // Check test-expr for canonical form, save upper-bound UB, flags for
7992   // less/greater and for strict/non-strict comparison.
7993   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7994   //   var relational-op b
7995   //   b relational-op var
7996   //
7997   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7998   if (!S) {
7999     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
8000         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
8001     return true;
8002   }
8003   Condition = S;
8004   S = getExprAsWritten(S);
8005   SourceLocation CondLoc = S->getBeginLoc();
8006   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
8007                                BinaryOperatorKind Opcode, const Expr *LHS,
8008                                const Expr *RHS, SourceRange SR,
8009                                SourceLocation OpLoc) -> llvm::Optional<bool> {
8010     if (BinaryOperator::isRelationalOp(Opcode)) {
8011       if (getInitLCDecl(LHS) == LCDecl)
8012         return setUB(const_cast<Expr *>(RHS),
8013                      (Opcode == BO_LT || Opcode == BO_LE),
8014                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
8015       if (getInitLCDecl(RHS) == LCDecl)
8016         return setUB(const_cast<Expr *>(LHS),
8017                      (Opcode == BO_GT || Opcode == BO_GE),
8018                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
8019     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
8020       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
8021                    /*LessOp=*/llvm::None,
8022                    /*StrictOp=*/true, SR, OpLoc);
8023     }
8024     return llvm::None;
8025   };
8026   llvm::Optional<bool> Res;
8027   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
8028     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
8029     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
8030                           RBO->getOperatorLoc());
8031   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
8032     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
8033                           BO->getSourceRange(), BO->getOperatorLoc());
8034   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8035     if (CE->getNumArgs() == 2) {
8036       Res = CheckAndSetCond(
8037           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
8038           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
8039     }
8040   }
8041   if (Res.hasValue())
8042     return *Res;
8043   if (dependent() || SemaRef.CurContext->isDependentContext())
8044     return false;
8045   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
8046       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
8047   return true;
8048 }
8049 
8050 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
8051   // RHS of canonical loop form increment can be:
8052   //   var + incr
8053   //   incr + var
8054   //   var - incr
8055   //
8056   RHS = RHS->IgnoreParenImpCasts();
8057   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
8058     if (BO->isAdditiveOp()) {
8059       bool IsAdd = BO->getOpcode() == BO_Add;
8060       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8061         return setStep(BO->getRHS(), !IsAdd);
8062       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
8063         return setStep(BO->getLHS(), /*Subtract=*/false);
8064     }
8065   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
8066     bool IsAdd = CE->getOperator() == OO_Plus;
8067     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
8068       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8069         return setStep(CE->getArg(1), !IsAdd);
8070       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
8071         return setStep(CE->getArg(0), /*Subtract=*/false);
8072     }
8073   }
8074   if (dependent() || SemaRef.CurContext->isDependentContext())
8075     return false;
8076   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8077       << RHS->getSourceRange() << LCDecl;
8078   return true;
8079 }
8080 
8081 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
8082   // Check incr-expr for canonical loop form and return true if it
8083   // does not conform.
8084   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
8085   //   ++var
8086   //   var++
8087   //   --var
8088   //   var--
8089   //   var += incr
8090   //   var -= incr
8091   //   var = var + incr
8092   //   var = incr + var
8093   //   var = var - incr
8094   //
8095   if (!S) {
8096     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
8097     return true;
8098   }
8099   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
8100     if (!ExprTemp->cleanupsHaveSideEffects())
8101       S = ExprTemp->getSubExpr();
8102 
8103   IncrementSrcRange = S->getSourceRange();
8104   S = S->IgnoreParens();
8105   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
8106     if (UO->isIncrementDecrementOp() &&
8107         getInitLCDecl(UO->getSubExpr()) == LCDecl)
8108       return setStep(SemaRef
8109                          .ActOnIntegerConstant(UO->getBeginLoc(),
8110                                                (UO->isDecrementOp() ? -1 : 1))
8111                          .get(),
8112                      /*Subtract=*/false);
8113   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
8114     switch (BO->getOpcode()) {
8115     case BO_AddAssign:
8116     case BO_SubAssign:
8117       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8118         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
8119       break;
8120     case BO_Assign:
8121       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8122         return checkAndSetIncRHS(BO->getRHS());
8123       break;
8124     default:
8125       break;
8126     }
8127   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8128     switch (CE->getOperator()) {
8129     case OO_PlusPlus:
8130     case OO_MinusMinus:
8131       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8132         return setStep(SemaRef
8133                            .ActOnIntegerConstant(
8134                                CE->getBeginLoc(),
8135                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
8136                            .get(),
8137                        /*Subtract=*/false);
8138       break;
8139     case OO_PlusEqual:
8140     case OO_MinusEqual:
8141       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8142         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
8143       break;
8144     case OO_Equal:
8145       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8146         return checkAndSetIncRHS(CE->getArg(1));
8147       break;
8148     default:
8149       break;
8150     }
8151   }
8152   if (dependent() || SemaRef.CurContext->isDependentContext())
8153     return false;
8154   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8155       << S->getSourceRange() << LCDecl;
8156   return true;
8157 }
8158 
8159 static ExprResult
8160 tryBuildCapture(Sema &SemaRef, Expr *Capture,
8161                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8162   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
8163     return Capture;
8164   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
8165     return SemaRef.PerformImplicitConversion(
8166         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
8167         /*AllowExplicit=*/true);
8168   auto I = Captures.find(Capture);
8169   if (I != Captures.end())
8170     return buildCapture(SemaRef, Capture, I->second);
8171   DeclRefExpr *Ref = nullptr;
8172   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
8173   Captures[Capture] = Ref;
8174   return Res;
8175 }
8176 
8177 /// Calculate number of iterations, transforming to unsigned, if number of
8178 /// iterations may be larger than the original type.
8179 static Expr *
8180 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
8181                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
8182                   bool TestIsStrictOp, bool RoundToStep,
8183                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8184   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8185   if (!NewStep.isUsable())
8186     return nullptr;
8187   llvm::APSInt LRes, SRes;
8188   bool IsLowerConst = false, IsStepConst = false;
8189   if (Optional<llvm::APSInt> Res =
8190           Lower->getIntegerConstantExpr(SemaRef.Context)) {
8191     LRes = *Res;
8192     IsLowerConst = true;
8193   }
8194   if (Optional<llvm::APSInt> Res =
8195           Step->getIntegerConstantExpr(SemaRef.Context)) {
8196     SRes = *Res;
8197     IsStepConst = true;
8198   }
8199   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
8200                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
8201                           (TestIsStrictOp && LRes.isStrictlyPositive()));
8202   bool NeedToReorganize = false;
8203   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
8204   if (!NoNeedToConvert && IsLowerConst &&
8205       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
8206     NoNeedToConvert = true;
8207     if (RoundToStep) {
8208       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
8209                         ? LRes.getBitWidth()
8210                         : SRes.getBitWidth();
8211       LRes = LRes.extend(BW + 1);
8212       LRes.setIsSigned(true);
8213       SRes = SRes.extend(BW + 1);
8214       SRes.setIsSigned(true);
8215       LRes -= SRes;
8216       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
8217       LRes = LRes.trunc(BW);
8218     }
8219     if (TestIsStrictOp) {
8220       unsigned BW = LRes.getBitWidth();
8221       LRes = LRes.extend(BW + 1);
8222       LRes.setIsSigned(true);
8223       ++LRes;
8224       NoNeedToConvert =
8225           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
8226       // truncate to the original bitwidth.
8227       LRes = LRes.trunc(BW);
8228     }
8229     NeedToReorganize = NoNeedToConvert;
8230   }
8231   llvm::APSInt URes;
8232   bool IsUpperConst = false;
8233   if (Optional<llvm::APSInt> Res =
8234           Upper->getIntegerConstantExpr(SemaRef.Context)) {
8235     URes = *Res;
8236     IsUpperConst = true;
8237   }
8238   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
8239       (!RoundToStep || IsStepConst)) {
8240     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
8241                                                           : URes.getBitWidth();
8242     LRes = LRes.extend(BW + 1);
8243     LRes.setIsSigned(true);
8244     URes = URes.extend(BW + 1);
8245     URes.setIsSigned(true);
8246     URes -= LRes;
8247     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
8248     NeedToReorganize = NoNeedToConvert;
8249   }
8250   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
8251   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
8252   // unsigned.
8253   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
8254       !LCTy->isDependentType() && LCTy->isIntegerType()) {
8255     QualType LowerTy = Lower->getType();
8256     QualType UpperTy = Upper->getType();
8257     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
8258     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
8259     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
8260         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
8261       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
8262           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
8263       Upper =
8264           SemaRef
8265               .PerformImplicitConversion(
8266                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8267                   CastType, Sema::AA_Converting)
8268               .get();
8269       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
8270       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
8271     }
8272   }
8273   if (!Lower || !Upper || NewStep.isInvalid())
8274     return nullptr;
8275 
8276   ExprResult Diff;
8277   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
8278   // 1]).
8279   if (NeedToReorganize) {
8280     Diff = Lower;
8281 
8282     if (RoundToStep) {
8283       // Lower - Step
8284       Diff =
8285           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
8286       if (!Diff.isUsable())
8287         return nullptr;
8288     }
8289 
8290     // Lower - Step [+ 1]
8291     if (TestIsStrictOp)
8292       Diff = SemaRef.BuildBinOp(
8293           S, DefaultLoc, BO_Add, Diff.get(),
8294           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8295     if (!Diff.isUsable())
8296       return nullptr;
8297 
8298     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8299     if (!Diff.isUsable())
8300       return nullptr;
8301 
8302     // Upper - (Lower - Step [+ 1]).
8303     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
8304     if (!Diff.isUsable())
8305       return nullptr;
8306   } else {
8307     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8308 
8309     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8310       // BuildBinOp already emitted error, this one is to point user to upper
8311       // and lower bound, and to tell what is passed to 'operator-'.
8312       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8313           << Upper->getSourceRange() << Lower->getSourceRange();
8314       return nullptr;
8315     }
8316 
8317     if (!Diff.isUsable())
8318       return nullptr;
8319 
8320     // Upper - Lower [- 1]
8321     if (TestIsStrictOp)
8322       Diff = SemaRef.BuildBinOp(
8323           S, DefaultLoc, BO_Sub, Diff.get(),
8324           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8325     if (!Diff.isUsable())
8326       return nullptr;
8327 
8328     if (RoundToStep) {
8329       // Upper - Lower [- 1] + Step
8330       Diff =
8331           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8332       if (!Diff.isUsable())
8333         return nullptr;
8334     }
8335   }
8336 
8337   // Parentheses (for dumping/debugging purposes only).
8338   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8339   if (!Diff.isUsable())
8340     return nullptr;
8341 
8342   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8343   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8344   if (!Diff.isUsable())
8345     return nullptr;
8346 
8347   return Diff.get();
8348 }
8349 
8350 /// Build the expression to calculate the number of iterations.
8351 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8352     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8353     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8354   QualType VarType = LCDecl->getType().getNonReferenceType();
8355   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8356       !SemaRef.getLangOpts().CPlusPlus)
8357     return nullptr;
8358   Expr *LBVal = LB;
8359   Expr *UBVal = UB;
8360   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8361   // max(LB(MinVal), LB(MaxVal))
8362   if (InitDependOnLC) {
8363     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8364     if (!IS.MinValue || !IS.MaxValue)
8365       return nullptr;
8366     // OuterVar = Min
8367     ExprResult MinValue =
8368         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8369     if (!MinValue.isUsable())
8370       return nullptr;
8371 
8372     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8373                                              IS.CounterVar, MinValue.get());
8374     if (!LBMinVal.isUsable())
8375       return nullptr;
8376     // OuterVar = Min, LBVal
8377     LBMinVal =
8378         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8379     if (!LBMinVal.isUsable())
8380       return nullptr;
8381     // (OuterVar = Min, LBVal)
8382     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8383     if (!LBMinVal.isUsable())
8384       return nullptr;
8385 
8386     // OuterVar = Max
8387     ExprResult MaxValue =
8388         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8389     if (!MaxValue.isUsable())
8390       return nullptr;
8391 
8392     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8393                                              IS.CounterVar, MaxValue.get());
8394     if (!LBMaxVal.isUsable())
8395       return nullptr;
8396     // OuterVar = Max, LBVal
8397     LBMaxVal =
8398         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8399     if (!LBMaxVal.isUsable())
8400       return nullptr;
8401     // (OuterVar = Max, LBVal)
8402     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8403     if (!LBMaxVal.isUsable())
8404       return nullptr;
8405 
8406     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8407     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8408     if (!LBMin || !LBMax)
8409       return nullptr;
8410     // LB(MinVal) < LB(MaxVal)
8411     ExprResult MinLessMaxRes =
8412         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8413     if (!MinLessMaxRes.isUsable())
8414       return nullptr;
8415     Expr *MinLessMax =
8416         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8417     if (!MinLessMax)
8418       return nullptr;
8419     if (TestIsLessOp.getValue()) {
8420       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8421       // LB(MaxVal))
8422       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8423                                                     MinLessMax, LBMin, LBMax);
8424       if (!MinLB.isUsable())
8425         return nullptr;
8426       LBVal = MinLB.get();
8427     } else {
8428       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8429       // LB(MaxVal))
8430       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8431                                                     MinLessMax, LBMax, LBMin);
8432       if (!MaxLB.isUsable())
8433         return nullptr;
8434       LBVal = MaxLB.get();
8435     }
8436   }
8437   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8438   // min(UB(MinVal), UB(MaxVal))
8439   if (CondDependOnLC) {
8440     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8441     if (!IS.MinValue || !IS.MaxValue)
8442       return nullptr;
8443     // OuterVar = Min
8444     ExprResult MinValue =
8445         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8446     if (!MinValue.isUsable())
8447       return nullptr;
8448 
8449     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8450                                              IS.CounterVar, MinValue.get());
8451     if (!UBMinVal.isUsable())
8452       return nullptr;
8453     // OuterVar = Min, UBVal
8454     UBMinVal =
8455         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8456     if (!UBMinVal.isUsable())
8457       return nullptr;
8458     // (OuterVar = Min, UBVal)
8459     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8460     if (!UBMinVal.isUsable())
8461       return nullptr;
8462 
8463     // OuterVar = Max
8464     ExprResult MaxValue =
8465         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8466     if (!MaxValue.isUsable())
8467       return nullptr;
8468 
8469     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8470                                              IS.CounterVar, MaxValue.get());
8471     if (!UBMaxVal.isUsable())
8472       return nullptr;
8473     // OuterVar = Max, UBVal
8474     UBMaxVal =
8475         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8476     if (!UBMaxVal.isUsable())
8477       return nullptr;
8478     // (OuterVar = Max, UBVal)
8479     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8480     if (!UBMaxVal.isUsable())
8481       return nullptr;
8482 
8483     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8484     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8485     if (!UBMin || !UBMax)
8486       return nullptr;
8487     // UB(MinVal) > UB(MaxVal)
8488     ExprResult MinGreaterMaxRes =
8489         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8490     if (!MinGreaterMaxRes.isUsable())
8491       return nullptr;
8492     Expr *MinGreaterMax =
8493         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8494     if (!MinGreaterMax)
8495       return nullptr;
8496     if (TestIsLessOp.getValue()) {
8497       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8498       // UB(MaxVal))
8499       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8500           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8501       if (!MaxUB.isUsable())
8502         return nullptr;
8503       UBVal = MaxUB.get();
8504     } else {
8505       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8506       // UB(MaxVal))
8507       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8508           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8509       if (!MinUB.isUsable())
8510         return nullptr;
8511       UBVal = MinUB.get();
8512     }
8513   }
8514   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8515   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8516   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8517   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8518   if (!Upper || !Lower)
8519     return nullptr;
8520 
8521   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8522                                       Step, VarType, TestIsStrictOp,
8523                                       /*RoundToStep=*/true, Captures);
8524   if (!Diff.isUsable())
8525     return nullptr;
8526 
8527   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8528   QualType Type = Diff.get()->getType();
8529   ASTContext &C = SemaRef.Context;
8530   bool UseVarType = VarType->hasIntegerRepresentation() &&
8531                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8532   if (!Type->isIntegerType() || UseVarType) {
8533     unsigned NewSize =
8534         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8535     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8536                                : Type->hasSignedIntegerRepresentation();
8537     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8538     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8539       Diff = SemaRef.PerformImplicitConversion(
8540           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8541       if (!Diff.isUsable())
8542         return nullptr;
8543     }
8544   }
8545   if (LimitedType) {
8546     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8547     if (NewSize != C.getTypeSize(Type)) {
8548       if (NewSize < C.getTypeSize(Type)) {
8549         assert(NewSize == 64 && "incorrect loop var size");
8550         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8551             << InitSrcRange << ConditionSrcRange;
8552       }
8553       QualType NewType = C.getIntTypeForBitwidth(
8554           NewSize, Type->hasSignedIntegerRepresentation() ||
8555                        C.getTypeSize(Type) < NewSize);
8556       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8557         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8558                                                  Sema::AA_Converting, true);
8559         if (!Diff.isUsable())
8560           return nullptr;
8561       }
8562     }
8563   }
8564 
8565   return Diff.get();
8566 }
8567 
8568 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8569     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8570   // Do not build for iterators, they cannot be used in non-rectangular loop
8571   // nests.
8572   if (LCDecl->getType()->isRecordType())
8573     return std::make_pair(nullptr, nullptr);
8574   // If we subtract, the min is in the condition, otherwise the min is in the
8575   // init value.
8576   Expr *MinExpr = nullptr;
8577   Expr *MaxExpr = nullptr;
8578   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8579   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8580   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8581                                            : CondDependOnLC.hasValue();
8582   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8583                                            : InitDependOnLC.hasValue();
8584   Expr *Lower =
8585       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8586   Expr *Upper =
8587       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8588   if (!Upper || !Lower)
8589     return std::make_pair(nullptr, nullptr);
8590 
8591   if (TestIsLessOp.getValue())
8592     MinExpr = Lower;
8593   else
8594     MaxExpr = Upper;
8595 
8596   // Build minimum/maximum value based on number of iterations.
8597   QualType VarType = LCDecl->getType().getNonReferenceType();
8598 
8599   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8600                                       Step, VarType, TestIsStrictOp,
8601                                       /*RoundToStep=*/false, Captures);
8602   if (!Diff.isUsable())
8603     return std::make_pair(nullptr, nullptr);
8604 
8605   // ((Upper - Lower [- 1]) / Step) * Step
8606   // Parentheses (for dumping/debugging purposes only).
8607   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8608   if (!Diff.isUsable())
8609     return std::make_pair(nullptr, nullptr);
8610 
8611   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8612   if (!NewStep.isUsable())
8613     return std::make_pair(nullptr, nullptr);
8614   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8615   if (!Diff.isUsable())
8616     return std::make_pair(nullptr, nullptr);
8617 
8618   // Parentheses (for dumping/debugging purposes only).
8619   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8620   if (!Diff.isUsable())
8621     return std::make_pair(nullptr, nullptr);
8622 
8623   // Convert to the ptrdiff_t, if original type is pointer.
8624   if (VarType->isAnyPointerType() &&
8625       !SemaRef.Context.hasSameType(
8626           Diff.get()->getType(),
8627           SemaRef.Context.getUnsignedPointerDiffType())) {
8628     Diff = SemaRef.PerformImplicitConversion(
8629         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8630         Sema::AA_Converting, /*AllowExplicit=*/true);
8631   }
8632   if (!Diff.isUsable())
8633     return std::make_pair(nullptr, nullptr);
8634 
8635   if (TestIsLessOp.getValue()) {
8636     // MinExpr = Lower;
8637     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8638     Diff = SemaRef.BuildBinOp(
8639         S, DefaultLoc, BO_Add,
8640         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8641         Diff.get());
8642     if (!Diff.isUsable())
8643       return std::make_pair(nullptr, nullptr);
8644   } else {
8645     // MaxExpr = Upper;
8646     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8647     Diff = SemaRef.BuildBinOp(
8648         S, DefaultLoc, BO_Sub,
8649         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8650         Diff.get());
8651     if (!Diff.isUsable())
8652       return std::make_pair(nullptr, nullptr);
8653   }
8654 
8655   // Convert to the original type.
8656   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8657     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8658                                              Sema::AA_Converting,
8659                                              /*AllowExplicit=*/true);
8660   if (!Diff.isUsable())
8661     return std::make_pair(nullptr, nullptr);
8662 
8663   Sema::TentativeAnalysisScope Trap(SemaRef);
8664   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8665   if (!Diff.isUsable())
8666     return std::make_pair(nullptr, nullptr);
8667 
8668   if (TestIsLessOp.getValue())
8669     MaxExpr = Diff.get();
8670   else
8671     MinExpr = Diff.get();
8672 
8673   return std::make_pair(MinExpr, MaxExpr);
8674 }
8675 
8676 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8677   if (InitDependOnLC || CondDependOnLC)
8678     return Condition;
8679   return nullptr;
8680 }
8681 
8682 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8683     Scope *S, Expr *Cond,
8684     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8685   // Do not build a precondition when the condition/initialization is dependent
8686   // to prevent pessimistic early loop exit.
8687   // TODO: this can be improved by calculating min/max values but not sure that
8688   // it will be very effective.
8689   if (CondDependOnLC || InitDependOnLC)
8690     return SemaRef
8691         .PerformImplicitConversion(
8692             SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8693             SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8694             /*AllowExplicit=*/true)
8695         .get();
8696 
8697   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8698   Sema::TentativeAnalysisScope Trap(SemaRef);
8699 
8700   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8701   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8702   if (!NewLB.isUsable() || !NewUB.isUsable())
8703     return nullptr;
8704 
8705   ExprResult CondExpr = SemaRef.BuildBinOp(
8706       S, DefaultLoc,
8707       TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
8708                               : (TestIsStrictOp ? BO_GT : BO_GE),
8709       NewLB.get(), NewUB.get());
8710   if (CondExpr.isUsable()) {
8711     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8712                                                 SemaRef.Context.BoolTy))
8713       CondExpr = SemaRef.PerformImplicitConversion(
8714           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8715           /*AllowExplicit=*/true);
8716   }
8717 
8718   // Otherwise use original loop condition and evaluate it in runtime.
8719   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8720 }
8721 
8722 /// Build reference expression to the counter be used for codegen.
8723 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8724     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8725     DSAStackTy &DSA) const {
8726   auto *VD = dyn_cast<VarDecl>(LCDecl);
8727   if (!VD) {
8728     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8729     DeclRefExpr *Ref = buildDeclRefExpr(
8730         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8731     const DSAStackTy::DSAVarData Data =
8732         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8733     // If the loop control decl is explicitly marked as private, do not mark it
8734     // as captured again.
8735     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8736       Captures.insert(std::make_pair(LCRef, Ref));
8737     return Ref;
8738   }
8739   return cast<DeclRefExpr>(LCRef);
8740 }
8741 
8742 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8743   if (LCDecl && !LCDecl->isInvalidDecl()) {
8744     QualType Type = LCDecl->getType().getNonReferenceType();
8745     VarDecl *PrivateVar = buildVarDecl(
8746         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8747         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8748         isa<VarDecl>(LCDecl)
8749             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8750             : nullptr);
8751     if (PrivateVar->isInvalidDecl())
8752       return nullptr;
8753     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8754   }
8755   return nullptr;
8756 }
8757 
8758 /// Build initialization of the counter to be used for codegen.
8759 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8760 
8761 /// Build step of the counter be used for codegen.
8762 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8763 
8764 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8765     Scope *S, Expr *Counter,
8766     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8767     Expr *Inc, OverloadedOperatorKind OOK) {
8768   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8769   if (!Cnt)
8770     return nullptr;
8771   if (Inc) {
8772     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8773            "Expected only + or - operations for depend clauses.");
8774     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8775     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8776     if (!Cnt)
8777       return nullptr;
8778   }
8779   QualType VarType = LCDecl->getType().getNonReferenceType();
8780   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8781       !SemaRef.getLangOpts().CPlusPlus)
8782     return nullptr;
8783   // Upper - Lower
8784   Expr *Upper = TestIsLessOp.getValue()
8785                     ? Cnt
8786                     : tryBuildCapture(SemaRef, LB, Captures).get();
8787   Expr *Lower = TestIsLessOp.getValue()
8788                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8789                     : Cnt;
8790   if (!Upper || !Lower)
8791     return nullptr;
8792 
8793   ExprResult Diff = calculateNumIters(
8794       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8795       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8796   if (!Diff.isUsable())
8797     return nullptr;
8798 
8799   return Diff.get();
8800 }
8801 } // namespace
8802 
8803 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8804   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8805   assert(Init && "Expected loop in canonical form.");
8806   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8807   if (AssociatedLoops > 0 &&
8808       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8809     DSAStack->loopStart();
8810     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8811                                     *DSAStack, ForLoc);
8812     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8813       if (ValueDecl *D = ISC.getLoopDecl()) {
8814         auto *VD = dyn_cast<VarDecl>(D);
8815         DeclRefExpr *PrivateRef = nullptr;
8816         if (!VD) {
8817           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8818             VD = Private;
8819           } else {
8820             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8821                                       /*WithInit=*/false);
8822             VD = cast<VarDecl>(PrivateRef->getDecl());
8823           }
8824         }
8825         DSAStack->addLoopControlVariable(D, VD);
8826         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8827         if (LD != D->getCanonicalDecl()) {
8828           DSAStack->resetPossibleLoopCounter();
8829           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8830             MarkDeclarationsReferencedInExpr(
8831                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8832                                  Var->getType().getNonLValueExprType(Context),
8833                                  ForLoc, /*RefersToCapture=*/true));
8834         }
8835         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8836         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8837         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8838         // associated for-loop of a simd construct with just one associated
8839         // for-loop may be listed in a linear clause with a constant-linear-step
8840         // that is the increment of the associated for-loop. The loop iteration
8841         // variable(s) in the associated for-loop(s) of a for or parallel for
8842         // construct may be listed in a private or lastprivate clause.
8843         DSAStackTy::DSAVarData DVar =
8844             DSAStack->getTopDSA(D, /*FromParent=*/false);
8845         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8846         // is declared in the loop and it is predetermined as a private.
8847         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8848         OpenMPClauseKind PredeterminedCKind =
8849             isOpenMPSimdDirective(DKind)
8850                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8851                 : OMPC_private;
8852         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8853               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8854               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8855                                          DVar.CKind != OMPC_private))) ||
8856              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8857                DKind == OMPD_master_taskloop ||
8858                DKind == OMPD_parallel_master_taskloop ||
8859                isOpenMPDistributeDirective(DKind)) &&
8860               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8861               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8862             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8863           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8864               << getOpenMPClauseName(DVar.CKind)
8865               << getOpenMPDirectiveName(DKind)
8866               << getOpenMPClauseName(PredeterminedCKind);
8867           if (DVar.RefExpr == nullptr)
8868             DVar.CKind = PredeterminedCKind;
8869           reportOriginalDsa(*this, DSAStack, D, DVar,
8870                             /*IsLoopIterVar=*/true);
8871         } else if (LoopDeclRefExpr) {
8872           // Make the loop iteration variable private (for worksharing
8873           // constructs), linear (for simd directives with the only one
8874           // associated loop) or lastprivate (for simd directives with several
8875           // collapsed or ordered loops).
8876           if (DVar.CKind == OMPC_unknown)
8877             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8878                              PrivateRef);
8879         }
8880       }
8881     }
8882     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8883   }
8884 }
8885 
8886 /// Called on a for stmt to check and extract its iteration space
8887 /// for further processing (such as collapsing).
8888 static bool checkOpenMPIterationSpace(
8889     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8890     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8891     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8892     Expr *OrderedLoopCountExpr,
8893     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8894     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8895     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8896   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8897   // OpenMP [2.9.1, Canonical Loop Form]
8898   //   for (init-expr; test-expr; incr-expr) structured-block
8899   //   for (range-decl: range-expr) structured-block
8900   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8901     S = CanonLoop->getLoopStmt();
8902   auto *For = dyn_cast_or_null<ForStmt>(S);
8903   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8904   // Ranged for is supported only in OpenMP 5.0.
8905   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8906     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8907         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8908         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8909         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8910     if (TotalNestedLoopCount > 1) {
8911       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8912         SemaRef.Diag(DSA.getConstructLoc(),
8913                      diag::note_omp_collapse_ordered_expr)
8914             << 2 << CollapseLoopCountExpr->getSourceRange()
8915             << OrderedLoopCountExpr->getSourceRange();
8916       else if (CollapseLoopCountExpr)
8917         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8918                      diag::note_omp_collapse_ordered_expr)
8919             << 0 << CollapseLoopCountExpr->getSourceRange();
8920       else
8921         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8922                      diag::note_omp_collapse_ordered_expr)
8923             << 1 << OrderedLoopCountExpr->getSourceRange();
8924     }
8925     return true;
8926   }
8927   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8928          "No loop body.");
8929   // Postpone analysis in dependent contexts for ranged for loops.
8930   if (CXXFor && SemaRef.CurContext->isDependentContext())
8931     return false;
8932 
8933   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8934                                   For ? For->getForLoc() : CXXFor->getForLoc());
8935 
8936   // Check init.
8937   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8938   if (ISC.checkAndSetInit(Init))
8939     return true;
8940 
8941   bool HasErrors = false;
8942 
8943   // Check loop variable's type.
8944   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8945     // OpenMP [2.6, Canonical Loop Form]
8946     // Var is one of the following:
8947     //   A variable of signed or unsigned integer type.
8948     //   For C++, a variable of a random access iterator type.
8949     //   For C, a variable of a pointer type.
8950     QualType VarType = LCDecl->getType().getNonReferenceType();
8951     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8952         !VarType->isPointerType() &&
8953         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8954       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8955           << SemaRef.getLangOpts().CPlusPlus;
8956       HasErrors = true;
8957     }
8958 
8959     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8960     // a Construct
8961     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8962     // parallel for construct is (are) private.
8963     // The loop iteration variable in the associated for-loop of a simd
8964     // construct with just one associated for-loop is linear with a
8965     // constant-linear-step that is the increment of the associated for-loop.
8966     // Exclude loop var from the list of variables with implicitly defined data
8967     // sharing attributes.
8968     VarsWithImplicitDSA.erase(LCDecl);
8969 
8970     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8971 
8972     // Check test-expr.
8973     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8974 
8975     // Check incr-expr.
8976     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8977   }
8978 
8979   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8980     return HasErrors;
8981 
8982   // Build the loop's iteration space representation.
8983   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8984       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8985   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8986       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8987                              (isOpenMPWorksharingDirective(DKind) ||
8988                               isOpenMPGenericLoopDirective(DKind) ||
8989                               isOpenMPTaskLoopDirective(DKind) ||
8990                               isOpenMPDistributeDirective(DKind) ||
8991                               isOpenMPLoopTransformationDirective(DKind)),
8992                              Captures);
8993   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8994       ISC.buildCounterVar(Captures, DSA);
8995   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8996       ISC.buildPrivateCounterVar();
8997   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8998   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8999   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
9000   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
9001       ISC.getConditionSrcRange();
9002   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
9003       ISC.getIncrementSrcRange();
9004   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
9005   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
9006       ISC.isStrictTestOp();
9007   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
9008            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
9009       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
9010   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
9011       ISC.buildFinalCondition(DSA.getCurScope());
9012   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
9013       ISC.doesInitDependOnLC();
9014   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
9015       ISC.doesCondDependOnLC();
9016   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
9017       ISC.getLoopDependentIdx();
9018 
9019   HasErrors |=
9020       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
9021        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
9022        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
9023        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
9024        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
9025        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
9026   if (!HasErrors && DSA.isOrderedRegion()) {
9027     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
9028       if (CurrentNestedLoopCount <
9029           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
9030         DSA.getOrderedRegionParam().second->setLoopNumIterations(
9031             CurrentNestedLoopCount,
9032             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
9033         DSA.getOrderedRegionParam().second->setLoopCounter(
9034             CurrentNestedLoopCount,
9035             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
9036       }
9037     }
9038     for (auto &Pair : DSA.getDoacrossDependClauses()) {
9039       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
9040         // Erroneous case - clause has some problems.
9041         continue;
9042       }
9043       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
9044           Pair.second.size() <= CurrentNestedLoopCount) {
9045         // Erroneous case - clause has some problems.
9046         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
9047         continue;
9048       }
9049       Expr *CntValue;
9050       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
9051         CntValue = ISC.buildOrderedLoopData(
9052             DSA.getCurScope(),
9053             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
9054             Pair.first->getDependencyLoc());
9055       else
9056         CntValue = ISC.buildOrderedLoopData(
9057             DSA.getCurScope(),
9058             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
9059             Pair.first->getDependencyLoc(),
9060             Pair.second[CurrentNestedLoopCount].first,
9061             Pair.second[CurrentNestedLoopCount].second);
9062       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
9063     }
9064   }
9065 
9066   return HasErrors;
9067 }
9068 
9069 /// Build 'VarRef = Start.
9070 static ExprResult
9071 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
9072                  ExprResult Start, bool IsNonRectangularLB,
9073                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9074   // Build 'VarRef = Start.
9075   ExprResult NewStart = IsNonRectangularLB
9076                             ? Start.get()
9077                             : tryBuildCapture(SemaRef, Start.get(), Captures);
9078   if (!NewStart.isUsable())
9079     return ExprError();
9080   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
9081                                    VarRef.get()->getType())) {
9082     NewStart = SemaRef.PerformImplicitConversion(
9083         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
9084         /*AllowExplicit=*/true);
9085     if (!NewStart.isUsable())
9086       return ExprError();
9087   }
9088 
9089   ExprResult Init =
9090       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9091   return Init;
9092 }
9093 
9094 /// Build 'VarRef = Start + Iter * Step'.
9095 static ExprResult buildCounterUpdate(
9096     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
9097     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
9098     bool IsNonRectangularLB,
9099     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
9100   // Add parentheses (for debugging purposes only).
9101   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
9102   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
9103       !Step.isUsable())
9104     return ExprError();
9105 
9106   ExprResult NewStep = Step;
9107   if (Captures)
9108     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
9109   if (NewStep.isInvalid())
9110     return ExprError();
9111   ExprResult Update =
9112       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
9113   if (!Update.isUsable())
9114     return ExprError();
9115 
9116   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
9117   // 'VarRef = Start (+|-) Iter * Step'.
9118   if (!Start.isUsable())
9119     return ExprError();
9120   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
9121   if (!NewStart.isUsable())
9122     return ExprError();
9123   if (Captures && !IsNonRectangularLB)
9124     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
9125   if (NewStart.isInvalid())
9126     return ExprError();
9127 
9128   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
9129   ExprResult SavedUpdate = Update;
9130   ExprResult UpdateVal;
9131   if (VarRef.get()->getType()->isOverloadableType() ||
9132       NewStart.get()->getType()->isOverloadableType() ||
9133       Update.get()->getType()->isOverloadableType()) {
9134     Sema::TentativeAnalysisScope Trap(SemaRef);
9135 
9136     Update =
9137         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9138     if (Update.isUsable()) {
9139       UpdateVal =
9140           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
9141                              VarRef.get(), SavedUpdate.get());
9142       if (UpdateVal.isUsable()) {
9143         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
9144                                             UpdateVal.get());
9145       }
9146     }
9147   }
9148 
9149   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
9150   if (!Update.isUsable() || !UpdateVal.isUsable()) {
9151     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
9152                                 NewStart.get(), SavedUpdate.get());
9153     if (!Update.isUsable())
9154       return ExprError();
9155 
9156     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
9157                                      VarRef.get()->getType())) {
9158       Update = SemaRef.PerformImplicitConversion(
9159           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
9160       if (!Update.isUsable())
9161         return ExprError();
9162     }
9163 
9164     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
9165   }
9166   return Update;
9167 }
9168 
9169 /// Convert integer expression \a E to make it have at least \a Bits
9170 /// bits.
9171 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
9172   if (E == nullptr)
9173     return ExprError();
9174   ASTContext &C = SemaRef.Context;
9175   QualType OldType = E->getType();
9176   unsigned HasBits = C.getTypeSize(OldType);
9177   if (HasBits >= Bits)
9178     return ExprResult(E);
9179   // OK to convert to signed, because new type has more bits than old.
9180   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
9181   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
9182                                            true);
9183 }
9184 
9185 /// Check if the given expression \a E is a constant integer that fits
9186 /// into \a Bits bits.
9187 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
9188   if (E == nullptr)
9189     return false;
9190   if (Optional<llvm::APSInt> Result =
9191           E->getIntegerConstantExpr(SemaRef.Context))
9192     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
9193   return false;
9194 }
9195 
9196 /// Build preinits statement for the given declarations.
9197 static Stmt *buildPreInits(ASTContext &Context,
9198                            MutableArrayRef<Decl *> PreInits) {
9199   if (!PreInits.empty()) {
9200     return new (Context) DeclStmt(
9201         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
9202         SourceLocation(), SourceLocation());
9203   }
9204   return nullptr;
9205 }
9206 
9207 /// Build preinits statement for the given declarations.
9208 static Stmt *
9209 buildPreInits(ASTContext &Context,
9210               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9211   if (!Captures.empty()) {
9212     SmallVector<Decl *, 16> PreInits;
9213     for (const auto &Pair : Captures)
9214       PreInits.push_back(Pair.second->getDecl());
9215     return buildPreInits(Context, PreInits);
9216   }
9217   return nullptr;
9218 }
9219 
9220 /// Build postupdate expression for the given list of postupdates expressions.
9221 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
9222   Expr *PostUpdate = nullptr;
9223   if (!PostUpdates.empty()) {
9224     for (Expr *E : PostUpdates) {
9225       Expr *ConvE = S.BuildCStyleCastExpr(
9226                          E->getExprLoc(),
9227                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
9228                          E->getExprLoc(), E)
9229                         .get();
9230       PostUpdate = PostUpdate
9231                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
9232                                               PostUpdate, ConvE)
9233                              .get()
9234                        : ConvE;
9235     }
9236   }
9237   return PostUpdate;
9238 }
9239 
9240 /// Called on a for stmt to check itself and nested loops (if any).
9241 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
9242 /// number of collapsed loops otherwise.
9243 static unsigned
9244 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
9245                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
9246                 DSAStackTy &DSA,
9247                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
9248                 OMPLoopBasedDirective::HelperExprs &Built) {
9249   unsigned NestedLoopCount = 1;
9250   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
9251                                     !isOpenMPLoopTransformationDirective(DKind);
9252 
9253   if (CollapseLoopCountExpr) {
9254     // Found 'collapse' clause - calculate collapse number.
9255     Expr::EvalResult Result;
9256     if (!CollapseLoopCountExpr->isValueDependent() &&
9257         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
9258       NestedLoopCount = Result.Val.getInt().getLimitedValue();
9259     } else {
9260       Built.clear(/*Size=*/1);
9261       return 1;
9262     }
9263   }
9264   unsigned OrderedLoopCount = 1;
9265   if (OrderedLoopCountExpr) {
9266     // Found 'ordered' clause - calculate collapse number.
9267     Expr::EvalResult EVResult;
9268     if (!OrderedLoopCountExpr->isValueDependent() &&
9269         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
9270                                             SemaRef.getASTContext())) {
9271       llvm::APSInt Result = EVResult.Val.getInt();
9272       if (Result.getLimitedValue() < NestedLoopCount) {
9273         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
9274                      diag::err_omp_wrong_ordered_loop_count)
9275             << OrderedLoopCountExpr->getSourceRange();
9276         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9277                      diag::note_collapse_loop_count)
9278             << CollapseLoopCountExpr->getSourceRange();
9279       }
9280       OrderedLoopCount = Result.getLimitedValue();
9281     } else {
9282       Built.clear(/*Size=*/1);
9283       return 1;
9284     }
9285   }
9286   // This is helper routine for loop directives (e.g., 'for', 'simd',
9287   // 'for simd', etc.).
9288   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9289   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
9290   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
9291   if (!OMPLoopBasedDirective::doForAllLoops(
9292           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
9293           SupportsNonPerfectlyNested, NumLoops,
9294           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
9295            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
9296            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
9297             if (checkOpenMPIterationSpace(
9298                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
9299                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
9300                     VarsWithImplicitDSA, IterSpaces, Captures))
9301               return true;
9302             if (Cnt > 0 && Cnt >= NestedLoopCount &&
9303                 IterSpaces[Cnt].CounterVar) {
9304               // Handle initialization of captured loop iterator variables.
9305               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
9306               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
9307                 Captures[DRE] = DRE;
9308               }
9309             }
9310             return false;
9311           },
9312           [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
9313             Stmt *DependentPreInits = Transform->getPreInits();
9314             if (!DependentPreInits)
9315               return;
9316             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9317               auto *D = cast<VarDecl>(C);
9318               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9319                                                   Transform->getBeginLoc());
9320               Captures[Ref] = Ref;
9321             }
9322           }))
9323     return 0;
9324 
9325   Built.clear(/* size */ NestedLoopCount);
9326 
9327   if (SemaRef.CurContext->isDependentContext())
9328     return NestedLoopCount;
9329 
9330   // An example of what is generated for the following code:
9331   //
9332   //   #pragma omp simd collapse(2) ordered(2)
9333   //   for (i = 0; i < NI; ++i)
9334   //     for (k = 0; k < NK; ++k)
9335   //       for (j = J0; j < NJ; j+=2) {
9336   //         <loop body>
9337   //       }
9338   //
9339   // We generate the code below.
9340   // Note: the loop body may be outlined in CodeGen.
9341   // Note: some counters may be C++ classes, operator- is used to find number of
9342   // iterations and operator+= to calculate counter value.
9343   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9344   // or i64 is currently supported).
9345   //
9346   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9347   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9348   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9349   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9350   //     // similar updates for vars in clauses (e.g. 'linear')
9351   //     <loop body (using local i and j)>
9352   //   }
9353   //   i = NI; // assign final values of counters
9354   //   j = NJ;
9355   //
9356 
9357   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9358   // the iteration counts of the collapsed for loops.
9359   // Precondition tests if there is at least one iteration (all conditions are
9360   // true).
9361   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9362   Expr *N0 = IterSpaces[0].NumIterations;
9363   ExprResult LastIteration32 =
9364       widenIterationCount(/*Bits=*/32,
9365                           SemaRef
9366                               .PerformImplicitConversion(
9367                                   N0->IgnoreImpCasts(), N0->getType(),
9368                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9369                               .get(),
9370                           SemaRef);
9371   ExprResult LastIteration64 = widenIterationCount(
9372       /*Bits=*/64,
9373       SemaRef
9374           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9375                                      Sema::AA_Converting,
9376                                      /*AllowExplicit=*/true)
9377           .get(),
9378       SemaRef);
9379 
9380   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9381     return NestedLoopCount;
9382 
9383   ASTContext &C = SemaRef.Context;
9384   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9385 
9386   Scope *CurScope = DSA.getCurScope();
9387   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9388     if (PreCond.isUsable()) {
9389       PreCond =
9390           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9391                              PreCond.get(), IterSpaces[Cnt].PreCond);
9392     }
9393     Expr *N = IterSpaces[Cnt].NumIterations;
9394     SourceLocation Loc = N->getExprLoc();
9395     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9396     if (LastIteration32.isUsable())
9397       LastIteration32 = SemaRef.BuildBinOp(
9398           CurScope, Loc, BO_Mul, LastIteration32.get(),
9399           SemaRef
9400               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9401                                          Sema::AA_Converting,
9402                                          /*AllowExplicit=*/true)
9403               .get());
9404     if (LastIteration64.isUsable())
9405       LastIteration64 = SemaRef.BuildBinOp(
9406           CurScope, Loc, BO_Mul, LastIteration64.get(),
9407           SemaRef
9408               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9409                                          Sema::AA_Converting,
9410                                          /*AllowExplicit=*/true)
9411               .get());
9412   }
9413 
9414   // Choose either the 32-bit or 64-bit version.
9415   ExprResult LastIteration = LastIteration64;
9416   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9417       (LastIteration32.isUsable() &&
9418        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9419        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9420         fitsInto(
9421             /*Bits=*/32,
9422             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9423             LastIteration64.get(), SemaRef))))
9424     LastIteration = LastIteration32;
9425   QualType VType = LastIteration.get()->getType();
9426   QualType RealVType = VType;
9427   QualType StrideVType = VType;
9428   if (isOpenMPTaskLoopDirective(DKind)) {
9429     VType =
9430         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9431     StrideVType =
9432         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9433   }
9434 
9435   if (!LastIteration.isUsable())
9436     return 0;
9437 
9438   // Save the number of iterations.
9439   ExprResult NumIterations = LastIteration;
9440   {
9441     LastIteration = SemaRef.BuildBinOp(
9442         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9443         LastIteration.get(),
9444         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9445     if (!LastIteration.isUsable())
9446       return 0;
9447   }
9448 
9449   // Calculate the last iteration number beforehand instead of doing this on
9450   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9451   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9452   ExprResult CalcLastIteration;
9453   if (!IsConstant) {
9454     ExprResult SaveRef =
9455         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9456     LastIteration = SaveRef;
9457 
9458     // Prepare SaveRef + 1.
9459     NumIterations = SemaRef.BuildBinOp(
9460         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9461         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9462     if (!NumIterations.isUsable())
9463       return 0;
9464   }
9465 
9466   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9467 
9468   // Build variables passed into runtime, necessary for worksharing directives.
9469   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9470   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9471       isOpenMPDistributeDirective(DKind) ||
9472       isOpenMPGenericLoopDirective(DKind) ||
9473       isOpenMPLoopTransformationDirective(DKind)) {
9474     // Lower bound variable, initialized with zero.
9475     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9476     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9477     SemaRef.AddInitializerToDecl(LBDecl,
9478                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9479                                  /*DirectInit*/ false);
9480 
9481     // Upper bound variable, initialized with last iteration number.
9482     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9483     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9484     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9485                                  /*DirectInit*/ false);
9486 
9487     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9488     // This will be used to implement clause 'lastprivate'.
9489     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9490     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9491     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9492     SemaRef.AddInitializerToDecl(ILDecl,
9493                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9494                                  /*DirectInit*/ false);
9495 
9496     // Stride variable returned by runtime (we initialize it to 1 by default).
9497     VarDecl *STDecl =
9498         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9499     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9500     SemaRef.AddInitializerToDecl(STDecl,
9501                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9502                                  /*DirectInit*/ false);
9503 
9504     // Build expression: UB = min(UB, LastIteration)
9505     // It is necessary for CodeGen of directives with static scheduling.
9506     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9507                                                 UB.get(), LastIteration.get());
9508     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9509         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9510         LastIteration.get(), UB.get());
9511     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9512                              CondOp.get());
9513     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9514 
9515     // If we have a combined directive that combines 'distribute', 'for' or
9516     // 'simd' we need to be able to access the bounds of the schedule of the
9517     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9518     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9519     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9520       // Lower bound variable, initialized with zero.
9521       VarDecl *CombLBDecl =
9522           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9523       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9524       SemaRef.AddInitializerToDecl(
9525           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9526           /*DirectInit*/ false);
9527 
9528       // Upper bound variable, initialized with last iteration number.
9529       VarDecl *CombUBDecl =
9530           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9531       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9532       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9533                                    /*DirectInit*/ false);
9534 
9535       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9536           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9537       ExprResult CombCondOp =
9538           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9539                                      LastIteration.get(), CombUB.get());
9540       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9541                                    CombCondOp.get());
9542       CombEUB =
9543           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9544 
9545       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9546       // We expect to have at least 2 more parameters than the 'parallel'
9547       // directive does - the lower and upper bounds of the previous schedule.
9548       assert(CD->getNumParams() >= 4 &&
9549              "Unexpected number of parameters in loop combined directive");
9550 
9551       // Set the proper type for the bounds given what we learned from the
9552       // enclosed loops.
9553       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9554       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9555 
9556       // Previous lower and upper bounds are obtained from the region
9557       // parameters.
9558       PrevLB =
9559           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9560       PrevUB =
9561           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9562     }
9563   }
9564 
9565   // Build the iteration variable and its initialization before loop.
9566   ExprResult IV;
9567   ExprResult Init, CombInit;
9568   {
9569     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9570     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9571     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9572                  isOpenMPGenericLoopDirective(DKind) ||
9573                  isOpenMPTaskLoopDirective(DKind) ||
9574                  isOpenMPDistributeDirective(DKind) ||
9575                  isOpenMPLoopTransformationDirective(DKind))
9576                     ? LB.get()
9577                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9578     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9579     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9580 
9581     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9582       Expr *CombRHS =
9583           (isOpenMPWorksharingDirective(DKind) ||
9584            isOpenMPGenericLoopDirective(DKind) ||
9585            isOpenMPTaskLoopDirective(DKind) ||
9586            isOpenMPDistributeDirective(DKind))
9587               ? CombLB.get()
9588               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9589       CombInit =
9590           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9591       CombInit =
9592           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9593     }
9594   }
9595 
9596   bool UseStrictCompare =
9597       RealVType->hasUnsignedIntegerRepresentation() &&
9598       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9599         return LIS.IsStrictCompare;
9600       });
9601   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9602   // unsigned IV)) for worksharing loops.
9603   SourceLocation CondLoc = AStmt->getBeginLoc();
9604   Expr *BoundUB = UB.get();
9605   if (UseStrictCompare) {
9606     BoundUB =
9607         SemaRef
9608             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9609                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9610             .get();
9611     BoundUB =
9612         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9613   }
9614   ExprResult Cond =
9615       (isOpenMPWorksharingDirective(DKind) ||
9616        isOpenMPGenericLoopDirective(DKind) ||
9617        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9618        isOpenMPLoopTransformationDirective(DKind))
9619           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9620                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9621                                BoundUB)
9622           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9623                                NumIterations.get());
9624   ExprResult CombDistCond;
9625   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9626     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9627                                       NumIterations.get());
9628   }
9629 
9630   ExprResult CombCond;
9631   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9632     Expr *BoundCombUB = CombUB.get();
9633     if (UseStrictCompare) {
9634       BoundCombUB =
9635           SemaRef
9636               .BuildBinOp(
9637                   CurScope, CondLoc, BO_Add, BoundCombUB,
9638                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9639               .get();
9640       BoundCombUB =
9641           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9642               .get();
9643     }
9644     CombCond =
9645         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9646                            IV.get(), BoundCombUB);
9647   }
9648   // Loop increment (IV = IV + 1)
9649   SourceLocation IncLoc = AStmt->getBeginLoc();
9650   ExprResult Inc =
9651       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9652                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9653   if (!Inc.isUsable())
9654     return 0;
9655   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9656   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9657   if (!Inc.isUsable())
9658     return 0;
9659 
9660   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9661   // Used for directives with static scheduling.
9662   // In combined construct, add combined version that use CombLB and CombUB
9663   // base variables for the update
9664   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9665   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9666       isOpenMPGenericLoopDirective(DKind) ||
9667       isOpenMPDistributeDirective(DKind) ||
9668       isOpenMPLoopTransformationDirective(DKind)) {
9669     // LB + ST
9670     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9671     if (!NextLB.isUsable())
9672       return 0;
9673     // LB = LB + ST
9674     NextLB =
9675         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9676     NextLB =
9677         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9678     if (!NextLB.isUsable())
9679       return 0;
9680     // UB + ST
9681     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9682     if (!NextUB.isUsable())
9683       return 0;
9684     // UB = UB + ST
9685     NextUB =
9686         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9687     NextUB =
9688         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9689     if (!NextUB.isUsable())
9690       return 0;
9691     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9692       CombNextLB =
9693           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9694       if (!NextLB.isUsable())
9695         return 0;
9696       // LB = LB + ST
9697       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9698                                       CombNextLB.get());
9699       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9700                                                /*DiscardedValue*/ false);
9701       if (!CombNextLB.isUsable())
9702         return 0;
9703       // UB + ST
9704       CombNextUB =
9705           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9706       if (!CombNextUB.isUsable())
9707         return 0;
9708       // UB = UB + ST
9709       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9710                                       CombNextUB.get());
9711       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9712                                                /*DiscardedValue*/ false);
9713       if (!CombNextUB.isUsable())
9714         return 0;
9715     }
9716   }
9717 
9718   // Create increment expression for distribute loop when combined in a same
9719   // directive with for as IV = IV + ST; ensure upper bound expression based
9720   // on PrevUB instead of NumIterations - used to implement 'for' when found
9721   // in combination with 'distribute', like in 'distribute parallel for'
9722   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9723   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9724   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9725     DistCond = SemaRef.BuildBinOp(
9726         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9727     assert(DistCond.isUsable() && "distribute cond expr was not built");
9728 
9729     DistInc =
9730         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9731     assert(DistInc.isUsable() && "distribute inc expr was not built");
9732     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9733                                  DistInc.get());
9734     DistInc =
9735         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9736     assert(DistInc.isUsable() && "distribute inc expr was not built");
9737 
9738     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9739     // construct
9740     ExprResult NewPrevUB = PrevUB;
9741     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9742     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9743                                      PrevUB.get()->getType())) {
9744       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9745           DistEUBLoc,
9746           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9747           DistEUBLoc, NewPrevUB.get());
9748       if (!NewPrevUB.isUsable())
9749         return 0;
9750     }
9751     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9752                                                 UB.get(), NewPrevUB.get());
9753     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9754         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9755     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9756                                  CondOp.get());
9757     PrevEUB =
9758         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9759 
9760     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9761     // parallel for is in combination with a distribute directive with
9762     // schedule(static, 1)
9763     Expr *BoundPrevUB = PrevUB.get();
9764     if (UseStrictCompare) {
9765       BoundPrevUB =
9766           SemaRef
9767               .BuildBinOp(
9768                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9769                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9770               .get();
9771       BoundPrevUB =
9772           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9773               .get();
9774     }
9775     ParForInDistCond =
9776         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9777                            IV.get(), BoundPrevUB);
9778   }
9779 
9780   // Build updates and final values of the loop counters.
9781   bool HasErrors = false;
9782   Built.Counters.resize(NestedLoopCount);
9783   Built.Inits.resize(NestedLoopCount);
9784   Built.Updates.resize(NestedLoopCount);
9785   Built.Finals.resize(NestedLoopCount);
9786   Built.DependentCounters.resize(NestedLoopCount);
9787   Built.DependentInits.resize(NestedLoopCount);
9788   Built.FinalsConditions.resize(NestedLoopCount);
9789   {
9790     // We implement the following algorithm for obtaining the
9791     // original loop iteration variable values based on the
9792     // value of the collapsed loop iteration variable IV.
9793     //
9794     // Let n+1 be the number of collapsed loops in the nest.
9795     // Iteration variables (I0, I1, .... In)
9796     // Iteration counts (N0, N1, ... Nn)
9797     //
9798     // Acc = IV;
9799     //
9800     // To compute Ik for loop k, 0 <= k <= n, generate:
9801     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9802     //    Ik = Acc / Prod;
9803     //    Acc -= Ik * Prod;
9804     //
9805     ExprResult Acc = IV;
9806     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9807       LoopIterationSpace &IS = IterSpaces[Cnt];
9808       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9809       ExprResult Iter;
9810 
9811       // Compute prod
9812       ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9813       for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
9814         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9815                                   IterSpaces[K].NumIterations);
9816 
9817       // Iter = Acc / Prod
9818       // If there is at least one more inner loop to avoid
9819       // multiplication by 1.
9820       if (Cnt + 1 < NestedLoopCount)
9821         Iter =
9822             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
9823       else
9824         Iter = Acc;
9825       if (!Iter.isUsable()) {
9826         HasErrors = true;
9827         break;
9828       }
9829 
9830       // Update Acc:
9831       // Acc -= Iter * Prod
9832       // Check if there is at least one more inner loop to avoid
9833       // multiplication by 1.
9834       if (Cnt + 1 < NestedLoopCount)
9835         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
9836                                   Prod.get());
9837       else
9838         Prod = Iter;
9839       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
9840 
9841       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9842       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9843       DeclRefExpr *CounterVar = buildDeclRefExpr(
9844           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9845           /*RefersToCapture=*/true);
9846       ExprResult Init =
9847           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9848                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9849       if (!Init.isUsable()) {
9850         HasErrors = true;
9851         break;
9852       }
9853       ExprResult Update = buildCounterUpdate(
9854           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9855           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9856       if (!Update.isUsable()) {
9857         HasErrors = true;
9858         break;
9859       }
9860 
9861       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9862       ExprResult Final =
9863           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9864                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9865                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9866       if (!Final.isUsable()) {
9867         HasErrors = true;
9868         break;
9869       }
9870 
9871       if (!Update.isUsable() || !Final.isUsable()) {
9872         HasErrors = true;
9873         break;
9874       }
9875       // Save results
9876       Built.Counters[Cnt] = IS.CounterVar;
9877       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9878       Built.Inits[Cnt] = Init.get();
9879       Built.Updates[Cnt] = Update.get();
9880       Built.Finals[Cnt] = Final.get();
9881       Built.DependentCounters[Cnt] = nullptr;
9882       Built.DependentInits[Cnt] = nullptr;
9883       Built.FinalsConditions[Cnt] = nullptr;
9884       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9885         Built.DependentCounters[Cnt] =
9886             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9887         Built.DependentInits[Cnt] =
9888             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9889         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9890       }
9891     }
9892   }
9893 
9894   if (HasErrors)
9895     return 0;
9896 
9897   // Save results
9898   Built.IterationVarRef = IV.get();
9899   Built.LastIteration = LastIteration.get();
9900   Built.NumIterations = NumIterations.get();
9901   Built.CalcLastIteration = SemaRef
9902                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9903                                                      /*DiscardedValue=*/false)
9904                                 .get();
9905   Built.PreCond = PreCond.get();
9906   Built.PreInits = buildPreInits(C, Captures);
9907   Built.Cond = Cond.get();
9908   Built.Init = Init.get();
9909   Built.Inc = Inc.get();
9910   Built.LB = LB.get();
9911   Built.UB = UB.get();
9912   Built.IL = IL.get();
9913   Built.ST = ST.get();
9914   Built.EUB = EUB.get();
9915   Built.NLB = NextLB.get();
9916   Built.NUB = NextUB.get();
9917   Built.PrevLB = PrevLB.get();
9918   Built.PrevUB = PrevUB.get();
9919   Built.DistInc = DistInc.get();
9920   Built.PrevEUB = PrevEUB.get();
9921   Built.DistCombinedFields.LB = CombLB.get();
9922   Built.DistCombinedFields.UB = CombUB.get();
9923   Built.DistCombinedFields.EUB = CombEUB.get();
9924   Built.DistCombinedFields.Init = CombInit.get();
9925   Built.DistCombinedFields.Cond = CombCond.get();
9926   Built.DistCombinedFields.NLB = CombNextLB.get();
9927   Built.DistCombinedFields.NUB = CombNextUB.get();
9928   Built.DistCombinedFields.DistCond = CombDistCond.get();
9929   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9930 
9931   return NestedLoopCount;
9932 }
9933 
9934 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9935   auto CollapseClauses =
9936       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9937   if (CollapseClauses.begin() != CollapseClauses.end())
9938     return (*CollapseClauses.begin())->getNumForLoops();
9939   return nullptr;
9940 }
9941 
9942 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9943   auto OrderedClauses =
9944       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9945   if (OrderedClauses.begin() != OrderedClauses.end())
9946     return (*OrderedClauses.begin())->getNumForLoops();
9947   return nullptr;
9948 }
9949 
9950 static bool checkSimdlenSafelenSpecified(Sema &S,
9951                                          const ArrayRef<OMPClause *> Clauses) {
9952   const OMPSafelenClause *Safelen = nullptr;
9953   const OMPSimdlenClause *Simdlen = nullptr;
9954 
9955   for (const OMPClause *Clause : Clauses) {
9956     if (Clause->getClauseKind() == OMPC_safelen)
9957       Safelen = cast<OMPSafelenClause>(Clause);
9958     else if (Clause->getClauseKind() == OMPC_simdlen)
9959       Simdlen = cast<OMPSimdlenClause>(Clause);
9960     if (Safelen && Simdlen)
9961       break;
9962   }
9963 
9964   if (Simdlen && Safelen) {
9965     const Expr *SimdlenLength = Simdlen->getSimdlen();
9966     const Expr *SafelenLength = Safelen->getSafelen();
9967     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9968         SimdlenLength->isInstantiationDependent() ||
9969         SimdlenLength->containsUnexpandedParameterPack())
9970       return false;
9971     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9972         SafelenLength->isInstantiationDependent() ||
9973         SafelenLength->containsUnexpandedParameterPack())
9974       return false;
9975     Expr::EvalResult SimdlenResult, SafelenResult;
9976     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9977     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9978     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9979     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9980     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9981     // If both simdlen and safelen clauses are specified, the value of the
9982     // simdlen parameter must be less than or equal to the value of the safelen
9983     // parameter.
9984     if (SimdlenRes > SafelenRes) {
9985       S.Diag(SimdlenLength->getExprLoc(),
9986              diag::err_omp_wrong_simdlen_safelen_values)
9987           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9988       return true;
9989     }
9990   }
9991   return false;
9992 }
9993 
9994 StmtResult
9995 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9996                                SourceLocation StartLoc, SourceLocation EndLoc,
9997                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9998   if (!AStmt)
9999     return StmtError();
10000 
10001   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10002   OMPLoopBasedDirective::HelperExprs B;
10003   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10004   // define the nested loops number.
10005   unsigned NestedLoopCount = checkOpenMPLoop(
10006       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10007       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10008   if (NestedLoopCount == 0)
10009     return StmtError();
10010 
10011   assert((CurContext->isDependentContext() || B.builtAll()) &&
10012          "omp simd loop exprs were not built");
10013 
10014   if (!CurContext->isDependentContext()) {
10015     // Finalize the clauses that need pre-built expressions for CodeGen.
10016     for (OMPClause *C : Clauses) {
10017       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10018         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10019                                      B.NumIterations, *this, CurScope,
10020                                      DSAStack))
10021           return StmtError();
10022     }
10023   }
10024 
10025   if (checkSimdlenSafelenSpecified(*this, Clauses))
10026     return StmtError();
10027 
10028   setFunctionHasBranchProtectedScope();
10029   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
10030                                   Clauses, AStmt, B);
10031 }
10032 
10033 StmtResult
10034 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10035                               SourceLocation StartLoc, SourceLocation EndLoc,
10036                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10037   if (!AStmt)
10038     return StmtError();
10039 
10040   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10041   OMPLoopBasedDirective::HelperExprs B;
10042   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10043   // define the nested loops number.
10044   unsigned NestedLoopCount = checkOpenMPLoop(
10045       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10046       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10047   if (NestedLoopCount == 0)
10048     return StmtError();
10049 
10050   assert((CurContext->isDependentContext() || B.builtAll()) &&
10051          "omp for loop exprs were not built");
10052 
10053   if (!CurContext->isDependentContext()) {
10054     // Finalize the clauses that need pre-built expressions for CodeGen.
10055     for (OMPClause *C : Clauses) {
10056       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10057         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10058                                      B.NumIterations, *this, CurScope,
10059                                      DSAStack))
10060           return StmtError();
10061     }
10062   }
10063 
10064   setFunctionHasBranchProtectedScope();
10065   return OMPForDirective::Create(
10066       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10067       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10068 }
10069 
10070 StmtResult Sema::ActOnOpenMPForSimdDirective(
10071     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10072     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10073   if (!AStmt)
10074     return StmtError();
10075 
10076   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10077   OMPLoopBasedDirective::HelperExprs B;
10078   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10079   // define the nested loops number.
10080   unsigned NestedLoopCount =
10081       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
10082                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10083                       VarsWithImplicitDSA, B);
10084   if (NestedLoopCount == 0)
10085     return StmtError();
10086 
10087   assert((CurContext->isDependentContext() || B.builtAll()) &&
10088          "omp for simd loop exprs were not built");
10089 
10090   if (!CurContext->isDependentContext()) {
10091     // Finalize the clauses that need pre-built expressions for CodeGen.
10092     for (OMPClause *C : Clauses) {
10093       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10094         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10095                                      B.NumIterations, *this, CurScope,
10096                                      DSAStack))
10097           return StmtError();
10098     }
10099   }
10100 
10101   if (checkSimdlenSafelenSpecified(*this, Clauses))
10102     return StmtError();
10103 
10104   setFunctionHasBranchProtectedScope();
10105   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
10106                                      Clauses, AStmt, B);
10107 }
10108 
10109 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10110                                               Stmt *AStmt,
10111                                               SourceLocation StartLoc,
10112                                               SourceLocation EndLoc) {
10113   if (!AStmt)
10114     return StmtError();
10115 
10116   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10117   auto BaseStmt = AStmt;
10118   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10119     BaseStmt = CS->getCapturedStmt();
10120   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10121     auto S = C->children();
10122     if (S.begin() == S.end())
10123       return StmtError();
10124     // All associated statements must be '#pragma omp section' except for
10125     // the first one.
10126     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10127       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10128         if (SectionStmt)
10129           Diag(SectionStmt->getBeginLoc(),
10130                diag::err_omp_sections_substmt_not_section);
10131         return StmtError();
10132       }
10133       cast<OMPSectionDirective>(SectionStmt)
10134           ->setHasCancel(DSAStack->isCancelRegion());
10135     }
10136   } else {
10137     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
10138     return StmtError();
10139   }
10140 
10141   setFunctionHasBranchProtectedScope();
10142 
10143   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10144                                       DSAStack->getTaskgroupReductionRef(),
10145                                       DSAStack->isCancelRegion());
10146 }
10147 
10148 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
10149                                              SourceLocation StartLoc,
10150                                              SourceLocation EndLoc) {
10151   if (!AStmt)
10152     return StmtError();
10153 
10154   setFunctionHasBranchProtectedScope();
10155   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
10156 
10157   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
10158                                      DSAStack->isCancelRegion());
10159 }
10160 
10161 static Expr *getDirectCallExpr(Expr *E) {
10162   E = E->IgnoreParenCasts()->IgnoreImplicit();
10163   if (auto *CE = dyn_cast<CallExpr>(E))
10164     if (CE->getDirectCallee())
10165       return E;
10166   return nullptr;
10167 }
10168 
10169 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10170                                               Stmt *AStmt,
10171                                               SourceLocation StartLoc,
10172                                               SourceLocation EndLoc) {
10173   if (!AStmt)
10174     return StmtError();
10175 
10176   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
10177 
10178   // 5.1 OpenMP
10179   // expression-stmt : an expression statement with one of the following forms:
10180   //   expression = target-call ( [expression-list] );
10181   //   target-call ( [expression-list] );
10182 
10183   SourceLocation TargetCallLoc;
10184 
10185   if (!CurContext->isDependentContext()) {
10186     Expr *TargetCall = nullptr;
10187 
10188     auto *E = dyn_cast<Expr>(S);
10189     if (!E) {
10190       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10191       return StmtError();
10192     }
10193 
10194     E = E->IgnoreParenCasts()->IgnoreImplicit();
10195 
10196     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
10197       if (BO->getOpcode() == BO_Assign)
10198         TargetCall = getDirectCallExpr(BO->getRHS());
10199     } else {
10200       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
10201         if (COCE->getOperator() == OO_Equal)
10202           TargetCall = getDirectCallExpr(COCE->getArg(1));
10203       if (!TargetCall)
10204         TargetCall = getDirectCallExpr(E);
10205     }
10206     if (!TargetCall) {
10207       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10208       return StmtError();
10209     }
10210     TargetCallLoc = TargetCall->getExprLoc();
10211   }
10212 
10213   setFunctionHasBranchProtectedScope();
10214 
10215   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10216                                       TargetCallLoc);
10217 }
10218 
10219 static bool checkGenericLoopLastprivate(Sema &S, ArrayRef<OMPClause *> Clauses,
10220                                         OpenMPDirectiveKind K,
10221                                         DSAStackTy *Stack) {
10222   bool ErrorFound = false;
10223   for (OMPClause *C : Clauses) {
10224     if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
10225       for (Expr *RefExpr : LPC->varlists()) {
10226         SourceLocation ELoc;
10227         SourceRange ERange;
10228         Expr *SimpleRefExpr = RefExpr;
10229         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
10230         if (ValueDecl *D = Res.first) {
10231           auto &&Info = Stack->isLoopControlVariable(D);
10232           if (!Info.first) {
10233             S.Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration)
10234                 << getOpenMPDirectiveName(K);
10235             ErrorFound = true;
10236           }
10237         }
10238       }
10239     }
10240   }
10241   return ErrorFound;
10242 }
10243 
10244 StmtResult Sema::ActOnOpenMPGenericLoopDirective(
10245     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10246     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10247   if (!AStmt)
10248     return StmtError();
10249 
10250   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10251   // A list item may not appear in a lastprivate clause unless it is the
10252   // loop iteration variable of a loop that is associated with the construct.
10253   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_loop, DSAStack))
10254     return StmtError();
10255 
10256   auto *CS = cast<CapturedStmt>(AStmt);
10257   // 1.2.2 OpenMP Language Terminology
10258   // Structured block - An executable statement with a single entry at the
10259   // top and a single exit at the bottom.
10260   // The point of exit cannot be a branch out of the structured block.
10261   // longjmp() and throw() must not violate the entry/exit criteria.
10262   CS->getCapturedDecl()->setNothrow();
10263 
10264   OMPLoopDirective::HelperExprs B;
10265   // In presence of clause 'collapse', it will define the nested loops number.
10266   unsigned NestedLoopCount = checkOpenMPLoop(
10267       OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10268       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10269   if (NestedLoopCount == 0)
10270     return StmtError();
10271 
10272   assert((CurContext->isDependentContext() || B.builtAll()) &&
10273          "omp loop exprs were not built");
10274 
10275   setFunctionHasBranchProtectedScope();
10276   return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
10277                                          NestedLoopCount, Clauses, AStmt, B);
10278 }
10279 
10280 StmtResult Sema::ActOnOpenMPTeamsGenericLoopDirective(
10281     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10282     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10283   if (!AStmt)
10284     return StmtError();
10285 
10286   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10287   // A list item may not appear in a lastprivate clause unless it is the
10288   // loop iteration variable of a loop that is associated with the construct.
10289   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_teams_loop, DSAStack))
10290     return StmtError();
10291 
10292   auto *CS = cast<CapturedStmt>(AStmt);
10293   // 1.2.2 OpenMP Language Terminology
10294   // Structured block - An executable statement with a single entry at the
10295   // top and a single exit at the bottom.
10296   // The point of exit cannot be a branch out of the structured block.
10297   // longjmp() and throw() must not violate the entry/exit criteria.
10298   CS->getCapturedDecl()->setNothrow();
10299   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_loop);
10300        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10301     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10302     // 1.2.2 OpenMP Language Terminology
10303     // Structured block - An executable statement with a single entry at the
10304     // top and a single exit at the bottom.
10305     // The point of exit cannot be a branch out of the structured block.
10306     // longjmp() and throw() must not violate the entry/exit criteria.
10307     CS->getCapturedDecl()->setNothrow();
10308   }
10309 
10310   OMPLoopDirective::HelperExprs B;
10311   // In presence of clause 'collapse', it will define the nested loops number.
10312   unsigned NestedLoopCount =
10313       checkOpenMPLoop(OMPD_teams_loop, getCollapseNumberExpr(Clauses),
10314                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10315                       VarsWithImplicitDSA, B);
10316   if (NestedLoopCount == 0)
10317     return StmtError();
10318 
10319   assert((CurContext->isDependentContext() || B.builtAll()) &&
10320          "omp loop exprs were not built");
10321 
10322   setFunctionHasBranchProtectedScope();
10323   DSAStack->setParentTeamsRegionLoc(StartLoc);
10324 
10325   return OMPTeamsGenericLoopDirective::Create(
10326       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10327 }
10328 
10329 StmtResult Sema::ActOnOpenMPTargetTeamsGenericLoopDirective(
10330     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10331     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10332   if (!AStmt)
10333     return StmtError();
10334 
10335   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10336   // A list item may not appear in a lastprivate clause unless it is the
10337   // loop iteration variable of a loop that is associated with the construct.
10338   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_teams_loop,
10339                                   DSAStack))
10340     return StmtError();
10341 
10342   auto *CS = cast<CapturedStmt>(AStmt);
10343   // 1.2.2 OpenMP Language Terminology
10344   // Structured block - An executable statement with a single entry at the
10345   // top and a single exit at the bottom.
10346   // The point of exit cannot be a branch out of the structured block.
10347   // longjmp() and throw() must not violate the entry/exit criteria.
10348   CS->getCapturedDecl()->setNothrow();
10349   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams_loop);
10350        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10351     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10352     // 1.2.2 OpenMP Language Terminology
10353     // Structured block - An executable statement with a single entry at the
10354     // top and a single exit at the bottom.
10355     // The point of exit cannot be a branch out of the structured block.
10356     // longjmp() and throw() must not violate the entry/exit criteria.
10357     CS->getCapturedDecl()->setNothrow();
10358   }
10359 
10360   OMPLoopDirective::HelperExprs B;
10361   // In presence of clause 'collapse', it will define the nested loops number.
10362   unsigned NestedLoopCount =
10363       checkOpenMPLoop(OMPD_target_teams_loop, getCollapseNumberExpr(Clauses),
10364                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10365                       VarsWithImplicitDSA, B);
10366   if (NestedLoopCount == 0)
10367     return StmtError();
10368 
10369   assert((CurContext->isDependentContext() || B.builtAll()) &&
10370          "omp loop exprs were not built");
10371 
10372   setFunctionHasBranchProtectedScope();
10373 
10374   return OMPTargetTeamsGenericLoopDirective::Create(
10375       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10376 }
10377 
10378 StmtResult Sema::ActOnOpenMPParallelGenericLoopDirective(
10379     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10380     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10381   if (!AStmt)
10382     return StmtError();
10383 
10384   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10385   // A list item may not appear in a lastprivate clause unless it is the
10386   // loop iteration variable of a loop that is associated with the construct.
10387   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_parallel_loop, DSAStack))
10388     return StmtError();
10389 
10390   auto *CS = cast<CapturedStmt>(AStmt);
10391   // 1.2.2 OpenMP Language Terminology
10392   // Structured block - An executable statement with a single entry at the
10393   // top and a single exit at the bottom.
10394   // The point of exit cannot be a branch out of the structured block.
10395   // longjmp() and throw() must not violate the entry/exit criteria.
10396   CS->getCapturedDecl()->setNothrow();
10397   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_parallel_loop);
10398        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10399     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10400     // 1.2.2 OpenMP Language Terminology
10401     // Structured block - An executable statement with a single entry at the
10402     // top and a single exit at the bottom.
10403     // The point of exit cannot be a branch out of the structured block.
10404     // longjmp() and throw() must not violate the entry/exit criteria.
10405     CS->getCapturedDecl()->setNothrow();
10406   }
10407 
10408   OMPLoopDirective::HelperExprs B;
10409   // In presence of clause 'collapse', it will define the nested loops number.
10410   unsigned NestedLoopCount =
10411       checkOpenMPLoop(OMPD_parallel_loop, getCollapseNumberExpr(Clauses),
10412                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10413                       VarsWithImplicitDSA, B);
10414   if (NestedLoopCount == 0)
10415     return StmtError();
10416 
10417   assert((CurContext->isDependentContext() || B.builtAll()) &&
10418          "omp loop exprs were not built");
10419 
10420   setFunctionHasBranchProtectedScope();
10421 
10422   return OMPParallelGenericLoopDirective::Create(
10423       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10424 }
10425 
10426 StmtResult Sema::ActOnOpenMPTargetParallelGenericLoopDirective(
10427     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10428     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10429   if (!AStmt)
10430     return StmtError();
10431 
10432   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
10433   // A list item may not appear in a lastprivate clause unless it is the
10434   // loop iteration variable of a loop that is associated with the construct.
10435   if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_parallel_loop,
10436                                   DSAStack))
10437     return StmtError();
10438 
10439   auto *CS = cast<CapturedStmt>(AStmt);
10440   // 1.2.2 OpenMP Language Terminology
10441   // Structured block - An executable statement with a single entry at the
10442   // top and a single exit at the bottom.
10443   // The point of exit cannot be a branch out of the structured block.
10444   // longjmp() and throw() must not violate the entry/exit criteria.
10445   CS->getCapturedDecl()->setNothrow();
10446   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_loop);
10447        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10448     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10449     // 1.2.2 OpenMP Language Terminology
10450     // Structured block - An executable statement with a single entry at the
10451     // top and a single exit at the bottom.
10452     // The point of exit cannot be a branch out of the structured block.
10453     // longjmp() and throw() must not violate the entry/exit criteria.
10454     CS->getCapturedDecl()->setNothrow();
10455   }
10456 
10457   OMPLoopDirective::HelperExprs B;
10458   // In presence of clause 'collapse', it will define the nested loops number.
10459   unsigned NestedLoopCount =
10460       checkOpenMPLoop(OMPD_target_parallel_loop, getCollapseNumberExpr(Clauses),
10461                       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10462                       VarsWithImplicitDSA, B);
10463   if (NestedLoopCount == 0)
10464     return StmtError();
10465 
10466   assert((CurContext->isDependentContext() || B.builtAll()) &&
10467          "omp loop exprs were not built");
10468 
10469   setFunctionHasBranchProtectedScope();
10470 
10471   return OMPTargetParallelGenericLoopDirective::Create(
10472       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10473 }
10474 
10475 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10476                                             Stmt *AStmt,
10477                                             SourceLocation StartLoc,
10478                                             SourceLocation EndLoc) {
10479   if (!AStmt)
10480     return StmtError();
10481 
10482   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10483 
10484   setFunctionHasBranchProtectedScope();
10485 
10486   // OpenMP [2.7.3, single Construct, Restrictions]
10487   // The copyprivate clause must not be used with the nowait clause.
10488   const OMPClause *Nowait = nullptr;
10489   const OMPClause *Copyprivate = nullptr;
10490   for (const OMPClause *Clause : Clauses) {
10491     if (Clause->getClauseKind() == OMPC_nowait)
10492       Nowait = Clause;
10493     else if (Clause->getClauseKind() == OMPC_copyprivate)
10494       Copyprivate = Clause;
10495     if (Copyprivate && Nowait) {
10496       Diag(Copyprivate->getBeginLoc(),
10497            diag::err_omp_single_copyprivate_with_nowait);
10498       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
10499       return StmtError();
10500     }
10501   }
10502 
10503   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10504 }
10505 
10506 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
10507                                             SourceLocation StartLoc,
10508                                             SourceLocation EndLoc) {
10509   if (!AStmt)
10510     return StmtError();
10511 
10512   setFunctionHasBranchProtectedScope();
10513 
10514   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
10515 }
10516 
10517 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10518                                             Stmt *AStmt,
10519                                             SourceLocation StartLoc,
10520                                             SourceLocation EndLoc) {
10521   if (!AStmt)
10522     return StmtError();
10523 
10524   setFunctionHasBranchProtectedScope();
10525 
10526   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10527 }
10528 
10529 StmtResult Sema::ActOnOpenMPCriticalDirective(
10530     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
10531     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
10532   if (!AStmt)
10533     return StmtError();
10534 
10535   bool ErrorFound = false;
10536   llvm::APSInt Hint;
10537   SourceLocation HintLoc;
10538   bool DependentHint = false;
10539   for (const OMPClause *C : Clauses) {
10540     if (C->getClauseKind() == OMPC_hint) {
10541       if (!DirName.getName()) {
10542         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
10543         ErrorFound = true;
10544       }
10545       Expr *E = cast<OMPHintClause>(C)->getHint();
10546       if (E->isTypeDependent() || E->isValueDependent() ||
10547           E->isInstantiationDependent()) {
10548         DependentHint = true;
10549       } else {
10550         Hint = E->EvaluateKnownConstInt(Context);
10551         HintLoc = C->getBeginLoc();
10552       }
10553     }
10554   }
10555   if (ErrorFound)
10556     return StmtError();
10557   const auto Pair = DSAStack->getCriticalWithHint(DirName);
10558   if (Pair.first && DirName.getName() && !DependentHint) {
10559     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
10560       Diag(StartLoc, diag::err_omp_critical_with_hint);
10561       if (HintLoc.isValid())
10562         Diag(HintLoc, diag::note_omp_critical_hint_here)
10563             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
10564       else
10565         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10566       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10567         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10568             << 1
10569             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10570                         /*Radix=*/10, /*Signed=*/false);
10571       } else {
10572         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10573       }
10574     }
10575   }
10576 
10577   setFunctionHasBranchProtectedScope();
10578 
10579   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10580                                            Clauses, AStmt);
10581   if (!Pair.first && DirName.getName() && !DependentHint)
10582     DSAStack->addCriticalWithHint(Dir, Hint);
10583   return Dir;
10584 }
10585 
10586 StmtResult Sema::ActOnOpenMPParallelForDirective(
10587     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10588     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10589   if (!AStmt)
10590     return StmtError();
10591 
10592   auto *CS = cast<CapturedStmt>(AStmt);
10593   // 1.2.2 OpenMP Language Terminology
10594   // Structured block - An executable statement with a single entry at the
10595   // top and a single exit at the bottom.
10596   // The point of exit cannot be a branch out of the structured block.
10597   // longjmp() and throw() must not violate the entry/exit criteria.
10598   CS->getCapturedDecl()->setNothrow();
10599 
10600   OMPLoopBasedDirective::HelperExprs B;
10601   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10602   // define the nested loops number.
10603   unsigned NestedLoopCount =
10604       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10605                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10606                       VarsWithImplicitDSA, B);
10607   if (NestedLoopCount == 0)
10608     return StmtError();
10609 
10610   assert((CurContext->isDependentContext() || B.builtAll()) &&
10611          "omp parallel for loop exprs were not built");
10612 
10613   if (!CurContext->isDependentContext()) {
10614     // Finalize the clauses that need pre-built expressions for CodeGen.
10615     for (OMPClause *C : Clauses) {
10616       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10617         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10618                                      B.NumIterations, *this, CurScope,
10619                                      DSAStack))
10620           return StmtError();
10621     }
10622   }
10623 
10624   setFunctionHasBranchProtectedScope();
10625   return OMPParallelForDirective::Create(
10626       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10627       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10628 }
10629 
10630 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10631     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10632     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10633   if (!AStmt)
10634     return StmtError();
10635 
10636   auto *CS = cast<CapturedStmt>(AStmt);
10637   // 1.2.2 OpenMP Language Terminology
10638   // Structured block - An executable statement with a single entry at the
10639   // top and a single exit at the bottom.
10640   // The point of exit cannot be a branch out of the structured block.
10641   // longjmp() and throw() must not violate the entry/exit criteria.
10642   CS->getCapturedDecl()->setNothrow();
10643 
10644   OMPLoopBasedDirective::HelperExprs B;
10645   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10646   // define the nested loops number.
10647   unsigned NestedLoopCount =
10648       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10649                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10650                       VarsWithImplicitDSA, B);
10651   if (NestedLoopCount == 0)
10652     return StmtError();
10653 
10654   if (!CurContext->isDependentContext()) {
10655     // Finalize the clauses that need pre-built expressions for CodeGen.
10656     for (OMPClause *C : Clauses) {
10657       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10658         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10659                                      B.NumIterations, *this, CurScope,
10660                                      DSAStack))
10661           return StmtError();
10662     }
10663   }
10664 
10665   if (checkSimdlenSafelenSpecified(*this, Clauses))
10666     return StmtError();
10667 
10668   setFunctionHasBranchProtectedScope();
10669   return OMPParallelForSimdDirective::Create(
10670       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10671 }
10672 
10673 StmtResult
10674 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10675                                          Stmt *AStmt, SourceLocation StartLoc,
10676                                          SourceLocation EndLoc) {
10677   if (!AStmt)
10678     return StmtError();
10679 
10680   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10681   auto *CS = cast<CapturedStmt>(AStmt);
10682   // 1.2.2 OpenMP Language Terminology
10683   // Structured block - An executable statement with a single entry at the
10684   // top and a single exit at the bottom.
10685   // The point of exit cannot be a branch out of the structured block.
10686   // longjmp() and throw() must not violate the entry/exit criteria.
10687   CS->getCapturedDecl()->setNothrow();
10688 
10689   setFunctionHasBranchProtectedScope();
10690 
10691   return OMPParallelMasterDirective::Create(
10692       Context, StartLoc, EndLoc, Clauses, AStmt,
10693       DSAStack->getTaskgroupReductionRef());
10694 }
10695 
10696 StmtResult
10697 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10698                                            Stmt *AStmt, SourceLocation StartLoc,
10699                                            SourceLocation EndLoc) {
10700   if (!AStmt)
10701     return StmtError();
10702 
10703   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10704   auto BaseStmt = AStmt;
10705   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10706     BaseStmt = CS->getCapturedStmt();
10707   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10708     auto S = C->children();
10709     if (S.begin() == S.end())
10710       return StmtError();
10711     // All associated statements must be '#pragma omp section' except for
10712     // the first one.
10713     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10714       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10715         if (SectionStmt)
10716           Diag(SectionStmt->getBeginLoc(),
10717                diag::err_omp_parallel_sections_substmt_not_section);
10718         return StmtError();
10719       }
10720       cast<OMPSectionDirective>(SectionStmt)
10721           ->setHasCancel(DSAStack->isCancelRegion());
10722     }
10723   } else {
10724     Diag(AStmt->getBeginLoc(),
10725          diag::err_omp_parallel_sections_not_compound_stmt);
10726     return StmtError();
10727   }
10728 
10729   setFunctionHasBranchProtectedScope();
10730 
10731   return OMPParallelSectionsDirective::Create(
10732       Context, StartLoc, EndLoc, Clauses, AStmt,
10733       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10734 }
10735 
10736 /// Find and diagnose mutually exclusive clause kinds.
10737 static bool checkMutuallyExclusiveClauses(
10738     Sema &S, ArrayRef<OMPClause *> Clauses,
10739     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10740   const OMPClause *PrevClause = nullptr;
10741   bool ErrorFound = false;
10742   for (const OMPClause *C : Clauses) {
10743     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10744       if (!PrevClause) {
10745         PrevClause = C;
10746       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10747         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10748             << getOpenMPClauseName(C->getClauseKind())
10749             << getOpenMPClauseName(PrevClause->getClauseKind());
10750         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10751             << getOpenMPClauseName(PrevClause->getClauseKind());
10752         ErrorFound = true;
10753       }
10754     }
10755   }
10756   return ErrorFound;
10757 }
10758 
10759 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10760                                           Stmt *AStmt, SourceLocation StartLoc,
10761                                           SourceLocation EndLoc) {
10762   if (!AStmt)
10763     return StmtError();
10764 
10765   // OpenMP 5.0, 2.10.1 task Construct
10766   // If a detach clause appears on the directive, then a mergeable clause cannot
10767   // appear on the same directive.
10768   if (checkMutuallyExclusiveClauses(*this, Clauses,
10769                                     {OMPC_detach, OMPC_mergeable}))
10770     return StmtError();
10771 
10772   auto *CS = cast<CapturedStmt>(AStmt);
10773   // 1.2.2 OpenMP Language Terminology
10774   // Structured block - An executable statement with a single entry at the
10775   // top and a single exit at the bottom.
10776   // The point of exit cannot be a branch out of the structured block.
10777   // longjmp() and throw() must not violate the entry/exit criteria.
10778   CS->getCapturedDecl()->setNothrow();
10779 
10780   setFunctionHasBranchProtectedScope();
10781 
10782   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10783                                   DSAStack->isCancelRegion());
10784 }
10785 
10786 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10787                                                SourceLocation EndLoc) {
10788   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10789 }
10790 
10791 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10792                                              SourceLocation EndLoc) {
10793   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10794 }
10795 
10796 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10797                                               SourceLocation StartLoc,
10798                                               SourceLocation EndLoc) {
10799   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
10800 }
10801 
10802 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10803                                                Stmt *AStmt,
10804                                                SourceLocation StartLoc,
10805                                                SourceLocation EndLoc) {
10806   if (!AStmt)
10807     return StmtError();
10808 
10809   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10810 
10811   setFunctionHasBranchProtectedScope();
10812 
10813   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10814                                        AStmt,
10815                                        DSAStack->getTaskgroupReductionRef());
10816 }
10817 
10818 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10819                                            SourceLocation StartLoc,
10820                                            SourceLocation EndLoc) {
10821   OMPFlushClause *FC = nullptr;
10822   OMPClause *OrderClause = nullptr;
10823   for (OMPClause *C : Clauses) {
10824     if (C->getClauseKind() == OMPC_flush)
10825       FC = cast<OMPFlushClause>(C);
10826     else
10827       OrderClause = C;
10828   }
10829   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10830   SourceLocation MemOrderLoc;
10831   for (const OMPClause *C : Clauses) {
10832     if (C->getClauseKind() == OMPC_acq_rel ||
10833         C->getClauseKind() == OMPC_acquire ||
10834         C->getClauseKind() == OMPC_release) {
10835       if (MemOrderKind != OMPC_unknown) {
10836         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10837             << getOpenMPDirectiveName(OMPD_flush) << 1
10838             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10839         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10840             << getOpenMPClauseName(MemOrderKind);
10841       } else {
10842         MemOrderKind = C->getClauseKind();
10843         MemOrderLoc = C->getBeginLoc();
10844       }
10845     }
10846   }
10847   if (FC && OrderClause) {
10848     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10849         << getOpenMPClauseName(OrderClause->getClauseKind());
10850     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10851         << getOpenMPClauseName(OrderClause->getClauseKind());
10852     return StmtError();
10853   }
10854   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10855 }
10856 
10857 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10858                                             SourceLocation StartLoc,
10859                                             SourceLocation EndLoc) {
10860   if (Clauses.empty()) {
10861     Diag(StartLoc, diag::err_omp_depobj_expected);
10862     return StmtError();
10863   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10864     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10865     return StmtError();
10866   }
10867   // Only depobj expression and another single clause is allowed.
10868   if (Clauses.size() > 2) {
10869     Diag(Clauses[2]->getBeginLoc(),
10870          diag::err_omp_depobj_single_clause_expected);
10871     return StmtError();
10872   } else if (Clauses.size() < 1) {
10873     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10874     return StmtError();
10875   }
10876   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10877 }
10878 
10879 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10880                                           SourceLocation StartLoc,
10881                                           SourceLocation EndLoc) {
10882   // Check that exactly one clause is specified.
10883   if (Clauses.size() != 1) {
10884     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10885          diag::err_omp_scan_single_clause_expected);
10886     return StmtError();
10887   }
10888   // Check that scan directive is used in the scopeof the OpenMP loop body.
10889   if (Scope *S = DSAStack->getCurScope()) {
10890     Scope *ParentS = S->getParent();
10891     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10892         !ParentS->getBreakParent()->isOpenMPLoopScope())
10893       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10894                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10895   }
10896   // Check that only one instance of scan directives is used in the same outer
10897   // region.
10898   if (DSAStack->doesParentHasScanDirective()) {
10899     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10900     Diag(DSAStack->getParentScanDirectiveLoc(),
10901          diag::note_omp_previous_directive)
10902         << "scan";
10903     return StmtError();
10904   }
10905   DSAStack->setParentHasScanDirective(StartLoc);
10906   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10907 }
10908 
10909 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10910                                              Stmt *AStmt,
10911                                              SourceLocation StartLoc,
10912                                              SourceLocation EndLoc) {
10913   const OMPClause *DependFound = nullptr;
10914   const OMPClause *DependSourceClause = nullptr;
10915   const OMPClause *DependSinkClause = nullptr;
10916   bool ErrorFound = false;
10917   const OMPThreadsClause *TC = nullptr;
10918   const OMPSIMDClause *SC = nullptr;
10919   for (const OMPClause *C : Clauses) {
10920     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10921       DependFound = C;
10922       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10923         if (DependSourceClause) {
10924           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10925               << getOpenMPDirectiveName(OMPD_ordered)
10926               << getOpenMPClauseName(OMPC_depend) << 2;
10927           ErrorFound = true;
10928         } else {
10929           DependSourceClause = C;
10930         }
10931         if (DependSinkClause) {
10932           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10933               << 0;
10934           ErrorFound = true;
10935         }
10936       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10937         if (DependSourceClause) {
10938           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10939               << 1;
10940           ErrorFound = true;
10941         }
10942         DependSinkClause = C;
10943       }
10944     } else if (C->getClauseKind() == OMPC_threads) {
10945       TC = cast<OMPThreadsClause>(C);
10946     } else if (C->getClauseKind() == OMPC_simd) {
10947       SC = cast<OMPSIMDClause>(C);
10948     }
10949   }
10950   if (!ErrorFound && !SC &&
10951       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10952     // OpenMP [2.8.1,simd Construct, Restrictions]
10953     // An ordered construct with the simd clause is the only OpenMP construct
10954     // that can appear in the simd region.
10955     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10956         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10957     ErrorFound = true;
10958   } else if (DependFound && (TC || SC)) {
10959     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10960         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10961     ErrorFound = true;
10962   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10963     Diag(DependFound->getBeginLoc(),
10964          diag::err_omp_ordered_directive_without_param);
10965     ErrorFound = true;
10966   } else if (TC || Clauses.empty()) {
10967     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10968       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10969       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10970           << (TC != nullptr);
10971       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10972       ErrorFound = true;
10973     }
10974   }
10975   if ((!AStmt && !DependFound) || ErrorFound)
10976     return StmtError();
10977 
10978   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10979   // During execution of an iteration of a worksharing-loop or a loop nest
10980   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10981   // must not execute more than one ordered region corresponding to an ordered
10982   // construct without a depend clause.
10983   if (!DependFound) {
10984     if (DSAStack->doesParentHasOrderedDirective()) {
10985       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10986       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10987            diag::note_omp_previous_directive)
10988           << "ordered";
10989       return StmtError();
10990     }
10991     DSAStack->setParentHasOrderedDirective(StartLoc);
10992   }
10993 
10994   if (AStmt) {
10995     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10996 
10997     setFunctionHasBranchProtectedScope();
10998   }
10999 
11000   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11001 }
11002 
11003 namespace {
11004 /// Helper class for checking expression in 'omp atomic [update]'
11005 /// construct.
11006 class OpenMPAtomicUpdateChecker {
11007   /// Error results for atomic update expressions.
11008   enum ExprAnalysisErrorCode {
11009     /// A statement is not an expression statement.
11010     NotAnExpression,
11011     /// Expression is not builtin binary or unary operation.
11012     NotABinaryOrUnaryExpression,
11013     /// Unary operation is not post-/pre- increment/decrement operation.
11014     NotAnUnaryIncDecExpression,
11015     /// An expression is not of scalar type.
11016     NotAScalarType,
11017     /// A binary operation is not an assignment operation.
11018     NotAnAssignmentOp,
11019     /// RHS part of the binary operation is not a binary expression.
11020     NotABinaryExpression,
11021     /// RHS part is not additive/multiplicative/shift/biwise binary
11022     /// expression.
11023     NotABinaryOperator,
11024     /// RHS binary operation does not have reference to the updated LHS
11025     /// part.
11026     NotAnUpdateExpression,
11027     /// No errors is found.
11028     NoError
11029   };
11030   /// Reference to Sema.
11031   Sema &SemaRef;
11032   /// A location for note diagnostics (when error is found).
11033   SourceLocation NoteLoc;
11034   /// 'x' lvalue part of the source atomic expression.
11035   Expr *X;
11036   /// 'expr' rvalue part of the source atomic expression.
11037   Expr *E;
11038   /// Helper expression of the form
11039   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
11040   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
11041   Expr *UpdateExpr;
11042   /// Is 'x' a LHS in a RHS part of full update expression. It is
11043   /// important for non-associative operations.
11044   bool IsXLHSInRHSPart;
11045   BinaryOperatorKind Op;
11046   SourceLocation OpLoc;
11047   /// true if the source expression is a postfix unary operation, false
11048   /// if it is a prefix unary operation.
11049   bool IsPostfixUpdate;
11050 
11051 public:
11052   OpenMPAtomicUpdateChecker(Sema &SemaRef)
11053       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
11054         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
11055   /// Check specified statement that it is suitable for 'atomic update'
11056   /// constructs and extract 'x', 'expr' and Operation from the original
11057   /// expression. If DiagId and NoteId == 0, then only check is performed
11058   /// without error notification.
11059   /// \param DiagId Diagnostic which should be emitted if error is found.
11060   /// \param NoteId Diagnostic note for the main error message.
11061   /// \return true if statement is not an update expression, false otherwise.
11062   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
11063   /// Return the 'x' lvalue part of the source atomic expression.
11064   Expr *getX() const { return X; }
11065   /// Return the 'expr' rvalue part of the source atomic expression.
11066   Expr *getExpr() const { return E; }
11067   /// Return the update expression used in calculation of the updated
11068   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
11069   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
11070   Expr *getUpdateExpr() const { return UpdateExpr; }
11071   /// Return true if 'x' is LHS in RHS part of full update expression,
11072   /// false otherwise.
11073   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
11074 
11075   /// true if the source expression is a postfix unary operation, false
11076   /// if it is a prefix unary operation.
11077   bool isPostfixUpdate() const { return IsPostfixUpdate; }
11078 
11079 private:
11080   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
11081                             unsigned NoteId = 0);
11082 };
11083 
11084 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
11085     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
11086   ExprAnalysisErrorCode ErrorFound = NoError;
11087   SourceLocation ErrorLoc, NoteLoc;
11088   SourceRange ErrorRange, NoteRange;
11089   // Allowed constructs are:
11090   //  x = x binop expr;
11091   //  x = expr binop x;
11092   if (AtomicBinOp->getOpcode() == BO_Assign) {
11093     X = AtomicBinOp->getLHS();
11094     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
11095             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
11096       if (AtomicInnerBinOp->isMultiplicativeOp() ||
11097           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
11098           AtomicInnerBinOp->isBitwiseOp()) {
11099         Op = AtomicInnerBinOp->getOpcode();
11100         OpLoc = AtomicInnerBinOp->getOperatorLoc();
11101         Expr *LHS = AtomicInnerBinOp->getLHS();
11102         Expr *RHS = AtomicInnerBinOp->getRHS();
11103         llvm::FoldingSetNodeID XId, LHSId, RHSId;
11104         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
11105                                           /*Canonical=*/true);
11106         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
11107                                             /*Canonical=*/true);
11108         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
11109                                             /*Canonical=*/true);
11110         if (XId == LHSId) {
11111           E = RHS;
11112           IsXLHSInRHSPart = true;
11113         } else if (XId == RHSId) {
11114           E = LHS;
11115           IsXLHSInRHSPart = false;
11116         } else {
11117           ErrorLoc = AtomicInnerBinOp->getExprLoc();
11118           ErrorRange = AtomicInnerBinOp->getSourceRange();
11119           NoteLoc = X->getExprLoc();
11120           NoteRange = X->getSourceRange();
11121           ErrorFound = NotAnUpdateExpression;
11122         }
11123       } else {
11124         ErrorLoc = AtomicInnerBinOp->getExprLoc();
11125         ErrorRange = AtomicInnerBinOp->getSourceRange();
11126         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
11127         NoteRange = SourceRange(NoteLoc, NoteLoc);
11128         ErrorFound = NotABinaryOperator;
11129       }
11130     } else {
11131       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
11132       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
11133       ErrorFound = NotABinaryExpression;
11134     }
11135   } else {
11136     ErrorLoc = AtomicBinOp->getExprLoc();
11137     ErrorRange = AtomicBinOp->getSourceRange();
11138     NoteLoc = AtomicBinOp->getOperatorLoc();
11139     NoteRange = SourceRange(NoteLoc, NoteLoc);
11140     ErrorFound = NotAnAssignmentOp;
11141   }
11142   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
11143     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
11144     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
11145     return true;
11146   }
11147   if (SemaRef.CurContext->isDependentContext())
11148     E = X = UpdateExpr = nullptr;
11149   return ErrorFound != NoError;
11150 }
11151 
11152 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
11153                                                unsigned NoteId) {
11154   ExprAnalysisErrorCode ErrorFound = NoError;
11155   SourceLocation ErrorLoc, NoteLoc;
11156   SourceRange ErrorRange, NoteRange;
11157   // Allowed constructs are:
11158   //  x++;
11159   //  x--;
11160   //  ++x;
11161   //  --x;
11162   //  x binop= expr;
11163   //  x = x binop expr;
11164   //  x = expr binop x;
11165   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
11166     AtomicBody = AtomicBody->IgnoreParenImpCasts();
11167     if (AtomicBody->getType()->isScalarType() ||
11168         AtomicBody->isInstantiationDependent()) {
11169       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
11170               AtomicBody->IgnoreParenImpCasts())) {
11171         // Check for Compound Assignment Operation
11172         Op = BinaryOperator::getOpForCompoundAssignment(
11173             AtomicCompAssignOp->getOpcode());
11174         OpLoc = AtomicCompAssignOp->getOperatorLoc();
11175         E = AtomicCompAssignOp->getRHS();
11176         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
11177         IsXLHSInRHSPart = true;
11178       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
11179                      AtomicBody->IgnoreParenImpCasts())) {
11180         // Check for Binary Operation
11181         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
11182           return true;
11183       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
11184                      AtomicBody->IgnoreParenImpCasts())) {
11185         // Check for Unary Operation
11186         if (AtomicUnaryOp->isIncrementDecrementOp()) {
11187           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
11188           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
11189           OpLoc = AtomicUnaryOp->getOperatorLoc();
11190           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
11191           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
11192           IsXLHSInRHSPart = true;
11193         } else {
11194           ErrorFound = NotAnUnaryIncDecExpression;
11195           ErrorLoc = AtomicUnaryOp->getExprLoc();
11196           ErrorRange = AtomicUnaryOp->getSourceRange();
11197           NoteLoc = AtomicUnaryOp->getOperatorLoc();
11198           NoteRange = SourceRange(NoteLoc, NoteLoc);
11199         }
11200       } else if (!AtomicBody->isInstantiationDependent()) {
11201         ErrorFound = NotABinaryOrUnaryExpression;
11202         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
11203         NoteRange = ErrorRange = AtomicBody->getSourceRange();
11204       }
11205     } else {
11206       ErrorFound = NotAScalarType;
11207       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
11208       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11209     }
11210   } else {
11211     ErrorFound = NotAnExpression;
11212     NoteLoc = ErrorLoc = S->getBeginLoc();
11213     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11214   }
11215   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
11216     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
11217     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
11218     return true;
11219   }
11220   if (SemaRef.CurContext->isDependentContext())
11221     E = X = UpdateExpr = nullptr;
11222   if (ErrorFound == NoError && E && X) {
11223     // Build an update expression of form 'OpaqueValueExpr(x) binop
11224     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
11225     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
11226     auto *OVEX = new (SemaRef.getASTContext())
11227         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
11228     auto *OVEExpr = new (SemaRef.getASTContext())
11229         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
11230     ExprResult Update =
11231         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
11232                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
11233     if (Update.isInvalid())
11234       return true;
11235     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
11236                                                Sema::AA_Casting);
11237     if (Update.isInvalid())
11238       return true;
11239     UpdateExpr = Update.get();
11240   }
11241   return ErrorFound != NoError;
11242 }
11243 
11244 /// Get the node id of the fixed point of an expression \a S.
11245 llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) {
11246   llvm::FoldingSetNodeID Id;
11247   S->IgnoreParenImpCasts()->Profile(Id, Context, true);
11248   return Id;
11249 }
11250 
11251 /// Check if two expressions are same.
11252 bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS,
11253                             const Expr *RHS) {
11254   return getNodeId(Context, LHS) == getNodeId(Context, RHS);
11255 }
11256 
11257 class OpenMPAtomicCompareChecker {
11258 public:
11259   /// All kinds of errors that can occur in `atomic compare`
11260   enum ErrorTy {
11261     /// Empty compound statement.
11262     NoStmt = 0,
11263     /// More than one statement in a compound statement.
11264     MoreThanOneStmt,
11265     /// Not an assignment binary operator.
11266     NotAnAssignment,
11267     /// Not a conditional operator.
11268     NotCondOp,
11269     /// Wrong false expr. According to the spec, 'x' should be at the false
11270     /// expression of a conditional expression.
11271     WrongFalseExpr,
11272     /// The condition of a conditional expression is not a binary operator.
11273     NotABinaryOp,
11274     /// Invalid binary operator (not <, >, or ==).
11275     InvalidBinaryOp,
11276     /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x).
11277     InvalidComparison,
11278     /// X is not a lvalue.
11279     XNotLValue,
11280     /// Not a scalar.
11281     NotScalar,
11282     /// Not an integer.
11283     NotInteger,
11284     /// 'else' statement is not expected.
11285     UnexpectedElse,
11286     /// Not an equality operator.
11287     NotEQ,
11288     /// Invalid assignment (not v == x).
11289     InvalidAssignment,
11290     /// Not if statement
11291     NotIfStmt,
11292     /// More than two statements in a compund statement.
11293     MoreThanTwoStmts,
11294     /// Not a compound statement.
11295     NotCompoundStmt,
11296     /// No else statement.
11297     NoElse,
11298     /// Not 'if (r)'.
11299     InvalidCondition,
11300     /// No error.
11301     NoError,
11302   };
11303 
11304   struct ErrorInfoTy {
11305     ErrorTy Error;
11306     SourceLocation ErrorLoc;
11307     SourceRange ErrorRange;
11308     SourceLocation NoteLoc;
11309     SourceRange NoteRange;
11310   };
11311 
11312   OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {}
11313 
11314   /// Check if statement \a S is valid for <tt>atomic compare</tt>.
11315   bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11316 
11317   Expr *getX() const { return X; }
11318   Expr *getE() const { return E; }
11319   Expr *getD() const { return D; }
11320   Expr *getCond() const { return C; }
11321   bool isXBinopExpr() const { return IsXBinopExpr; }
11322 
11323 protected:
11324   /// Reference to ASTContext
11325   ASTContext &ContextRef;
11326   /// 'x' lvalue part of the source atomic expression.
11327   Expr *X = nullptr;
11328   /// 'expr' or 'e' rvalue part of the source atomic expression.
11329   Expr *E = nullptr;
11330   /// 'd' rvalue part of the source atomic expression.
11331   Expr *D = nullptr;
11332   /// 'cond' part of the source atomic expression. It is in one of the following
11333   /// forms:
11334   /// expr ordop x
11335   /// x ordop expr
11336   /// x == e
11337   /// e == x
11338   Expr *C = nullptr;
11339   /// True if the cond expr is in the form of 'x ordop expr'.
11340   bool IsXBinopExpr = true;
11341 
11342   /// Check if it is a valid conditional update statement (cond-update-stmt).
11343   bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo);
11344 
11345   /// Check if it is a valid conditional expression statement (cond-expr-stmt).
11346   bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11347 
11348   /// Check if all captured values have right type.
11349   bool checkType(ErrorInfoTy &ErrorInfo) const;
11350 
11351   static bool CheckValue(const Expr *E, ErrorInfoTy &ErrorInfo,
11352                          bool ShouldBeLValue) {
11353     if (ShouldBeLValue && !E->isLValue()) {
11354       ErrorInfo.Error = ErrorTy::XNotLValue;
11355       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11356       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11357       return false;
11358     }
11359 
11360     if (!E->isInstantiationDependent()) {
11361       QualType QTy = E->getType();
11362       if (!QTy->isScalarType()) {
11363         ErrorInfo.Error = ErrorTy::NotScalar;
11364         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11365         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11366         return false;
11367       }
11368 
11369       if (!QTy->isIntegerType()) {
11370         ErrorInfo.Error = ErrorTy::NotInteger;
11371         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11372         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11373         return false;
11374       }
11375     }
11376 
11377     return true;
11378   }
11379 };
11380 
11381 bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S,
11382                                                      ErrorInfoTy &ErrorInfo) {
11383   auto *Then = S->getThen();
11384   if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
11385     if (CS->body_empty()) {
11386       ErrorInfo.Error = ErrorTy::NoStmt;
11387       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11388       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11389       return false;
11390     }
11391     if (CS->size() > 1) {
11392       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11393       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11394       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11395       return false;
11396     }
11397     Then = CS->body_front();
11398   }
11399 
11400   auto *BO = dyn_cast<BinaryOperator>(Then);
11401   if (!BO) {
11402     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11403     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
11404     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
11405     return false;
11406   }
11407   if (BO->getOpcode() != BO_Assign) {
11408     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11409     ErrorInfo.ErrorLoc = BO->getExprLoc();
11410     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11411     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11412     return false;
11413   }
11414 
11415   X = BO->getLHS();
11416 
11417   auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
11418   if (!Cond) {
11419     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11420     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
11421     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
11422     return false;
11423   }
11424 
11425   switch (Cond->getOpcode()) {
11426   case BO_EQ: {
11427     C = Cond;
11428     D = BO->getRHS()->IgnoreImpCasts();
11429     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11430       E = Cond->getRHS()->IgnoreImpCasts();
11431     } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11432       E = Cond->getLHS()->IgnoreImpCasts();
11433     } else {
11434       ErrorInfo.Error = ErrorTy::InvalidComparison;
11435       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11436       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11437       return false;
11438     }
11439     break;
11440   }
11441   case BO_LT:
11442   case BO_GT: {
11443     E = BO->getRHS()->IgnoreImpCasts();
11444     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
11445         checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
11446       C = Cond;
11447     } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
11448                checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11449       C = Cond;
11450       IsXBinopExpr = false;
11451     } else {
11452       ErrorInfo.Error = ErrorTy::InvalidComparison;
11453       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11454       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11455       return false;
11456     }
11457     break;
11458   }
11459   default:
11460     ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
11461     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11462     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11463     return false;
11464   }
11465 
11466   if (S->getElse()) {
11467     ErrorInfo.Error = ErrorTy::UnexpectedElse;
11468     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getElse()->getBeginLoc();
11469     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getElse()->getSourceRange();
11470     return false;
11471   }
11472 
11473   return true;
11474 }
11475 
11476 bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S,
11477                                                    ErrorInfoTy &ErrorInfo) {
11478   auto *BO = dyn_cast<BinaryOperator>(S);
11479   if (!BO) {
11480     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11481     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11482     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11483     return false;
11484   }
11485   if (BO->getOpcode() != BO_Assign) {
11486     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11487     ErrorInfo.ErrorLoc = BO->getExprLoc();
11488     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11489     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11490     return false;
11491   }
11492 
11493   X = BO->getLHS();
11494 
11495   auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts());
11496   if (!CO) {
11497     ErrorInfo.Error = ErrorTy::NotCondOp;
11498     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc();
11499     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange();
11500     return false;
11501   }
11502 
11503   if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) {
11504     ErrorInfo.Error = ErrorTy::WrongFalseExpr;
11505     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc();
11506     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11507         CO->getFalseExpr()->getSourceRange();
11508     return false;
11509   }
11510 
11511   auto *Cond = dyn_cast<BinaryOperator>(CO->getCond());
11512   if (!Cond) {
11513     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11514     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
11515     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11516         CO->getCond()->getSourceRange();
11517     return false;
11518   }
11519 
11520   switch (Cond->getOpcode()) {
11521   case BO_EQ: {
11522     C = Cond;
11523     D = CO->getTrueExpr()->IgnoreImpCasts();
11524     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11525       E = Cond->getRHS()->IgnoreImpCasts();
11526     } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11527       E = Cond->getLHS()->IgnoreImpCasts();
11528     } else {
11529       ErrorInfo.Error = ErrorTy::InvalidComparison;
11530       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11531       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11532       return false;
11533     }
11534     break;
11535   }
11536   case BO_LT:
11537   case BO_GT: {
11538     E = CO->getTrueExpr()->IgnoreImpCasts();
11539     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
11540         checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
11541       C = Cond;
11542     } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
11543                checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11544       C = Cond;
11545       IsXBinopExpr = false;
11546     } else {
11547       ErrorInfo.Error = ErrorTy::InvalidComparison;
11548       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11549       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11550       return false;
11551     }
11552     break;
11553   }
11554   default:
11555     ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
11556     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11557     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11558     return false;
11559   }
11560 
11561   return true;
11562 }
11563 
11564 bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const {
11565   // 'x' and 'e' cannot be nullptr
11566   assert(X && E && "X and E cannot be nullptr");
11567 
11568   if (!CheckValue(X, ErrorInfo, true))
11569     return false;
11570 
11571   if (!CheckValue(E, ErrorInfo, false))
11572     return false;
11573 
11574   if (D && !CheckValue(D, ErrorInfo, false))
11575     return false;
11576 
11577   return true;
11578 }
11579 
11580 bool OpenMPAtomicCompareChecker::checkStmt(
11581     Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) {
11582   auto *CS = dyn_cast<CompoundStmt>(S);
11583   if (CS) {
11584     if (CS->body_empty()) {
11585       ErrorInfo.Error = ErrorTy::NoStmt;
11586       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11587       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11588       return false;
11589     }
11590 
11591     if (CS->size() != 1) {
11592       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11593       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11594       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11595       return false;
11596     }
11597     S = CS->body_front();
11598   }
11599 
11600   auto Res = false;
11601 
11602   if (auto *IS = dyn_cast<IfStmt>(S)) {
11603     // Check if the statement is in one of the following forms
11604     // (cond-update-stmt):
11605     // if (expr ordop x) { x = expr; }
11606     // if (x ordop expr) { x = expr; }
11607     // if (x == e) { x = d; }
11608     Res = checkCondUpdateStmt(IS, ErrorInfo);
11609   } else {
11610     // Check if the statement is in one of the following forms (cond-expr-stmt):
11611     // x = expr ordop x ? expr : x;
11612     // x = x ordop expr ? expr : x;
11613     // x = x == e ? d : x;
11614     Res = checkCondExprStmt(S, ErrorInfo);
11615   }
11616 
11617   if (!Res)
11618     return false;
11619 
11620   return checkType(ErrorInfo);
11621 }
11622 
11623 class OpenMPAtomicCompareCaptureChecker final
11624     : public OpenMPAtomicCompareChecker {
11625 public:
11626   OpenMPAtomicCompareCaptureChecker(Sema &S) : OpenMPAtomicCompareChecker(S) {}
11627 
11628   Expr *getV() const { return V; }
11629   Expr *getR() const { return R; }
11630   bool isFailOnly() const { return IsFailOnly; }
11631 
11632   /// Check if statement \a S is valid for <tt>atomic compare capture</tt>.
11633   bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11634 
11635 private:
11636   bool checkType(ErrorInfoTy &ErrorInfo);
11637 
11638   // NOTE: Form 3, 4, 5 in the following comments mean the 3rd, 4th, and 5th
11639   // form of 'conditional-update-capture-atomic' structured block on the v5.2
11640   // spec p.p. 82:
11641   // (1) { v = x; cond-update-stmt }
11642   // (2) { cond-update-stmt v = x; }
11643   // (3) if(x == e) { x = d; } else { v = x; }
11644   // (4) { r = x == e; if(r) { x = d; } }
11645   // (5) { r = x == e; if(r) { x = d; } else { v = x; } }
11646 
11647   /// Check if it is valid 'if(x == e) { x = d; } else { v = x; }' (form 3)
11648   bool checkForm3(IfStmt *S, ErrorInfoTy &ErrorInfo);
11649 
11650   /// Check if it is valid '{ r = x == e; if(r) { x = d; } }',
11651   /// or '{ r = x == e; if(r) { x = d; } else { v = x; } }' (form 4 and 5)
11652   bool checkForm45(Stmt *S, ErrorInfoTy &ErrorInfo);
11653 
11654   /// 'v' lvalue part of the source atomic expression.
11655   Expr *V = nullptr;
11656   /// 'r' lvalue part of the source atomic expression.
11657   Expr *R = nullptr;
11658   /// If 'v' is only updated when the comparison fails.
11659   bool IsFailOnly = false;
11660 };
11661 
11662 bool OpenMPAtomicCompareCaptureChecker::checkType(ErrorInfoTy &ErrorInfo) {
11663   if (!OpenMPAtomicCompareChecker::checkType(ErrorInfo))
11664     return false;
11665 
11666   if (V && !CheckValue(V, ErrorInfo, true))
11667     return false;
11668 
11669   if (R && !CheckValue(R, ErrorInfo, true))
11670     return false;
11671 
11672   return true;
11673 }
11674 
11675 bool OpenMPAtomicCompareCaptureChecker::checkForm3(IfStmt *S,
11676                                                    ErrorInfoTy &ErrorInfo) {
11677   IsFailOnly = true;
11678 
11679   auto *Then = S->getThen();
11680   if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
11681     if (CS->body_empty()) {
11682       ErrorInfo.Error = ErrorTy::NoStmt;
11683       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11684       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11685       return false;
11686     }
11687     if (CS->size() > 1) {
11688       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11689       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11690       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11691       return false;
11692     }
11693     Then = CS->body_front();
11694   }
11695 
11696   auto *BO = dyn_cast<BinaryOperator>(Then);
11697   if (!BO) {
11698     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11699     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
11700     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
11701     return false;
11702   }
11703   if (BO->getOpcode() != BO_Assign) {
11704     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11705     ErrorInfo.ErrorLoc = BO->getExprLoc();
11706     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11707     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11708     return false;
11709   }
11710 
11711   X = BO->getLHS();
11712   D = BO->getRHS();
11713 
11714   auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
11715   if (!Cond) {
11716     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11717     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
11718     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
11719     return false;
11720   }
11721   if (Cond->getOpcode() != BO_EQ) {
11722     ErrorInfo.Error = ErrorTy::NotEQ;
11723     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11724     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11725     return false;
11726   }
11727 
11728   if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11729     E = Cond->getRHS();
11730   } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11731     E = Cond->getLHS();
11732   } else {
11733     ErrorInfo.Error = ErrorTy::InvalidComparison;
11734     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11735     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11736     return false;
11737   }
11738 
11739   C = Cond;
11740 
11741   if (!S->getElse()) {
11742     ErrorInfo.Error = ErrorTy::NoElse;
11743     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11744     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11745     return false;
11746   }
11747 
11748   auto *Else = S->getElse();
11749   if (auto *CS = dyn_cast<CompoundStmt>(Else)) {
11750     if (CS->body_empty()) {
11751       ErrorInfo.Error = ErrorTy::NoStmt;
11752       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11753       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11754       return false;
11755     }
11756     if (CS->size() > 1) {
11757       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11758       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11759       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11760       return false;
11761     }
11762     Else = CS->body_front();
11763   }
11764 
11765   auto *ElseBO = dyn_cast<BinaryOperator>(Else);
11766   if (!ElseBO) {
11767     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11768     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
11769     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
11770     return false;
11771   }
11772   if (ElseBO->getOpcode() != BO_Assign) {
11773     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11774     ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
11775     ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
11776     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
11777     return false;
11778   }
11779 
11780   if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
11781     ErrorInfo.Error = ErrorTy::InvalidAssignment;
11782     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseBO->getRHS()->getExprLoc();
11783     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11784         ElseBO->getRHS()->getSourceRange();
11785     return false;
11786   }
11787 
11788   V = ElseBO->getLHS();
11789 
11790   return checkType(ErrorInfo);
11791 }
11792 
11793 bool OpenMPAtomicCompareCaptureChecker::checkForm45(Stmt *S,
11794                                                     ErrorInfoTy &ErrorInfo) {
11795   // We don't check here as they should be already done before call this
11796   // function.
11797   auto *CS = cast<CompoundStmt>(S);
11798   assert(CS->size() == 2 && "CompoundStmt size is not expected");
11799   auto *S1 = cast<BinaryOperator>(CS->body_front());
11800   auto *S2 = cast<IfStmt>(CS->body_back());
11801   assert(S1->getOpcode() == BO_Assign && "unexpected binary operator");
11802 
11803   if (!checkIfTwoExprsAreSame(ContextRef, S1->getLHS(), S2->getCond())) {
11804     ErrorInfo.Error = ErrorTy::InvalidCondition;
11805     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getCond()->getExprLoc();
11806     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S1->getLHS()->getSourceRange();
11807     return false;
11808   }
11809 
11810   R = S1->getLHS();
11811 
11812   auto *Then = S2->getThen();
11813   if (auto *ThenCS = dyn_cast<CompoundStmt>(Then)) {
11814     if (ThenCS->body_empty()) {
11815       ErrorInfo.Error = ErrorTy::NoStmt;
11816       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
11817       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
11818       return false;
11819     }
11820     if (ThenCS->size() > 1) {
11821       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11822       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
11823       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
11824       return false;
11825     }
11826     Then = ThenCS->body_front();
11827   }
11828 
11829   auto *ThenBO = dyn_cast<BinaryOperator>(Then);
11830   if (!ThenBO) {
11831     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11832     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getBeginLoc();
11833     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S2->getSourceRange();
11834     return false;
11835   }
11836   if (ThenBO->getOpcode() != BO_Assign) {
11837     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11838     ErrorInfo.ErrorLoc = ThenBO->getExprLoc();
11839     ErrorInfo.NoteLoc = ThenBO->getOperatorLoc();
11840     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenBO->getSourceRange();
11841     return false;
11842   }
11843 
11844   X = ThenBO->getLHS();
11845   D = ThenBO->getRHS();
11846 
11847   auto *BO = cast<BinaryOperator>(S1->getRHS()->IgnoreImpCasts());
11848   if (BO->getOpcode() != BO_EQ) {
11849     ErrorInfo.Error = ErrorTy::NotEQ;
11850     ErrorInfo.ErrorLoc = BO->getExprLoc();
11851     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11852     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11853     return false;
11854   }
11855 
11856   C = BO;
11857 
11858   if (checkIfTwoExprsAreSame(ContextRef, X, BO->getLHS())) {
11859     E = BO->getRHS();
11860   } else if (checkIfTwoExprsAreSame(ContextRef, X, BO->getRHS())) {
11861     E = BO->getLHS();
11862   } else {
11863     ErrorInfo.Error = ErrorTy::InvalidComparison;
11864     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getExprLoc();
11865     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11866     return false;
11867   }
11868 
11869   if (S2->getElse()) {
11870     IsFailOnly = true;
11871 
11872     auto *Else = S2->getElse();
11873     if (auto *ElseCS = dyn_cast<CompoundStmt>(Else)) {
11874       if (ElseCS->body_empty()) {
11875         ErrorInfo.Error = ErrorTy::NoStmt;
11876         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
11877         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
11878         return false;
11879       }
11880       if (ElseCS->size() > 1) {
11881         ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11882         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
11883         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
11884         return false;
11885       }
11886       Else = ElseCS->body_front();
11887     }
11888 
11889     auto *ElseBO = dyn_cast<BinaryOperator>(Else);
11890     if (!ElseBO) {
11891       ErrorInfo.Error = ErrorTy::NotAnAssignment;
11892       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
11893       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
11894       return false;
11895     }
11896     if (ElseBO->getOpcode() != BO_Assign) {
11897       ErrorInfo.Error = ErrorTy::NotAnAssignment;
11898       ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
11899       ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
11900       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
11901       return false;
11902     }
11903     if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
11904       ErrorInfo.Error = ErrorTy::InvalidAssignment;
11905       ErrorInfo.ErrorLoc = ElseBO->getRHS()->getExprLoc();
11906       ErrorInfo.NoteLoc = X->getExprLoc();
11907       ErrorInfo.ErrorRange = ElseBO->getRHS()->getSourceRange();
11908       ErrorInfo.NoteRange = X->getSourceRange();
11909       return false;
11910     }
11911 
11912     V = ElseBO->getLHS();
11913   }
11914 
11915   return checkType(ErrorInfo);
11916 }
11917 
11918 bool OpenMPAtomicCompareCaptureChecker::checkStmt(Stmt *S,
11919                                                   ErrorInfoTy &ErrorInfo) {
11920   // if(x == e) { x = d; } else { v = x; }
11921   if (auto *IS = dyn_cast<IfStmt>(S))
11922     return checkForm3(IS, ErrorInfo);
11923 
11924   auto *CS = dyn_cast<CompoundStmt>(S);
11925   if (!CS) {
11926     ErrorInfo.Error = ErrorTy::NotCompoundStmt;
11927     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11928     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11929     return false;
11930   }
11931   if (CS->body_empty()) {
11932     ErrorInfo.Error = ErrorTy::NoStmt;
11933     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11934     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11935     return false;
11936   }
11937 
11938   // { if(x == e) { x = d; } else { v = x; } }
11939   if (CS->size() == 1) {
11940     auto *IS = dyn_cast<IfStmt>(CS->body_front());
11941     if (!IS) {
11942       ErrorInfo.Error = ErrorTy::NotIfStmt;
11943       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->body_front()->getBeginLoc();
11944       ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11945           CS->body_front()->getSourceRange();
11946       return false;
11947     }
11948 
11949     return checkForm3(IS, ErrorInfo);
11950   } else if (CS->size() == 2) {
11951     auto *S1 = CS->body_front();
11952     auto *S2 = CS->body_back();
11953 
11954     Stmt *UpdateStmt = nullptr;
11955     Stmt *CondUpdateStmt = nullptr;
11956 
11957     if (auto *BO = dyn_cast<BinaryOperator>(S1)) {
11958       // { v = x; cond-update-stmt } or form 45.
11959       UpdateStmt = S1;
11960       CondUpdateStmt = S2;
11961       // Check if form 45.
11962       if (dyn_cast<BinaryOperator>(BO->getRHS()->IgnoreImpCasts()) &&
11963           dyn_cast<IfStmt>(S2))
11964         return checkForm45(CS, ErrorInfo);
11965     } else {
11966       // { cond-update-stmt v = x; }
11967       UpdateStmt = S2;
11968       CondUpdateStmt = S1;
11969     }
11970 
11971     auto CheckCondUpdateStmt = [this, &ErrorInfo](Stmt *CUS) {
11972       auto *IS = dyn_cast<IfStmt>(CUS);
11973       if (!IS) {
11974         ErrorInfo.Error = ErrorTy::NotIfStmt;
11975         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CUS->getBeginLoc();
11976         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CUS->getSourceRange();
11977         return false;
11978       }
11979 
11980       if (!checkCondUpdateStmt(IS, ErrorInfo))
11981         return false;
11982 
11983       return true;
11984     };
11985 
11986     // CheckUpdateStmt has to be called *after* CheckCondUpdateStmt.
11987     auto CheckUpdateStmt = [this, &ErrorInfo](Stmt *US) {
11988       auto *BO = dyn_cast<BinaryOperator>(US);
11989       if (!BO) {
11990         ErrorInfo.Error = ErrorTy::NotAnAssignment;
11991         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = US->getBeginLoc();
11992         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = US->getSourceRange();
11993         return false;
11994       }
11995       if (BO->getOpcode() != BO_Assign) {
11996         ErrorInfo.Error = ErrorTy::NotAnAssignment;
11997         ErrorInfo.ErrorLoc = BO->getExprLoc();
11998         ErrorInfo.NoteLoc = BO->getOperatorLoc();
11999         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
12000         return false;
12001       }
12002       if (!checkIfTwoExprsAreSame(ContextRef, this->X, BO->getRHS())) {
12003         ErrorInfo.Error = ErrorTy::InvalidAssignment;
12004         ErrorInfo.ErrorLoc = BO->getRHS()->getExprLoc();
12005         ErrorInfo.NoteLoc = this->X->getExprLoc();
12006         ErrorInfo.ErrorRange = BO->getRHS()->getSourceRange();
12007         ErrorInfo.NoteRange = this->X->getSourceRange();
12008         return false;
12009       }
12010 
12011       this->V = BO->getLHS();
12012 
12013       return true;
12014     };
12015 
12016     if (!CheckCondUpdateStmt(CondUpdateStmt))
12017       return false;
12018     if (!CheckUpdateStmt(UpdateStmt))
12019       return false;
12020   } else {
12021     ErrorInfo.Error = ErrorTy::MoreThanTwoStmts;
12022     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
12023     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
12024     return false;
12025   }
12026 
12027   return checkType(ErrorInfo);
12028 }
12029 } // namespace
12030 
12031 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
12032                                             Stmt *AStmt,
12033                                             SourceLocation StartLoc,
12034                                             SourceLocation EndLoc) {
12035   // Register location of the first atomic directive.
12036   DSAStack->addAtomicDirectiveLoc(StartLoc);
12037   if (!AStmt)
12038     return StmtError();
12039 
12040   // 1.2.2 OpenMP Language Terminology
12041   // Structured block - An executable statement with a single entry at the
12042   // top and a single exit at the bottom.
12043   // The point of exit cannot be a branch out of the structured block.
12044   // longjmp() and throw() must not violate the entry/exit criteria.
12045   OpenMPClauseKind AtomicKind = OMPC_unknown;
12046   SourceLocation AtomicKindLoc;
12047   OpenMPClauseKind MemOrderKind = OMPC_unknown;
12048   SourceLocation MemOrderLoc;
12049   bool MutexClauseEncountered = false;
12050   llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds;
12051   for (const OMPClause *C : Clauses) {
12052     switch (C->getClauseKind()) {
12053     case OMPC_read:
12054     case OMPC_write:
12055     case OMPC_update:
12056       MutexClauseEncountered = true;
12057       LLVM_FALLTHROUGH;
12058     case OMPC_capture:
12059     case OMPC_compare: {
12060       if (AtomicKind != OMPC_unknown && MutexClauseEncountered) {
12061         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
12062             << SourceRange(C->getBeginLoc(), C->getEndLoc());
12063         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
12064             << getOpenMPClauseName(AtomicKind);
12065       } else {
12066         AtomicKind = C->getClauseKind();
12067         AtomicKindLoc = C->getBeginLoc();
12068         if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) {
12069           Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
12070               << SourceRange(C->getBeginLoc(), C->getEndLoc());
12071           Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
12072               << getOpenMPClauseName(AtomicKind);
12073         }
12074       }
12075       break;
12076     }
12077     case OMPC_seq_cst:
12078     case OMPC_acq_rel:
12079     case OMPC_acquire:
12080     case OMPC_release:
12081     case OMPC_relaxed: {
12082       if (MemOrderKind != OMPC_unknown) {
12083         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
12084             << getOpenMPDirectiveName(OMPD_atomic) << 0
12085             << SourceRange(C->getBeginLoc(), C->getEndLoc());
12086         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
12087             << getOpenMPClauseName(MemOrderKind);
12088       } else {
12089         MemOrderKind = C->getClauseKind();
12090         MemOrderLoc = C->getBeginLoc();
12091       }
12092       break;
12093     }
12094     // The following clauses are allowed, but we don't need to do anything here.
12095     case OMPC_hint:
12096       break;
12097     default:
12098       llvm_unreachable("unknown clause is encountered");
12099     }
12100   }
12101   bool IsCompareCapture = false;
12102   if (EncounteredAtomicKinds.contains(OMPC_compare) &&
12103       EncounteredAtomicKinds.contains(OMPC_capture)) {
12104     IsCompareCapture = true;
12105     AtomicKind = OMPC_compare;
12106   }
12107   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
12108   // If atomic-clause is read then memory-order-clause must not be acq_rel or
12109   // release.
12110   // If atomic-clause is write then memory-order-clause must not be acq_rel or
12111   // acquire.
12112   // If atomic-clause is update or not present then memory-order-clause must not
12113   // be acq_rel or acquire.
12114   if ((AtomicKind == OMPC_read &&
12115        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
12116       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
12117         AtomicKind == OMPC_unknown) &&
12118        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
12119     SourceLocation Loc = AtomicKindLoc;
12120     if (AtomicKind == OMPC_unknown)
12121       Loc = StartLoc;
12122     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
12123         << getOpenMPClauseName(AtomicKind)
12124         << (AtomicKind == OMPC_unknown ? 1 : 0)
12125         << getOpenMPClauseName(MemOrderKind);
12126     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
12127         << getOpenMPClauseName(MemOrderKind);
12128   }
12129 
12130   Stmt *Body = AStmt;
12131   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
12132     Body = EWC->getSubExpr();
12133 
12134   Expr *X = nullptr;
12135   Expr *V = nullptr;
12136   Expr *E = nullptr;
12137   Expr *UE = nullptr;
12138   Expr *D = nullptr;
12139   Expr *CE = nullptr;
12140   bool IsXLHSInRHSPart = false;
12141   bool IsPostfixUpdate = false;
12142   // OpenMP [2.12.6, atomic Construct]
12143   // In the next expressions:
12144   // * x and v (as applicable) are both l-value expressions with scalar type.
12145   // * During the execution of an atomic region, multiple syntactic
12146   // occurrences of x must designate the same storage location.
12147   // * Neither of v and expr (as applicable) may access the storage location
12148   // designated by x.
12149   // * Neither of x and expr (as applicable) may access the storage location
12150   // designated by v.
12151   // * expr is an expression with scalar type.
12152   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
12153   // * binop, binop=, ++, and -- are not overloaded operators.
12154   // * The expression x binop expr must be numerically equivalent to x binop
12155   // (expr). This requirement is satisfied if the operators in expr have
12156   // precedence greater than binop, or by using parentheses around expr or
12157   // subexpressions of expr.
12158   // * The expression expr binop x must be numerically equivalent to (expr)
12159   // binop x. This requirement is satisfied if the operators in expr have
12160   // precedence equal to or greater than binop, or by using parentheses around
12161   // expr or subexpressions of expr.
12162   // * For forms that allow multiple occurrences of x, the number of times
12163   // that x is evaluated is unspecified.
12164   if (AtomicKind == OMPC_read) {
12165     enum {
12166       NotAnExpression,
12167       NotAnAssignmentOp,
12168       NotAScalarType,
12169       NotAnLValue,
12170       NoError
12171     } ErrorFound = NoError;
12172     SourceLocation ErrorLoc, NoteLoc;
12173     SourceRange ErrorRange, NoteRange;
12174     // If clause is read:
12175     //  v = x;
12176     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
12177       const auto *AtomicBinOp =
12178           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
12179       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
12180         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
12181         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
12182         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
12183             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
12184           if (!X->isLValue() || !V->isLValue()) {
12185             const Expr *NotLValueExpr = X->isLValue() ? V : X;
12186             ErrorFound = NotAnLValue;
12187             ErrorLoc = AtomicBinOp->getExprLoc();
12188             ErrorRange = AtomicBinOp->getSourceRange();
12189             NoteLoc = NotLValueExpr->getExprLoc();
12190             NoteRange = NotLValueExpr->getSourceRange();
12191           }
12192         } else if (!X->isInstantiationDependent() ||
12193                    !V->isInstantiationDependent()) {
12194           const Expr *NotScalarExpr =
12195               (X->isInstantiationDependent() || X->getType()->isScalarType())
12196                   ? V
12197                   : X;
12198           ErrorFound = NotAScalarType;
12199           ErrorLoc = AtomicBinOp->getExprLoc();
12200           ErrorRange = AtomicBinOp->getSourceRange();
12201           NoteLoc = NotScalarExpr->getExprLoc();
12202           NoteRange = NotScalarExpr->getSourceRange();
12203         }
12204       } else if (!AtomicBody->isInstantiationDependent()) {
12205         ErrorFound = NotAnAssignmentOp;
12206         ErrorLoc = AtomicBody->getExprLoc();
12207         ErrorRange = AtomicBody->getSourceRange();
12208         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
12209                               : AtomicBody->getExprLoc();
12210         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
12211                                 : AtomicBody->getSourceRange();
12212       }
12213     } else {
12214       ErrorFound = NotAnExpression;
12215       NoteLoc = ErrorLoc = Body->getBeginLoc();
12216       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
12217     }
12218     if (ErrorFound != NoError) {
12219       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
12220           << ErrorRange;
12221       Diag(NoteLoc, diag::note_omp_atomic_read_write)
12222           << ErrorFound << NoteRange;
12223       return StmtError();
12224     }
12225     if (CurContext->isDependentContext())
12226       V = X = nullptr;
12227   } else if (AtomicKind == OMPC_write) {
12228     enum {
12229       NotAnExpression,
12230       NotAnAssignmentOp,
12231       NotAScalarType,
12232       NotAnLValue,
12233       NoError
12234     } ErrorFound = NoError;
12235     SourceLocation ErrorLoc, NoteLoc;
12236     SourceRange ErrorRange, NoteRange;
12237     // If clause is write:
12238     //  x = expr;
12239     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
12240       const auto *AtomicBinOp =
12241           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
12242       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
12243         X = AtomicBinOp->getLHS();
12244         E = AtomicBinOp->getRHS();
12245         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
12246             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
12247           if (!X->isLValue()) {
12248             ErrorFound = NotAnLValue;
12249             ErrorLoc = AtomicBinOp->getExprLoc();
12250             ErrorRange = AtomicBinOp->getSourceRange();
12251             NoteLoc = X->getExprLoc();
12252             NoteRange = X->getSourceRange();
12253           }
12254         } else if (!X->isInstantiationDependent() ||
12255                    !E->isInstantiationDependent()) {
12256           const Expr *NotScalarExpr =
12257               (X->isInstantiationDependent() || X->getType()->isScalarType())
12258                   ? E
12259                   : X;
12260           ErrorFound = NotAScalarType;
12261           ErrorLoc = AtomicBinOp->getExprLoc();
12262           ErrorRange = AtomicBinOp->getSourceRange();
12263           NoteLoc = NotScalarExpr->getExprLoc();
12264           NoteRange = NotScalarExpr->getSourceRange();
12265         }
12266       } else if (!AtomicBody->isInstantiationDependent()) {
12267         ErrorFound = NotAnAssignmentOp;
12268         ErrorLoc = AtomicBody->getExprLoc();
12269         ErrorRange = AtomicBody->getSourceRange();
12270         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
12271                               : AtomicBody->getExprLoc();
12272         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
12273                                 : AtomicBody->getSourceRange();
12274       }
12275     } else {
12276       ErrorFound = NotAnExpression;
12277       NoteLoc = ErrorLoc = Body->getBeginLoc();
12278       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
12279     }
12280     if (ErrorFound != NoError) {
12281       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
12282           << ErrorRange;
12283       Diag(NoteLoc, diag::note_omp_atomic_read_write)
12284           << ErrorFound << NoteRange;
12285       return StmtError();
12286     }
12287     if (CurContext->isDependentContext())
12288       E = X = nullptr;
12289   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
12290     // If clause is update:
12291     //  x++;
12292     //  x--;
12293     //  ++x;
12294     //  --x;
12295     //  x binop= expr;
12296     //  x = x binop expr;
12297     //  x = expr binop x;
12298     OpenMPAtomicUpdateChecker Checker(*this);
12299     if (Checker.checkStatement(
12300             Body,
12301             (AtomicKind == OMPC_update)
12302                 ? diag::err_omp_atomic_update_not_expression_statement
12303                 : diag::err_omp_atomic_not_expression_statement,
12304             diag::note_omp_atomic_update))
12305       return StmtError();
12306     if (!CurContext->isDependentContext()) {
12307       E = Checker.getExpr();
12308       X = Checker.getX();
12309       UE = Checker.getUpdateExpr();
12310       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12311     }
12312   } else if (AtomicKind == OMPC_capture) {
12313     enum {
12314       NotAnAssignmentOp,
12315       NotACompoundStatement,
12316       NotTwoSubstatements,
12317       NotASpecificExpression,
12318       NoError
12319     } ErrorFound = NoError;
12320     SourceLocation ErrorLoc, NoteLoc;
12321     SourceRange ErrorRange, NoteRange;
12322     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
12323       // If clause is a capture:
12324       //  v = x++;
12325       //  v = x--;
12326       //  v = ++x;
12327       //  v = --x;
12328       //  v = x binop= expr;
12329       //  v = x = x binop expr;
12330       //  v = x = expr binop x;
12331       const auto *AtomicBinOp =
12332           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
12333       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
12334         V = AtomicBinOp->getLHS();
12335         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
12336         OpenMPAtomicUpdateChecker Checker(*this);
12337         if (Checker.checkStatement(
12338                 Body, diag::err_omp_atomic_capture_not_expression_statement,
12339                 diag::note_omp_atomic_update))
12340           return StmtError();
12341         E = Checker.getExpr();
12342         X = Checker.getX();
12343         UE = Checker.getUpdateExpr();
12344         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12345         IsPostfixUpdate = Checker.isPostfixUpdate();
12346       } else if (!AtomicBody->isInstantiationDependent()) {
12347         ErrorLoc = AtomicBody->getExprLoc();
12348         ErrorRange = AtomicBody->getSourceRange();
12349         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
12350                               : AtomicBody->getExprLoc();
12351         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
12352                                 : AtomicBody->getSourceRange();
12353         ErrorFound = NotAnAssignmentOp;
12354       }
12355       if (ErrorFound != NoError) {
12356         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
12357             << ErrorRange;
12358         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
12359         return StmtError();
12360       }
12361       if (CurContext->isDependentContext())
12362         UE = V = E = X = nullptr;
12363     } else {
12364       // If clause is a capture:
12365       //  { v = x; x = expr; }
12366       //  { v = x; x++; }
12367       //  { v = x; x--; }
12368       //  { v = x; ++x; }
12369       //  { v = x; --x; }
12370       //  { v = x; x binop= expr; }
12371       //  { v = x; x = x binop expr; }
12372       //  { v = x; x = expr binop x; }
12373       //  { x++; v = x; }
12374       //  { x--; v = x; }
12375       //  { ++x; v = x; }
12376       //  { --x; v = x; }
12377       //  { x binop= expr; v = x; }
12378       //  { x = x binop expr; v = x; }
12379       //  { x = expr binop x; v = x; }
12380       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
12381         // Check that this is { expr1; expr2; }
12382         if (CS->size() == 2) {
12383           Stmt *First = CS->body_front();
12384           Stmt *Second = CS->body_back();
12385           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
12386             First = EWC->getSubExpr()->IgnoreParenImpCasts();
12387           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
12388             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
12389           // Need to find what subexpression is 'v' and what is 'x'.
12390           OpenMPAtomicUpdateChecker Checker(*this);
12391           bool IsUpdateExprFound = !Checker.checkStatement(Second);
12392           BinaryOperator *BinOp = nullptr;
12393           if (IsUpdateExprFound) {
12394             BinOp = dyn_cast<BinaryOperator>(First);
12395             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
12396           }
12397           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
12398             //  { v = x; x++; }
12399             //  { v = x; x--; }
12400             //  { v = x; ++x; }
12401             //  { v = x; --x; }
12402             //  { v = x; x binop= expr; }
12403             //  { v = x; x = x binop expr; }
12404             //  { v = x; x = expr binop x; }
12405             // Check that the first expression has form v = x.
12406             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
12407             llvm::FoldingSetNodeID XId, PossibleXId;
12408             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
12409             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
12410             IsUpdateExprFound = XId == PossibleXId;
12411             if (IsUpdateExprFound) {
12412               V = BinOp->getLHS();
12413               X = Checker.getX();
12414               E = Checker.getExpr();
12415               UE = Checker.getUpdateExpr();
12416               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12417               IsPostfixUpdate = true;
12418             }
12419           }
12420           if (!IsUpdateExprFound) {
12421             IsUpdateExprFound = !Checker.checkStatement(First);
12422             BinOp = nullptr;
12423             if (IsUpdateExprFound) {
12424               BinOp = dyn_cast<BinaryOperator>(Second);
12425               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
12426             }
12427             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
12428               //  { x++; v = x; }
12429               //  { x--; v = x; }
12430               //  { ++x; v = x; }
12431               //  { --x; v = x; }
12432               //  { x binop= expr; v = x; }
12433               //  { x = x binop expr; v = x; }
12434               //  { x = expr binop x; v = x; }
12435               // Check that the second expression has form v = x.
12436               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
12437               llvm::FoldingSetNodeID XId, PossibleXId;
12438               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
12439               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
12440               IsUpdateExprFound = XId == PossibleXId;
12441               if (IsUpdateExprFound) {
12442                 V = BinOp->getLHS();
12443                 X = Checker.getX();
12444                 E = Checker.getExpr();
12445                 UE = Checker.getUpdateExpr();
12446                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
12447                 IsPostfixUpdate = false;
12448               }
12449             }
12450           }
12451           if (!IsUpdateExprFound) {
12452             //  { v = x; x = expr; }
12453             auto *FirstExpr = dyn_cast<Expr>(First);
12454             auto *SecondExpr = dyn_cast<Expr>(Second);
12455             if (!FirstExpr || !SecondExpr ||
12456                 !(FirstExpr->isInstantiationDependent() ||
12457                   SecondExpr->isInstantiationDependent())) {
12458               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
12459               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
12460                 ErrorFound = NotAnAssignmentOp;
12461                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
12462                                                 : First->getBeginLoc();
12463                 NoteRange = ErrorRange = FirstBinOp
12464                                              ? FirstBinOp->getSourceRange()
12465                                              : SourceRange(ErrorLoc, ErrorLoc);
12466               } else {
12467                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
12468                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
12469                   ErrorFound = NotAnAssignmentOp;
12470                   NoteLoc = ErrorLoc = SecondBinOp
12471                                            ? SecondBinOp->getOperatorLoc()
12472                                            : Second->getBeginLoc();
12473                   NoteRange = ErrorRange =
12474                       SecondBinOp ? SecondBinOp->getSourceRange()
12475                                   : SourceRange(ErrorLoc, ErrorLoc);
12476                 } else {
12477                   Expr *PossibleXRHSInFirst =
12478                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
12479                   Expr *PossibleXLHSInSecond =
12480                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
12481                   llvm::FoldingSetNodeID X1Id, X2Id;
12482                   PossibleXRHSInFirst->Profile(X1Id, Context,
12483                                                /*Canonical=*/true);
12484                   PossibleXLHSInSecond->Profile(X2Id, Context,
12485                                                 /*Canonical=*/true);
12486                   IsUpdateExprFound = X1Id == X2Id;
12487                   if (IsUpdateExprFound) {
12488                     V = FirstBinOp->getLHS();
12489                     X = SecondBinOp->getLHS();
12490                     E = SecondBinOp->getRHS();
12491                     UE = nullptr;
12492                     IsXLHSInRHSPart = false;
12493                     IsPostfixUpdate = true;
12494                   } else {
12495                     ErrorFound = NotASpecificExpression;
12496                     ErrorLoc = FirstBinOp->getExprLoc();
12497                     ErrorRange = FirstBinOp->getSourceRange();
12498                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
12499                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
12500                   }
12501                 }
12502               }
12503             }
12504           }
12505         } else {
12506           NoteLoc = ErrorLoc = Body->getBeginLoc();
12507           NoteRange = ErrorRange =
12508               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
12509           ErrorFound = NotTwoSubstatements;
12510         }
12511       } else {
12512         NoteLoc = ErrorLoc = Body->getBeginLoc();
12513         NoteRange = ErrorRange =
12514             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
12515         ErrorFound = NotACompoundStatement;
12516       }
12517     }
12518     if (ErrorFound != NoError) {
12519       Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
12520           << ErrorRange;
12521       Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
12522       return StmtError();
12523     }
12524     if (CurContext->isDependentContext())
12525       UE = V = E = X = nullptr;
12526   } else if (AtomicKind == OMPC_compare) {
12527     if (IsCompareCapture) {
12528       OpenMPAtomicCompareCaptureChecker::ErrorInfoTy ErrorInfo;
12529       OpenMPAtomicCompareCaptureChecker Checker(*this);
12530       if (!Checker.checkStmt(Body, ErrorInfo)) {
12531         Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare_capture)
12532             << ErrorInfo.ErrorRange;
12533         Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
12534             << ErrorInfo.Error << ErrorInfo.NoteRange;
12535         return StmtError();
12536       }
12537       // TODO: We don't set X, D, E, etc. here because in code gen we will emit
12538       // error directly.
12539     } else {
12540       OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo;
12541       OpenMPAtomicCompareChecker Checker(*this);
12542       if (!Checker.checkStmt(Body, ErrorInfo)) {
12543         Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare)
12544             << ErrorInfo.ErrorRange;
12545         Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
12546             << ErrorInfo.Error << ErrorInfo.NoteRange;
12547         return StmtError();
12548       }
12549       X = Checker.getX();
12550       E = Checker.getE();
12551       D = Checker.getD();
12552       CE = Checker.getCond();
12553       // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'.
12554       IsXLHSInRHSPart = Checker.isXBinopExpr();
12555     }
12556   }
12557 
12558   setFunctionHasBranchProtectedScope();
12559 
12560   return OMPAtomicDirective::Create(
12561       Context, StartLoc, EndLoc, Clauses, AStmt,
12562       {X, V, E, UE, D, CE, IsXLHSInRHSPart, IsPostfixUpdate});
12563 }
12564 
12565 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
12566                                             Stmt *AStmt,
12567                                             SourceLocation StartLoc,
12568                                             SourceLocation EndLoc) {
12569   if (!AStmt)
12570     return StmtError();
12571 
12572   auto *CS = cast<CapturedStmt>(AStmt);
12573   // 1.2.2 OpenMP Language Terminology
12574   // Structured block - An executable statement with a single entry at the
12575   // top and a single exit at the bottom.
12576   // The point of exit cannot be a branch out of the structured block.
12577   // longjmp() and throw() must not violate the entry/exit criteria.
12578   CS->getCapturedDecl()->setNothrow();
12579   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
12580        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12581     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12582     // 1.2.2 OpenMP Language Terminology
12583     // Structured block - An executable statement with a single entry at the
12584     // top and a single exit at the bottom.
12585     // The point of exit cannot be a branch out of the structured block.
12586     // longjmp() and throw() must not violate the entry/exit criteria.
12587     CS->getCapturedDecl()->setNothrow();
12588   }
12589 
12590   // OpenMP [2.16, Nesting of Regions]
12591   // If specified, a teams construct must be contained within a target
12592   // construct. That target construct must contain no statements or directives
12593   // outside of the teams construct.
12594   if (DSAStack->hasInnerTeamsRegion()) {
12595     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
12596     bool OMPTeamsFound = true;
12597     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
12598       auto I = CS->body_begin();
12599       while (I != CS->body_end()) {
12600         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
12601         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
12602             OMPTeamsFound) {
12603 
12604           OMPTeamsFound = false;
12605           break;
12606         }
12607         ++I;
12608       }
12609       assert(I != CS->body_end() && "Not found statement");
12610       S = *I;
12611     } else {
12612       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
12613       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
12614     }
12615     if (!OMPTeamsFound) {
12616       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
12617       Diag(DSAStack->getInnerTeamsRegionLoc(),
12618            diag::note_omp_nested_teams_construct_here);
12619       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
12620           << isa<OMPExecutableDirective>(S);
12621       return StmtError();
12622     }
12623   }
12624 
12625   setFunctionHasBranchProtectedScope();
12626 
12627   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
12628 }
12629 
12630 StmtResult
12631 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
12632                                          Stmt *AStmt, SourceLocation StartLoc,
12633                                          SourceLocation EndLoc) {
12634   if (!AStmt)
12635     return StmtError();
12636 
12637   auto *CS = cast<CapturedStmt>(AStmt);
12638   // 1.2.2 OpenMP Language Terminology
12639   // Structured block - An executable statement with a single entry at the
12640   // top and a single exit at the bottom.
12641   // The point of exit cannot be a branch out of the structured block.
12642   // longjmp() and throw() must not violate the entry/exit criteria.
12643   CS->getCapturedDecl()->setNothrow();
12644   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
12645        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12646     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12647     // 1.2.2 OpenMP Language Terminology
12648     // Structured block - An executable statement with a single entry at the
12649     // top and a single exit at the bottom.
12650     // The point of exit cannot be a branch out of the structured block.
12651     // longjmp() and throw() must not violate the entry/exit criteria.
12652     CS->getCapturedDecl()->setNothrow();
12653   }
12654 
12655   setFunctionHasBranchProtectedScope();
12656 
12657   return OMPTargetParallelDirective::Create(
12658       Context, StartLoc, EndLoc, Clauses, AStmt,
12659       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12660 }
12661 
12662 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
12663     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12664     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12665   if (!AStmt)
12666     return StmtError();
12667 
12668   auto *CS = cast<CapturedStmt>(AStmt);
12669   // 1.2.2 OpenMP Language Terminology
12670   // Structured block - An executable statement with a single entry at the
12671   // top and a single exit at the bottom.
12672   // The point of exit cannot be a branch out of the structured block.
12673   // longjmp() and throw() must not violate the entry/exit criteria.
12674   CS->getCapturedDecl()->setNothrow();
12675   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12676        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12677     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12678     // 1.2.2 OpenMP Language Terminology
12679     // Structured block - An executable statement with a single entry at the
12680     // top and a single exit at the bottom.
12681     // The point of exit cannot be a branch out of the structured block.
12682     // longjmp() and throw() must not violate the entry/exit criteria.
12683     CS->getCapturedDecl()->setNothrow();
12684   }
12685 
12686   OMPLoopBasedDirective::HelperExprs B;
12687   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12688   // define the nested loops number.
12689   unsigned NestedLoopCount =
12690       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
12691                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12692                       VarsWithImplicitDSA, B);
12693   if (NestedLoopCount == 0)
12694     return StmtError();
12695 
12696   assert((CurContext->isDependentContext() || B.builtAll()) &&
12697          "omp target parallel for loop exprs were not built");
12698 
12699   if (!CurContext->isDependentContext()) {
12700     // Finalize the clauses that need pre-built expressions for CodeGen.
12701     for (OMPClause *C : Clauses) {
12702       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12703         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12704                                      B.NumIterations, *this, CurScope,
12705                                      DSAStack))
12706           return StmtError();
12707     }
12708   }
12709 
12710   setFunctionHasBranchProtectedScope();
12711   return OMPTargetParallelForDirective::Create(
12712       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12713       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12714 }
12715 
12716 /// Check for existence of a map clause in the list of clauses.
12717 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
12718                        const OpenMPClauseKind K) {
12719   return llvm::any_of(
12720       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
12721 }
12722 
12723 template <typename... Params>
12724 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
12725                        const Params... ClauseTypes) {
12726   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
12727 }
12728 
12729 /// Check if the variables in the mapping clause are externally visible.
12730 static bool isClauseMappable(ArrayRef<OMPClause *> Clauses) {
12731   for (const OMPClause *C : Clauses) {
12732     if (auto *TC = dyn_cast<OMPToClause>(C))
12733       return llvm::all_of(TC->all_decls(), [](ValueDecl *VD) {
12734         return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
12735                (VD->isExternallyVisible() &&
12736                 VD->getVisibility() != HiddenVisibility);
12737       });
12738     else if (auto *FC = dyn_cast<OMPFromClause>(C))
12739       return llvm::all_of(FC->all_decls(), [](ValueDecl *VD) {
12740         return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
12741                (VD->isExternallyVisible() &&
12742                 VD->getVisibility() != HiddenVisibility);
12743       });
12744   }
12745 
12746   return true;
12747 }
12748 
12749 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
12750                                                 Stmt *AStmt,
12751                                                 SourceLocation StartLoc,
12752                                                 SourceLocation EndLoc) {
12753   if (!AStmt)
12754     return StmtError();
12755 
12756   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12757 
12758   // OpenMP [2.12.2, target data Construct, Restrictions]
12759   // At least one map, use_device_addr or use_device_ptr clause must appear on
12760   // the directive.
12761   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
12762       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
12763     StringRef Expected;
12764     if (LangOpts.OpenMP < 50)
12765       Expected = "'map' or 'use_device_ptr'";
12766     else
12767       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
12768     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12769         << Expected << getOpenMPDirectiveName(OMPD_target_data);
12770     return StmtError();
12771   }
12772 
12773   setFunctionHasBranchProtectedScope();
12774 
12775   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12776                                         AStmt);
12777 }
12778 
12779 StmtResult
12780 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
12781                                           SourceLocation StartLoc,
12782                                           SourceLocation EndLoc, Stmt *AStmt) {
12783   if (!AStmt)
12784     return StmtError();
12785 
12786   auto *CS = cast<CapturedStmt>(AStmt);
12787   // 1.2.2 OpenMP Language Terminology
12788   // Structured block - An executable statement with a single entry at the
12789   // top and a single exit at the bottom.
12790   // The point of exit cannot be a branch out of the structured block.
12791   // longjmp() and throw() must not violate the entry/exit criteria.
12792   CS->getCapturedDecl()->setNothrow();
12793   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
12794        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12795     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12796     // 1.2.2 OpenMP Language Terminology
12797     // Structured block - An executable statement with a single entry at the
12798     // top and a single exit at the bottom.
12799     // The point of exit cannot be a branch out of the structured block.
12800     // longjmp() and throw() must not violate the entry/exit criteria.
12801     CS->getCapturedDecl()->setNothrow();
12802   }
12803 
12804   // OpenMP [2.10.2, Restrictions, p. 99]
12805   // At least one map clause must appear on the directive.
12806   if (!hasClauses(Clauses, OMPC_map)) {
12807     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12808         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
12809     return StmtError();
12810   }
12811 
12812   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12813                                              AStmt);
12814 }
12815 
12816 StmtResult
12817 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
12818                                          SourceLocation StartLoc,
12819                                          SourceLocation EndLoc, Stmt *AStmt) {
12820   if (!AStmt)
12821     return StmtError();
12822 
12823   auto *CS = cast<CapturedStmt>(AStmt);
12824   // 1.2.2 OpenMP Language Terminology
12825   // Structured block - An executable statement with a single entry at the
12826   // top and a single exit at the bottom.
12827   // The point of exit cannot be a branch out of the structured block.
12828   // longjmp() and throw() must not violate the entry/exit criteria.
12829   CS->getCapturedDecl()->setNothrow();
12830   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
12831        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12832     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12833     // 1.2.2 OpenMP Language Terminology
12834     // Structured block - An executable statement with a single entry at the
12835     // top and a single exit at the bottom.
12836     // The point of exit cannot be a branch out of the structured block.
12837     // longjmp() and throw() must not violate the entry/exit criteria.
12838     CS->getCapturedDecl()->setNothrow();
12839   }
12840 
12841   // OpenMP [2.10.3, Restrictions, p. 102]
12842   // At least one map clause must appear on the directive.
12843   if (!hasClauses(Clauses, OMPC_map)) {
12844     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12845         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
12846     return StmtError();
12847   }
12848 
12849   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12850                                             AStmt);
12851 }
12852 
12853 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
12854                                                   SourceLocation StartLoc,
12855                                                   SourceLocation EndLoc,
12856                                                   Stmt *AStmt) {
12857   if (!AStmt)
12858     return StmtError();
12859 
12860   auto *CS = cast<CapturedStmt>(AStmt);
12861   // 1.2.2 OpenMP Language Terminology
12862   // Structured block - An executable statement with a single entry at the
12863   // top and a single exit at the bottom.
12864   // The point of exit cannot be a branch out of the structured block.
12865   // longjmp() and throw() must not violate the entry/exit criteria.
12866   CS->getCapturedDecl()->setNothrow();
12867   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
12868        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12869     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12870     // 1.2.2 OpenMP Language Terminology
12871     // Structured block - An executable statement with a single entry at the
12872     // top and a single exit at the bottom.
12873     // The point of exit cannot be a branch out of the structured block.
12874     // longjmp() and throw() must not violate the entry/exit criteria.
12875     CS->getCapturedDecl()->setNothrow();
12876   }
12877 
12878   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
12879     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
12880     return StmtError();
12881   }
12882 
12883   if (!isClauseMappable(Clauses)) {
12884     Diag(StartLoc, diag::err_omp_cannot_update_with_internal_linkage);
12885     return StmtError();
12886   }
12887 
12888   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
12889                                           AStmt);
12890 }
12891 
12892 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
12893                                            Stmt *AStmt, SourceLocation StartLoc,
12894                                            SourceLocation EndLoc) {
12895   if (!AStmt)
12896     return StmtError();
12897 
12898   auto *CS = cast<CapturedStmt>(AStmt);
12899   // 1.2.2 OpenMP Language Terminology
12900   // Structured block - An executable statement with a single entry at the
12901   // top and a single exit at the bottom.
12902   // The point of exit cannot be a branch out of the structured block.
12903   // longjmp() and throw() must not violate the entry/exit criteria.
12904   CS->getCapturedDecl()->setNothrow();
12905 
12906   setFunctionHasBranchProtectedScope();
12907 
12908   DSAStack->setParentTeamsRegionLoc(StartLoc);
12909 
12910   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
12911 }
12912 
12913 StmtResult
12914 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
12915                                             SourceLocation EndLoc,
12916                                             OpenMPDirectiveKind CancelRegion) {
12917   if (DSAStack->isParentNowaitRegion()) {
12918     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
12919     return StmtError();
12920   }
12921   if (DSAStack->isParentOrderedRegion()) {
12922     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
12923     return StmtError();
12924   }
12925   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
12926                                                CancelRegion);
12927 }
12928 
12929 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
12930                                             SourceLocation StartLoc,
12931                                             SourceLocation EndLoc,
12932                                             OpenMPDirectiveKind CancelRegion) {
12933   if (DSAStack->isParentNowaitRegion()) {
12934     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
12935     return StmtError();
12936   }
12937   if (DSAStack->isParentOrderedRegion()) {
12938     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
12939     return StmtError();
12940   }
12941   DSAStack->setParentCancelRegion(/*Cancel=*/true);
12942   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
12943                                     CancelRegion);
12944 }
12945 
12946 static bool checkReductionClauseWithNogroup(Sema &S,
12947                                             ArrayRef<OMPClause *> Clauses) {
12948   const OMPClause *ReductionClause = nullptr;
12949   const OMPClause *NogroupClause = nullptr;
12950   for (const OMPClause *C : Clauses) {
12951     if (C->getClauseKind() == OMPC_reduction) {
12952       ReductionClause = C;
12953       if (NogroupClause)
12954         break;
12955       continue;
12956     }
12957     if (C->getClauseKind() == OMPC_nogroup) {
12958       NogroupClause = C;
12959       if (ReductionClause)
12960         break;
12961       continue;
12962     }
12963   }
12964   if (ReductionClause && NogroupClause) {
12965     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
12966         << SourceRange(NogroupClause->getBeginLoc(),
12967                        NogroupClause->getEndLoc());
12968     return true;
12969   }
12970   return false;
12971 }
12972 
12973 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
12974     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12975     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12976   if (!AStmt)
12977     return StmtError();
12978 
12979   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12980   OMPLoopBasedDirective::HelperExprs B;
12981   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12982   // define the nested loops number.
12983   unsigned NestedLoopCount =
12984       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
12985                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12986                       VarsWithImplicitDSA, B);
12987   if (NestedLoopCount == 0)
12988     return StmtError();
12989 
12990   assert((CurContext->isDependentContext() || B.builtAll()) &&
12991          "omp for loop exprs were not built");
12992 
12993   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12994   // The grainsize clause and num_tasks clause are mutually exclusive and may
12995   // not appear on the same taskloop directive.
12996   if (checkMutuallyExclusiveClauses(*this, Clauses,
12997                                     {OMPC_grainsize, OMPC_num_tasks}))
12998     return StmtError();
12999   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13000   // If a reduction clause is present on the taskloop directive, the nogroup
13001   // clause must not be specified.
13002   if (checkReductionClauseWithNogroup(*this, Clauses))
13003     return StmtError();
13004 
13005   setFunctionHasBranchProtectedScope();
13006   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
13007                                       NestedLoopCount, Clauses, AStmt, B,
13008                                       DSAStack->isCancelRegion());
13009 }
13010 
13011 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
13012     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13013     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13014   if (!AStmt)
13015     return StmtError();
13016 
13017   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13018   OMPLoopBasedDirective::HelperExprs B;
13019   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13020   // define the nested loops number.
13021   unsigned NestedLoopCount =
13022       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
13023                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
13024                       VarsWithImplicitDSA, B);
13025   if (NestedLoopCount == 0)
13026     return StmtError();
13027 
13028   assert((CurContext->isDependentContext() || B.builtAll()) &&
13029          "omp for loop exprs were not built");
13030 
13031   if (!CurContext->isDependentContext()) {
13032     // Finalize the clauses that need pre-built expressions for CodeGen.
13033     for (OMPClause *C : Clauses) {
13034       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13035         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13036                                      B.NumIterations, *this, CurScope,
13037                                      DSAStack))
13038           return StmtError();
13039     }
13040   }
13041 
13042   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13043   // The grainsize clause and num_tasks clause are mutually exclusive and may
13044   // not appear on the same taskloop directive.
13045   if (checkMutuallyExclusiveClauses(*this, Clauses,
13046                                     {OMPC_grainsize, OMPC_num_tasks}))
13047     return StmtError();
13048   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13049   // If a reduction clause is present on the taskloop directive, the nogroup
13050   // clause must not be specified.
13051   if (checkReductionClauseWithNogroup(*this, Clauses))
13052     return StmtError();
13053   if (checkSimdlenSafelenSpecified(*this, Clauses))
13054     return StmtError();
13055 
13056   setFunctionHasBranchProtectedScope();
13057   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
13058                                           NestedLoopCount, Clauses, AStmt, B);
13059 }
13060 
13061 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
13062     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13063     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13064   if (!AStmt)
13065     return StmtError();
13066 
13067   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13068   OMPLoopBasedDirective::HelperExprs B;
13069   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13070   // define the nested loops number.
13071   unsigned NestedLoopCount =
13072       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
13073                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
13074                       VarsWithImplicitDSA, B);
13075   if (NestedLoopCount == 0)
13076     return StmtError();
13077 
13078   assert((CurContext->isDependentContext() || B.builtAll()) &&
13079          "omp for loop exprs were not built");
13080 
13081   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13082   // The grainsize clause and num_tasks clause are mutually exclusive and may
13083   // not appear on the same taskloop directive.
13084   if (checkMutuallyExclusiveClauses(*this, Clauses,
13085                                     {OMPC_grainsize, OMPC_num_tasks}))
13086     return StmtError();
13087   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13088   // If a reduction clause is present on the taskloop directive, the nogroup
13089   // clause must not be specified.
13090   if (checkReductionClauseWithNogroup(*this, Clauses))
13091     return StmtError();
13092 
13093   setFunctionHasBranchProtectedScope();
13094   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
13095                                             NestedLoopCount, Clauses, AStmt, B,
13096                                             DSAStack->isCancelRegion());
13097 }
13098 
13099 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
13100     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13101     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13102   if (!AStmt)
13103     return StmtError();
13104 
13105   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13106   OMPLoopBasedDirective::HelperExprs B;
13107   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13108   // define the nested loops number.
13109   unsigned NestedLoopCount =
13110       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
13111                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
13112                       VarsWithImplicitDSA, B);
13113   if (NestedLoopCount == 0)
13114     return StmtError();
13115 
13116   assert((CurContext->isDependentContext() || B.builtAll()) &&
13117          "omp for loop exprs were not built");
13118 
13119   if (!CurContext->isDependentContext()) {
13120     // Finalize the clauses that need pre-built expressions for CodeGen.
13121     for (OMPClause *C : Clauses) {
13122       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13123         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13124                                      B.NumIterations, *this, CurScope,
13125                                      DSAStack))
13126           return StmtError();
13127     }
13128   }
13129 
13130   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13131   // The grainsize clause and num_tasks clause are mutually exclusive and may
13132   // not appear on the same taskloop directive.
13133   if (checkMutuallyExclusiveClauses(*this, Clauses,
13134                                     {OMPC_grainsize, OMPC_num_tasks}))
13135     return StmtError();
13136   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13137   // If a reduction clause is present on the taskloop directive, the nogroup
13138   // clause must not be specified.
13139   if (checkReductionClauseWithNogroup(*this, Clauses))
13140     return StmtError();
13141   if (checkSimdlenSafelenSpecified(*this, Clauses))
13142     return StmtError();
13143 
13144   setFunctionHasBranchProtectedScope();
13145   return OMPMasterTaskLoopSimdDirective::Create(
13146       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13147 }
13148 
13149 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
13150     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13151     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13152   if (!AStmt)
13153     return StmtError();
13154 
13155   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13156   auto *CS = cast<CapturedStmt>(AStmt);
13157   // 1.2.2 OpenMP Language Terminology
13158   // Structured block - An executable statement with a single entry at the
13159   // top and a single exit at the bottom.
13160   // The point of exit cannot be a branch out of the structured block.
13161   // longjmp() and throw() must not violate the entry/exit criteria.
13162   CS->getCapturedDecl()->setNothrow();
13163   for (int ThisCaptureLevel =
13164            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
13165        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13166     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13167     // 1.2.2 OpenMP Language Terminology
13168     // Structured block - An executable statement with a single entry at the
13169     // top and a single exit at the bottom.
13170     // The point of exit cannot be a branch out of the structured block.
13171     // longjmp() and throw() must not violate the entry/exit criteria.
13172     CS->getCapturedDecl()->setNothrow();
13173   }
13174 
13175   OMPLoopBasedDirective::HelperExprs B;
13176   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13177   // define the nested loops number.
13178   unsigned NestedLoopCount = checkOpenMPLoop(
13179       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
13180       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
13181       VarsWithImplicitDSA, B);
13182   if (NestedLoopCount == 0)
13183     return StmtError();
13184 
13185   assert((CurContext->isDependentContext() || B.builtAll()) &&
13186          "omp for loop exprs were not built");
13187 
13188   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13189   // The grainsize clause and num_tasks clause are mutually exclusive and may
13190   // not appear on the same taskloop directive.
13191   if (checkMutuallyExclusiveClauses(*this, Clauses,
13192                                     {OMPC_grainsize, OMPC_num_tasks}))
13193     return StmtError();
13194   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13195   // If a reduction clause is present on the taskloop directive, the nogroup
13196   // clause must not be specified.
13197   if (checkReductionClauseWithNogroup(*this, Clauses))
13198     return StmtError();
13199 
13200   setFunctionHasBranchProtectedScope();
13201   return OMPParallelMasterTaskLoopDirective::Create(
13202       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13203       DSAStack->isCancelRegion());
13204 }
13205 
13206 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
13207     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13208     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13209   if (!AStmt)
13210     return StmtError();
13211 
13212   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13213   auto *CS = cast<CapturedStmt>(AStmt);
13214   // 1.2.2 OpenMP Language Terminology
13215   // Structured block - An executable statement with a single entry at the
13216   // top and a single exit at the bottom.
13217   // The point of exit cannot be a branch out of the structured block.
13218   // longjmp() and throw() must not violate the entry/exit criteria.
13219   CS->getCapturedDecl()->setNothrow();
13220   for (int ThisCaptureLevel =
13221            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
13222        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13223     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13224     // 1.2.2 OpenMP Language Terminology
13225     // Structured block - An executable statement with a single entry at the
13226     // top and a single exit at the bottom.
13227     // The point of exit cannot be a branch out of the structured block.
13228     // longjmp() and throw() must not violate the entry/exit criteria.
13229     CS->getCapturedDecl()->setNothrow();
13230   }
13231 
13232   OMPLoopBasedDirective::HelperExprs B;
13233   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13234   // define the nested loops number.
13235   unsigned NestedLoopCount = checkOpenMPLoop(
13236       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
13237       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
13238       VarsWithImplicitDSA, B);
13239   if (NestedLoopCount == 0)
13240     return StmtError();
13241 
13242   assert((CurContext->isDependentContext() || B.builtAll()) &&
13243          "omp for loop exprs were not built");
13244 
13245   if (!CurContext->isDependentContext()) {
13246     // Finalize the clauses that need pre-built expressions for CodeGen.
13247     for (OMPClause *C : Clauses) {
13248       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13249         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13250                                      B.NumIterations, *this, CurScope,
13251                                      DSAStack))
13252           return StmtError();
13253     }
13254   }
13255 
13256   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13257   // The grainsize clause and num_tasks clause are mutually exclusive and may
13258   // not appear on the same taskloop directive.
13259   if (checkMutuallyExclusiveClauses(*this, Clauses,
13260                                     {OMPC_grainsize, OMPC_num_tasks}))
13261     return StmtError();
13262   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
13263   // If a reduction clause is present on the taskloop directive, the nogroup
13264   // clause must not be specified.
13265   if (checkReductionClauseWithNogroup(*this, Clauses))
13266     return StmtError();
13267   if (checkSimdlenSafelenSpecified(*this, Clauses))
13268     return StmtError();
13269 
13270   setFunctionHasBranchProtectedScope();
13271   return OMPParallelMasterTaskLoopSimdDirective::Create(
13272       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13273 }
13274 
13275 StmtResult Sema::ActOnOpenMPDistributeDirective(
13276     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13277     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13278   if (!AStmt)
13279     return StmtError();
13280 
13281   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
13282   OMPLoopBasedDirective::HelperExprs B;
13283   // In presence of clause 'collapse' with number of loops, it will
13284   // define the nested loops number.
13285   unsigned NestedLoopCount =
13286       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
13287                       nullptr /*ordered not a clause on distribute*/, AStmt,
13288                       *this, *DSAStack, VarsWithImplicitDSA, B);
13289   if (NestedLoopCount == 0)
13290     return StmtError();
13291 
13292   assert((CurContext->isDependentContext() || B.builtAll()) &&
13293          "omp for loop exprs were not built");
13294 
13295   setFunctionHasBranchProtectedScope();
13296   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
13297                                         NestedLoopCount, Clauses, AStmt, B);
13298 }
13299 
13300 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
13301     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13302     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13303   if (!AStmt)
13304     return StmtError();
13305 
13306   auto *CS = cast<CapturedStmt>(AStmt);
13307   // 1.2.2 OpenMP Language Terminology
13308   // Structured block - An executable statement with a single entry at the
13309   // top and a single exit at the bottom.
13310   // The point of exit cannot be a branch out of the structured block.
13311   // longjmp() and throw() must not violate the entry/exit criteria.
13312   CS->getCapturedDecl()->setNothrow();
13313   for (int ThisCaptureLevel =
13314            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
13315        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13316     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13317     // 1.2.2 OpenMP Language Terminology
13318     // Structured block - An executable statement with a single entry at the
13319     // top and a single exit at the bottom.
13320     // The point of exit cannot be a branch out of the structured block.
13321     // longjmp() and throw() must not violate the entry/exit criteria.
13322     CS->getCapturedDecl()->setNothrow();
13323   }
13324 
13325   OMPLoopBasedDirective::HelperExprs B;
13326   // In presence of clause 'collapse' with number of loops, it will
13327   // define the nested loops number.
13328   unsigned NestedLoopCount = checkOpenMPLoop(
13329       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13330       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13331       VarsWithImplicitDSA, B);
13332   if (NestedLoopCount == 0)
13333     return StmtError();
13334 
13335   assert((CurContext->isDependentContext() || B.builtAll()) &&
13336          "omp for loop exprs were not built");
13337 
13338   setFunctionHasBranchProtectedScope();
13339   return OMPDistributeParallelForDirective::Create(
13340       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13341       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13342 }
13343 
13344 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
13345     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13346     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13347   if (!AStmt)
13348     return StmtError();
13349 
13350   auto *CS = cast<CapturedStmt>(AStmt);
13351   // 1.2.2 OpenMP Language Terminology
13352   // Structured block - An executable statement with a single entry at the
13353   // top and a single exit at the bottom.
13354   // The point of exit cannot be a branch out of the structured block.
13355   // longjmp() and throw() must not violate the entry/exit criteria.
13356   CS->getCapturedDecl()->setNothrow();
13357   for (int ThisCaptureLevel =
13358            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
13359        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13360     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13361     // 1.2.2 OpenMP Language Terminology
13362     // Structured block - An executable statement with a single entry at the
13363     // top and a single exit at the bottom.
13364     // The point of exit cannot be a branch out of the structured block.
13365     // longjmp() and throw() must not violate the entry/exit criteria.
13366     CS->getCapturedDecl()->setNothrow();
13367   }
13368 
13369   OMPLoopBasedDirective::HelperExprs B;
13370   // In presence of clause 'collapse' with number of loops, it will
13371   // define the nested loops number.
13372   unsigned NestedLoopCount = checkOpenMPLoop(
13373       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
13374       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13375       VarsWithImplicitDSA, B);
13376   if (NestedLoopCount == 0)
13377     return StmtError();
13378 
13379   assert((CurContext->isDependentContext() || B.builtAll()) &&
13380          "omp for loop exprs were not built");
13381 
13382   if (!CurContext->isDependentContext()) {
13383     // Finalize the clauses that need pre-built expressions for CodeGen.
13384     for (OMPClause *C : Clauses) {
13385       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13386         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13387                                      B.NumIterations, *this, CurScope,
13388                                      DSAStack))
13389           return StmtError();
13390     }
13391   }
13392 
13393   if (checkSimdlenSafelenSpecified(*this, Clauses))
13394     return StmtError();
13395 
13396   setFunctionHasBranchProtectedScope();
13397   return OMPDistributeParallelForSimdDirective::Create(
13398       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13399 }
13400 
13401 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
13402     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13403     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13404   if (!AStmt)
13405     return StmtError();
13406 
13407   auto *CS = cast<CapturedStmt>(AStmt);
13408   // 1.2.2 OpenMP Language Terminology
13409   // Structured block - An executable statement with a single entry at the
13410   // top and a single exit at the bottom.
13411   // The point of exit cannot be a branch out of the structured block.
13412   // longjmp() and throw() must not violate the entry/exit criteria.
13413   CS->getCapturedDecl()->setNothrow();
13414   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
13415        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13416     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13417     // 1.2.2 OpenMP Language Terminology
13418     // Structured block - An executable statement with a single entry at the
13419     // top and a single exit at the bottom.
13420     // The point of exit cannot be a branch out of the structured block.
13421     // longjmp() and throw() must not violate the entry/exit criteria.
13422     CS->getCapturedDecl()->setNothrow();
13423   }
13424 
13425   OMPLoopBasedDirective::HelperExprs B;
13426   // In presence of clause 'collapse' with number of loops, it will
13427   // define the nested loops number.
13428   unsigned NestedLoopCount =
13429       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
13430                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13431                       *DSAStack, VarsWithImplicitDSA, B);
13432   if (NestedLoopCount == 0)
13433     return StmtError();
13434 
13435   assert((CurContext->isDependentContext() || B.builtAll()) &&
13436          "omp for loop exprs were not built");
13437 
13438   if (!CurContext->isDependentContext()) {
13439     // Finalize the clauses that need pre-built expressions for CodeGen.
13440     for (OMPClause *C : Clauses) {
13441       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13442         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13443                                      B.NumIterations, *this, CurScope,
13444                                      DSAStack))
13445           return StmtError();
13446     }
13447   }
13448 
13449   if (checkSimdlenSafelenSpecified(*this, Clauses))
13450     return StmtError();
13451 
13452   setFunctionHasBranchProtectedScope();
13453   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
13454                                             NestedLoopCount, Clauses, AStmt, B);
13455 }
13456 
13457 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
13458     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13459     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13460   if (!AStmt)
13461     return StmtError();
13462 
13463   auto *CS = cast<CapturedStmt>(AStmt);
13464   // 1.2.2 OpenMP Language Terminology
13465   // Structured block - An executable statement with a single entry at the
13466   // top and a single exit at the bottom.
13467   // The point of exit cannot be a branch out of the structured block.
13468   // longjmp() and throw() must not violate the entry/exit criteria.
13469   CS->getCapturedDecl()->setNothrow();
13470   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
13471        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13472     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13473     // 1.2.2 OpenMP Language Terminology
13474     // Structured block - An executable statement with a single entry at the
13475     // top and a single exit at the bottom.
13476     // The point of exit cannot be a branch out of the structured block.
13477     // longjmp() and throw() must not violate the entry/exit criteria.
13478     CS->getCapturedDecl()->setNothrow();
13479   }
13480 
13481   OMPLoopBasedDirective::HelperExprs B;
13482   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
13483   // define the nested loops number.
13484   unsigned NestedLoopCount = checkOpenMPLoop(
13485       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
13486       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
13487       B);
13488   if (NestedLoopCount == 0)
13489     return StmtError();
13490 
13491   assert((CurContext->isDependentContext() || B.builtAll()) &&
13492          "omp target parallel for simd loop exprs were not built");
13493 
13494   if (!CurContext->isDependentContext()) {
13495     // Finalize the clauses that need pre-built expressions for CodeGen.
13496     for (OMPClause *C : Clauses) {
13497       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13498         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13499                                      B.NumIterations, *this, CurScope,
13500                                      DSAStack))
13501           return StmtError();
13502     }
13503   }
13504   if (checkSimdlenSafelenSpecified(*this, Clauses))
13505     return StmtError();
13506 
13507   setFunctionHasBranchProtectedScope();
13508   return OMPTargetParallelForSimdDirective::Create(
13509       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13510 }
13511 
13512 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
13513     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13514     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13515   if (!AStmt)
13516     return StmtError();
13517 
13518   auto *CS = cast<CapturedStmt>(AStmt);
13519   // 1.2.2 OpenMP Language Terminology
13520   // Structured block - An executable statement with a single entry at the
13521   // top and a single exit at the bottom.
13522   // The point of exit cannot be a branch out of the structured block.
13523   // longjmp() and throw() must not violate the entry/exit criteria.
13524   CS->getCapturedDecl()->setNothrow();
13525   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
13526        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13527     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13528     // 1.2.2 OpenMP Language Terminology
13529     // Structured block - An executable statement with a single entry at the
13530     // top and a single exit at the bottom.
13531     // The point of exit cannot be a branch out of the structured block.
13532     // longjmp() and throw() must not violate the entry/exit criteria.
13533     CS->getCapturedDecl()->setNothrow();
13534   }
13535 
13536   OMPLoopBasedDirective::HelperExprs B;
13537   // In presence of clause 'collapse' with number of loops, it will define the
13538   // nested loops number.
13539   unsigned NestedLoopCount =
13540       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
13541                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
13542                       VarsWithImplicitDSA, B);
13543   if (NestedLoopCount == 0)
13544     return StmtError();
13545 
13546   assert((CurContext->isDependentContext() || B.builtAll()) &&
13547          "omp target simd loop exprs were not built");
13548 
13549   if (!CurContext->isDependentContext()) {
13550     // Finalize the clauses that need pre-built expressions for CodeGen.
13551     for (OMPClause *C : Clauses) {
13552       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13553         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13554                                      B.NumIterations, *this, CurScope,
13555                                      DSAStack))
13556           return StmtError();
13557     }
13558   }
13559 
13560   if (checkSimdlenSafelenSpecified(*this, Clauses))
13561     return StmtError();
13562 
13563   setFunctionHasBranchProtectedScope();
13564   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
13565                                         NestedLoopCount, Clauses, AStmt, B);
13566 }
13567 
13568 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
13569     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13570     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13571   if (!AStmt)
13572     return StmtError();
13573 
13574   auto *CS = cast<CapturedStmt>(AStmt);
13575   // 1.2.2 OpenMP Language Terminology
13576   // Structured block - An executable statement with a single entry at the
13577   // top and a single exit at the bottom.
13578   // The point of exit cannot be a branch out of the structured block.
13579   // longjmp() and throw() must not violate the entry/exit criteria.
13580   CS->getCapturedDecl()->setNothrow();
13581   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
13582        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13583     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13584     // 1.2.2 OpenMP Language Terminology
13585     // Structured block - An executable statement with a single entry at the
13586     // top and a single exit at the bottom.
13587     // The point of exit cannot be a branch out of the structured block.
13588     // longjmp() and throw() must not violate the entry/exit criteria.
13589     CS->getCapturedDecl()->setNothrow();
13590   }
13591 
13592   OMPLoopBasedDirective::HelperExprs B;
13593   // In presence of clause 'collapse' with number of loops, it will
13594   // define the nested loops number.
13595   unsigned NestedLoopCount =
13596       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
13597                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13598                       *DSAStack, VarsWithImplicitDSA, B);
13599   if (NestedLoopCount == 0)
13600     return StmtError();
13601 
13602   assert((CurContext->isDependentContext() || B.builtAll()) &&
13603          "omp teams distribute loop exprs were not built");
13604 
13605   setFunctionHasBranchProtectedScope();
13606 
13607   DSAStack->setParentTeamsRegionLoc(StartLoc);
13608 
13609   return OMPTeamsDistributeDirective::Create(
13610       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13611 }
13612 
13613 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
13614     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13615     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13616   if (!AStmt)
13617     return StmtError();
13618 
13619   auto *CS = cast<CapturedStmt>(AStmt);
13620   // 1.2.2 OpenMP Language Terminology
13621   // Structured block - An executable statement with a single entry at the
13622   // top and a single exit at the bottom.
13623   // The point of exit cannot be a branch out of the structured block.
13624   // longjmp() and throw() must not violate the entry/exit criteria.
13625   CS->getCapturedDecl()->setNothrow();
13626   for (int ThisCaptureLevel =
13627            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
13628        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13629     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13630     // 1.2.2 OpenMP Language Terminology
13631     // Structured block - An executable statement with a single entry at the
13632     // top and a single exit at the bottom.
13633     // The point of exit cannot be a branch out of the structured block.
13634     // longjmp() and throw() must not violate the entry/exit criteria.
13635     CS->getCapturedDecl()->setNothrow();
13636   }
13637 
13638   OMPLoopBasedDirective::HelperExprs B;
13639   // In presence of clause 'collapse' with number of loops, it will
13640   // define the nested loops number.
13641   unsigned NestedLoopCount = checkOpenMPLoop(
13642       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
13643       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13644       VarsWithImplicitDSA, B);
13645 
13646   if (NestedLoopCount == 0)
13647     return StmtError();
13648 
13649   assert((CurContext->isDependentContext() || B.builtAll()) &&
13650          "omp teams distribute simd loop exprs were not built");
13651 
13652   if (!CurContext->isDependentContext()) {
13653     // Finalize the clauses that need pre-built expressions for CodeGen.
13654     for (OMPClause *C : Clauses) {
13655       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13656         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13657                                      B.NumIterations, *this, CurScope,
13658                                      DSAStack))
13659           return StmtError();
13660     }
13661   }
13662 
13663   if (checkSimdlenSafelenSpecified(*this, Clauses))
13664     return StmtError();
13665 
13666   setFunctionHasBranchProtectedScope();
13667 
13668   DSAStack->setParentTeamsRegionLoc(StartLoc);
13669 
13670   return OMPTeamsDistributeSimdDirective::Create(
13671       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13672 }
13673 
13674 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
13675     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13676     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13677   if (!AStmt)
13678     return StmtError();
13679 
13680   auto *CS = cast<CapturedStmt>(AStmt);
13681   // 1.2.2 OpenMP Language Terminology
13682   // Structured block - An executable statement with a single entry at the
13683   // top and a single exit at the bottom.
13684   // The point of exit cannot be a branch out of the structured block.
13685   // longjmp() and throw() must not violate the entry/exit criteria.
13686   CS->getCapturedDecl()->setNothrow();
13687 
13688   for (int ThisCaptureLevel =
13689            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
13690        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13691     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13692     // 1.2.2 OpenMP Language Terminology
13693     // Structured block - An executable statement with a single entry at the
13694     // top and a single exit at the bottom.
13695     // The point of exit cannot be a branch out of the structured block.
13696     // longjmp() and throw() must not violate the entry/exit criteria.
13697     CS->getCapturedDecl()->setNothrow();
13698   }
13699 
13700   OMPLoopBasedDirective::HelperExprs B;
13701   // In presence of clause 'collapse' with number of loops, it will
13702   // define the nested loops number.
13703   unsigned NestedLoopCount = checkOpenMPLoop(
13704       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
13705       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13706       VarsWithImplicitDSA, B);
13707 
13708   if (NestedLoopCount == 0)
13709     return StmtError();
13710 
13711   assert((CurContext->isDependentContext() || B.builtAll()) &&
13712          "omp for loop exprs were not built");
13713 
13714   if (!CurContext->isDependentContext()) {
13715     // Finalize the clauses that need pre-built expressions for CodeGen.
13716     for (OMPClause *C : Clauses) {
13717       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13718         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13719                                      B.NumIterations, *this, CurScope,
13720                                      DSAStack))
13721           return StmtError();
13722     }
13723   }
13724 
13725   if (checkSimdlenSafelenSpecified(*this, Clauses))
13726     return StmtError();
13727 
13728   setFunctionHasBranchProtectedScope();
13729 
13730   DSAStack->setParentTeamsRegionLoc(StartLoc);
13731 
13732   return OMPTeamsDistributeParallelForSimdDirective::Create(
13733       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13734 }
13735 
13736 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
13737     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13738     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13739   if (!AStmt)
13740     return StmtError();
13741 
13742   auto *CS = cast<CapturedStmt>(AStmt);
13743   // 1.2.2 OpenMP Language Terminology
13744   // Structured block - An executable statement with a single entry at the
13745   // top and a single exit at the bottom.
13746   // The point of exit cannot be a branch out of the structured block.
13747   // longjmp() and throw() must not violate the entry/exit criteria.
13748   CS->getCapturedDecl()->setNothrow();
13749 
13750   for (int ThisCaptureLevel =
13751            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
13752        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13753     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13754     // 1.2.2 OpenMP Language Terminology
13755     // Structured block - An executable statement with a single entry at the
13756     // top and a single exit at the bottom.
13757     // The point of exit cannot be a branch out of the structured block.
13758     // longjmp() and throw() must not violate the entry/exit criteria.
13759     CS->getCapturedDecl()->setNothrow();
13760   }
13761 
13762   OMPLoopBasedDirective::HelperExprs B;
13763   // In presence of clause 'collapse' with number of loops, it will
13764   // define the nested loops number.
13765   unsigned NestedLoopCount = checkOpenMPLoop(
13766       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13767       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13768       VarsWithImplicitDSA, B);
13769 
13770   if (NestedLoopCount == 0)
13771     return StmtError();
13772 
13773   assert((CurContext->isDependentContext() || B.builtAll()) &&
13774          "omp for loop exprs were not built");
13775 
13776   setFunctionHasBranchProtectedScope();
13777 
13778   DSAStack->setParentTeamsRegionLoc(StartLoc);
13779 
13780   return OMPTeamsDistributeParallelForDirective::Create(
13781       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13782       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13783 }
13784 
13785 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
13786                                                  Stmt *AStmt,
13787                                                  SourceLocation StartLoc,
13788                                                  SourceLocation EndLoc) {
13789   if (!AStmt)
13790     return StmtError();
13791 
13792   auto *CS = cast<CapturedStmt>(AStmt);
13793   // 1.2.2 OpenMP Language Terminology
13794   // Structured block - An executable statement with a single entry at the
13795   // top and a single exit at the bottom.
13796   // The point of exit cannot be a branch out of the structured block.
13797   // longjmp() and throw() must not violate the entry/exit criteria.
13798   CS->getCapturedDecl()->setNothrow();
13799 
13800   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
13801        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13802     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13803     // 1.2.2 OpenMP Language Terminology
13804     // Structured block - An executable statement with a single entry at the
13805     // top and a single exit at the bottom.
13806     // The point of exit cannot be a branch out of the structured block.
13807     // longjmp() and throw() must not violate the entry/exit criteria.
13808     CS->getCapturedDecl()->setNothrow();
13809   }
13810   setFunctionHasBranchProtectedScope();
13811 
13812   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
13813                                          AStmt);
13814 }
13815 
13816 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
13817     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13818     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13819   if (!AStmt)
13820     return StmtError();
13821 
13822   auto *CS = cast<CapturedStmt>(AStmt);
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   for (int ThisCaptureLevel =
13830            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
13831        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13832     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13833     // 1.2.2 OpenMP Language Terminology
13834     // Structured block - An executable statement with a single entry at the
13835     // top and a single exit at the bottom.
13836     // The point of exit cannot be a branch out of the structured block.
13837     // longjmp() and throw() must not violate the entry/exit criteria.
13838     CS->getCapturedDecl()->setNothrow();
13839   }
13840 
13841   OMPLoopBasedDirective::HelperExprs B;
13842   // In presence of clause 'collapse' with number of loops, it will
13843   // define the nested loops number.
13844   unsigned NestedLoopCount = checkOpenMPLoop(
13845       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
13846       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13847       VarsWithImplicitDSA, B);
13848   if (NestedLoopCount == 0)
13849     return StmtError();
13850 
13851   assert((CurContext->isDependentContext() || B.builtAll()) &&
13852          "omp target teams distribute loop exprs were not built");
13853 
13854   setFunctionHasBranchProtectedScope();
13855   return OMPTargetTeamsDistributeDirective::Create(
13856       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13857 }
13858 
13859 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
13860     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13861     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13862   if (!AStmt)
13863     return StmtError();
13864 
13865   auto *CS = cast<CapturedStmt>(AStmt);
13866   // 1.2.2 OpenMP Language Terminology
13867   // Structured block - An executable statement with a single entry at the
13868   // top and a single exit at the bottom.
13869   // The point of exit cannot be a branch out of the structured block.
13870   // longjmp() and throw() must not violate the entry/exit criteria.
13871   CS->getCapturedDecl()->setNothrow();
13872   for (int ThisCaptureLevel =
13873            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
13874        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13875     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13876     // 1.2.2 OpenMP Language Terminology
13877     // Structured block - An executable statement with a single entry at the
13878     // top and a single exit at the bottom.
13879     // The point of exit cannot be a branch out of the structured block.
13880     // longjmp() and throw() must not violate the entry/exit criteria.
13881     CS->getCapturedDecl()->setNothrow();
13882   }
13883 
13884   OMPLoopBasedDirective::HelperExprs B;
13885   // In presence of clause 'collapse' with number of loops, it will
13886   // define the nested loops number.
13887   unsigned NestedLoopCount = checkOpenMPLoop(
13888       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13889       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13890       VarsWithImplicitDSA, B);
13891   if (NestedLoopCount == 0)
13892     return StmtError();
13893 
13894   assert((CurContext->isDependentContext() || B.builtAll()) &&
13895          "omp target teams distribute parallel for loop exprs were not built");
13896 
13897   if (!CurContext->isDependentContext()) {
13898     // Finalize the clauses that need pre-built expressions for CodeGen.
13899     for (OMPClause *C : Clauses) {
13900       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13901         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13902                                      B.NumIterations, *this, CurScope,
13903                                      DSAStack))
13904           return StmtError();
13905     }
13906   }
13907 
13908   setFunctionHasBranchProtectedScope();
13909   return OMPTargetTeamsDistributeParallelForDirective::Create(
13910       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13911       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13912 }
13913 
13914 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
13915     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13916     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13917   if (!AStmt)
13918     return StmtError();
13919 
13920   auto *CS = cast<CapturedStmt>(AStmt);
13921   // 1.2.2 OpenMP Language Terminology
13922   // Structured block - An executable statement with a single entry at the
13923   // top and a single exit at the bottom.
13924   // The point of exit cannot be a branch out of the structured block.
13925   // longjmp() and throw() must not violate the entry/exit criteria.
13926   CS->getCapturedDecl()->setNothrow();
13927   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
13928            OMPD_target_teams_distribute_parallel_for_simd);
13929        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13930     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13931     // 1.2.2 OpenMP Language Terminology
13932     // Structured block - An executable statement with a single entry at the
13933     // top and a single exit at the bottom.
13934     // The point of exit cannot be a branch out of the structured block.
13935     // longjmp() and throw() must not violate the entry/exit criteria.
13936     CS->getCapturedDecl()->setNothrow();
13937   }
13938 
13939   OMPLoopBasedDirective::HelperExprs B;
13940   // In presence of clause 'collapse' with number of loops, it will
13941   // define the nested loops number.
13942   unsigned NestedLoopCount =
13943       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
13944                       getCollapseNumberExpr(Clauses),
13945                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13946                       *DSAStack, VarsWithImplicitDSA, B);
13947   if (NestedLoopCount == 0)
13948     return StmtError();
13949 
13950   assert((CurContext->isDependentContext() || B.builtAll()) &&
13951          "omp target teams distribute parallel for simd loop exprs were not "
13952          "built");
13953 
13954   if (!CurContext->isDependentContext()) {
13955     // Finalize the clauses that need pre-built expressions for CodeGen.
13956     for (OMPClause *C : Clauses) {
13957       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13958         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13959                                      B.NumIterations, *this, CurScope,
13960                                      DSAStack))
13961           return StmtError();
13962     }
13963   }
13964 
13965   if (checkSimdlenSafelenSpecified(*this, Clauses))
13966     return StmtError();
13967 
13968   setFunctionHasBranchProtectedScope();
13969   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
13970       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13971 }
13972 
13973 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
13974     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13975     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13976   if (!AStmt)
13977     return StmtError();
13978 
13979   auto *CS = cast<CapturedStmt>(AStmt);
13980   // 1.2.2 OpenMP Language Terminology
13981   // Structured block - An executable statement with a single entry at the
13982   // top and a single exit at the bottom.
13983   // The point of exit cannot be a branch out of the structured block.
13984   // longjmp() and throw() must not violate the entry/exit criteria.
13985   CS->getCapturedDecl()->setNothrow();
13986   for (int ThisCaptureLevel =
13987            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
13988        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13989     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13990     // 1.2.2 OpenMP Language Terminology
13991     // Structured block - An executable statement with a single entry at the
13992     // top and a single exit at the bottom.
13993     // The point of exit cannot be a branch out of the structured block.
13994     // longjmp() and throw() must not violate the entry/exit criteria.
13995     CS->getCapturedDecl()->setNothrow();
13996   }
13997 
13998   OMPLoopBasedDirective::HelperExprs B;
13999   // In presence of clause 'collapse' with number of loops, it will
14000   // define the nested loops number.
14001   unsigned NestedLoopCount = checkOpenMPLoop(
14002       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
14003       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
14004       VarsWithImplicitDSA, B);
14005   if (NestedLoopCount == 0)
14006     return StmtError();
14007 
14008   assert((CurContext->isDependentContext() || B.builtAll()) &&
14009          "omp target teams distribute simd loop exprs were not built");
14010 
14011   if (!CurContext->isDependentContext()) {
14012     // Finalize the clauses that need pre-built expressions for CodeGen.
14013     for (OMPClause *C : Clauses) {
14014       if (auto *LC = dyn_cast<OMPLinearClause>(C))
14015         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
14016                                      B.NumIterations, *this, CurScope,
14017                                      DSAStack))
14018           return StmtError();
14019     }
14020   }
14021 
14022   if (checkSimdlenSafelenSpecified(*this, Clauses))
14023     return StmtError();
14024 
14025   setFunctionHasBranchProtectedScope();
14026   return OMPTargetTeamsDistributeSimdDirective::Create(
14027       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
14028 }
14029 
14030 bool Sema::checkTransformableLoopNest(
14031     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
14032     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
14033     Stmt *&Body,
14034     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
14035         &OriginalInits) {
14036   OriginalInits.emplace_back();
14037   bool Result = OMPLoopBasedDirective::doForAllLoops(
14038       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
14039       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
14040                                                         Stmt *CurStmt) {
14041         VarsWithInheritedDSAType TmpDSA;
14042         unsigned SingleNumLoops =
14043             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
14044                             TmpDSA, LoopHelpers[Cnt]);
14045         if (SingleNumLoops == 0)
14046           return true;
14047         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
14048         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
14049           OriginalInits.back().push_back(For->getInit());
14050           Body = For->getBody();
14051         } else {
14052           assert(isa<CXXForRangeStmt>(CurStmt) &&
14053                  "Expected canonical for or range-based for loops.");
14054           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
14055           OriginalInits.back().push_back(CXXFor->getBeginStmt());
14056           Body = CXXFor->getBody();
14057         }
14058         OriginalInits.emplace_back();
14059         return false;
14060       },
14061       [&OriginalInits](OMPLoopBasedDirective *Transform) {
14062         Stmt *DependentPreInits;
14063         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
14064           DependentPreInits = Dir->getPreInits();
14065         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
14066           DependentPreInits = Dir->getPreInits();
14067         else
14068           llvm_unreachable("Unhandled loop transformation");
14069         if (!DependentPreInits)
14070           return;
14071         llvm::append_range(OriginalInits.back(),
14072                            cast<DeclStmt>(DependentPreInits)->getDeclGroup());
14073       });
14074   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
14075   OriginalInits.pop_back();
14076   return Result;
14077 }
14078 
14079 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
14080                                           Stmt *AStmt, SourceLocation StartLoc,
14081                                           SourceLocation EndLoc) {
14082   auto SizesClauses =
14083       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
14084   if (SizesClauses.empty()) {
14085     // A missing 'sizes' clause is already reported by the parser.
14086     return StmtError();
14087   }
14088   const OMPSizesClause *SizesClause = *SizesClauses.begin();
14089   unsigned NumLoops = SizesClause->getNumSizes();
14090 
14091   // Empty statement should only be possible if there already was an error.
14092   if (!AStmt)
14093     return StmtError();
14094 
14095   // Verify and diagnose loop nest.
14096   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
14097   Stmt *Body = nullptr;
14098   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
14099       OriginalInits;
14100   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
14101                                   OriginalInits))
14102     return StmtError();
14103 
14104   // Delay tiling to when template is completely instantiated.
14105   if (CurContext->isDependentContext())
14106     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
14107                                     NumLoops, AStmt, nullptr, nullptr);
14108 
14109   SmallVector<Decl *, 4> PreInits;
14110 
14111   // Create iteration variables for the generated loops.
14112   SmallVector<VarDecl *, 4> FloorIndVars;
14113   SmallVector<VarDecl *, 4> TileIndVars;
14114   FloorIndVars.resize(NumLoops);
14115   TileIndVars.resize(NumLoops);
14116   for (unsigned I = 0; I < NumLoops; ++I) {
14117     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
14118 
14119     assert(LoopHelper.Counters.size() == 1 &&
14120            "Expect single-dimensional loop iteration space");
14121     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
14122     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
14123     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
14124     QualType CntTy = IterVarRef->getType();
14125 
14126     // Iteration variable for the floor (i.e. outer) loop.
14127     {
14128       std::string FloorCntName =
14129           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
14130       VarDecl *FloorCntDecl =
14131           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
14132       FloorIndVars[I] = FloorCntDecl;
14133     }
14134 
14135     // Iteration variable for the tile (i.e. inner) loop.
14136     {
14137       std::string TileCntName =
14138           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
14139 
14140       // Reuse the iteration variable created by checkOpenMPLoop. It is also
14141       // used by the expressions to derive the original iteration variable's
14142       // value from the logical iteration number.
14143       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
14144       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
14145       TileIndVars[I] = TileCntDecl;
14146     }
14147     for (auto &P : OriginalInits[I]) {
14148       if (auto *D = P.dyn_cast<Decl *>())
14149         PreInits.push_back(D);
14150       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
14151         PreInits.append(PI->decl_begin(), PI->decl_end());
14152     }
14153     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
14154       PreInits.append(PI->decl_begin(), PI->decl_end());
14155     // Gather declarations for the data members used as counters.
14156     for (Expr *CounterRef : LoopHelper.Counters) {
14157       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
14158       if (isa<OMPCapturedExprDecl>(CounterDecl))
14159         PreInits.push_back(CounterDecl);
14160     }
14161   }
14162 
14163   // Once the original iteration values are set, append the innermost body.
14164   Stmt *Inner = Body;
14165 
14166   // Create tile loops from the inside to the outside.
14167   for (int I = NumLoops - 1; I >= 0; --I) {
14168     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
14169     Expr *NumIterations = LoopHelper.NumIterations;
14170     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
14171     QualType CntTy = OrigCntVar->getType();
14172     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
14173     Scope *CurScope = getCurScope();
14174 
14175     // Commonly used variables.
14176     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
14177                                            OrigCntVar->getExprLoc());
14178     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
14179                                             OrigCntVar->getExprLoc());
14180 
14181     // For init-statement: auto .tile.iv = .floor.iv
14182     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
14183                          /*DirectInit=*/false);
14184     Decl *CounterDecl = TileIndVars[I];
14185     StmtResult InitStmt = new (Context)
14186         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
14187                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
14188     if (!InitStmt.isUsable())
14189       return StmtError();
14190 
14191     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
14192     // NumIterations)
14193     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14194                                       BO_Add, FloorIV, DimTileSize);
14195     if (!EndOfTile.isUsable())
14196       return StmtError();
14197     ExprResult IsPartialTile =
14198         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
14199                    NumIterations, EndOfTile.get());
14200     if (!IsPartialTile.isUsable())
14201       return StmtError();
14202     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
14203         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
14204         IsPartialTile.get(), NumIterations, EndOfTile.get());
14205     if (!MinTileAndIterSpace.isUsable())
14206       return StmtError();
14207     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14208                                      BO_LT, TileIV, MinTileAndIterSpace.get());
14209     if (!CondExpr.isUsable())
14210       return StmtError();
14211 
14212     // For incr-statement: ++.tile.iv
14213     ExprResult IncrStmt =
14214         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
14215     if (!IncrStmt.isUsable())
14216       return StmtError();
14217 
14218     // Statements to set the original iteration variable's value from the
14219     // logical iteration number.
14220     // Generated for loop is:
14221     // Original_for_init;
14222     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
14223     // NumIterations); ++.tile.iv) {
14224     //   Original_Body;
14225     //   Original_counter_update;
14226     // }
14227     // FIXME: If the innermost body is an loop itself, inserting these
14228     // statements stops it being recognized  as a perfectly nested loop (e.g.
14229     // for applying tiling again). If this is the case, sink the expressions
14230     // further into the inner loop.
14231     SmallVector<Stmt *, 4> BodyParts;
14232     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
14233     BodyParts.push_back(Inner);
14234     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
14235                                  Inner->getEndLoc());
14236     Inner = new (Context)
14237         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
14238                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
14239                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14240   }
14241 
14242   // Create floor loops from the inside to the outside.
14243   for (int I = NumLoops - 1; I >= 0; --I) {
14244     auto &LoopHelper = LoopHelpers[I];
14245     Expr *NumIterations = LoopHelper.NumIterations;
14246     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
14247     QualType CntTy = OrigCntVar->getType();
14248     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
14249     Scope *CurScope = getCurScope();
14250 
14251     // Commonly used variables.
14252     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
14253                                             OrigCntVar->getExprLoc());
14254 
14255     // For init-statement: auto .floor.iv = 0
14256     AddInitializerToDecl(
14257         FloorIndVars[I],
14258         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
14259         /*DirectInit=*/false);
14260     Decl *CounterDecl = FloorIndVars[I];
14261     StmtResult InitStmt = new (Context)
14262         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
14263                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
14264     if (!InitStmt.isUsable())
14265       return StmtError();
14266 
14267     // For cond-expression: .floor.iv < NumIterations
14268     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14269                                      BO_LT, FloorIV, NumIterations);
14270     if (!CondExpr.isUsable())
14271       return StmtError();
14272 
14273     // For incr-statement: .floor.iv += DimTileSize
14274     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
14275                                      BO_AddAssign, FloorIV, DimTileSize);
14276     if (!IncrStmt.isUsable())
14277       return StmtError();
14278 
14279     Inner = new (Context)
14280         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
14281                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
14282                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14283   }
14284 
14285   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
14286                                   AStmt, Inner,
14287                                   buildPreInits(Context, PreInits));
14288 }
14289 
14290 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
14291                                             Stmt *AStmt,
14292                                             SourceLocation StartLoc,
14293                                             SourceLocation EndLoc) {
14294   // Empty statement should only be possible if there already was an error.
14295   if (!AStmt)
14296     return StmtError();
14297 
14298   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
14299     return StmtError();
14300 
14301   const OMPFullClause *FullClause =
14302       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
14303   const OMPPartialClause *PartialClause =
14304       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
14305   assert(!(FullClause && PartialClause) &&
14306          "mutual exclusivity must have been checked before");
14307 
14308   constexpr unsigned NumLoops = 1;
14309   Stmt *Body = nullptr;
14310   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
14311       NumLoops);
14312   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
14313       OriginalInits;
14314   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
14315                                   Body, OriginalInits))
14316     return StmtError();
14317 
14318   unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
14319 
14320   // Delay unrolling to when template is completely instantiated.
14321   if (CurContext->isDependentContext())
14322     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
14323                                       NumGeneratedLoops, nullptr, nullptr);
14324 
14325   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
14326 
14327   if (FullClause) {
14328     if (!VerifyPositiveIntegerConstantInClause(
14329              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
14330              /*SuppressExprDiags=*/true)
14331              .isUsable()) {
14332       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
14333       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
14334           << "#pragma omp unroll full";
14335       return StmtError();
14336     }
14337   }
14338 
14339   // The generated loop may only be passed to other loop-associated directive
14340   // when a partial clause is specified. Without the requirement it is
14341   // sufficient to generate loop unroll metadata at code-generation.
14342   if (NumGeneratedLoops == 0)
14343     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
14344                                       NumGeneratedLoops, nullptr, nullptr);
14345 
14346   // Otherwise, we need to provide a de-sugared/transformed AST that can be
14347   // associated with another loop directive.
14348   //
14349   // The canonical loop analysis return by checkTransformableLoopNest assumes
14350   // the following structure to be the same loop without transformations or
14351   // directives applied: \code OriginalInits; LoopHelper.PreInits;
14352   // LoopHelper.Counters;
14353   // for (; IV < LoopHelper.NumIterations; ++IV) {
14354   //   LoopHelper.Updates;
14355   //   Body;
14356   // }
14357   // \endcode
14358   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
14359   // and referenced by LoopHelper.IterationVarRef.
14360   //
14361   // The unrolling directive transforms this into the following loop:
14362   // \code
14363   // OriginalInits;         \
14364   // LoopHelper.PreInits;    > NewPreInits
14365   // LoopHelper.Counters;   /
14366   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
14367   //   #pragma clang loop unroll_count(Factor)
14368   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
14369   //   {
14370   //     LoopHelper.Updates;
14371   //     Body;
14372   //   }
14373   // }
14374   // \endcode
14375   // where UIV is a new logical iteration counter. IV must be the same VarDecl
14376   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
14377   // references it. If the partially unrolled loop is associated with another
14378   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
14379   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
14380   // OpenMP canonical loop. The inner loop is not an associable canonical loop
14381   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
14382   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
14383   // property of the OMPLoopBasedDirective instead of statements in
14384   // CompoundStatement. This is to allow the loop to become a non-outermost loop
14385   // of a canonical loop nest where these PreInits are emitted before the
14386   // outermost directive.
14387 
14388   // Determine the PreInit declarations.
14389   SmallVector<Decl *, 4> PreInits;
14390   assert(OriginalInits.size() == 1 &&
14391          "Expecting a single-dimensional loop iteration space");
14392   for (auto &P : OriginalInits[0]) {
14393     if (auto *D = P.dyn_cast<Decl *>())
14394       PreInits.push_back(D);
14395     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
14396       PreInits.append(PI->decl_begin(), PI->decl_end());
14397   }
14398   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
14399     PreInits.append(PI->decl_begin(), PI->decl_end());
14400   // Gather declarations for the data members used as counters.
14401   for (Expr *CounterRef : LoopHelper.Counters) {
14402     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
14403     if (isa<OMPCapturedExprDecl>(CounterDecl))
14404       PreInits.push_back(CounterDecl);
14405   }
14406 
14407   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
14408   QualType IVTy = IterationVarRef->getType();
14409   assert(LoopHelper.Counters.size() == 1 &&
14410          "Expecting a single-dimensional loop iteration space");
14411   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
14412 
14413   // Determine the unroll factor.
14414   uint64_t Factor;
14415   SourceLocation FactorLoc;
14416   if (Expr *FactorVal = PartialClause->getFactor()) {
14417     Factor =
14418         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
14419     FactorLoc = FactorVal->getExprLoc();
14420   } else {
14421     // TODO: Use a better profitability model.
14422     Factor = 2;
14423   }
14424   assert(Factor > 0 && "Expected positive unroll factor");
14425   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
14426     return IntegerLiteral::Create(
14427         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
14428         FactorLoc);
14429   };
14430 
14431   // Iteration variable SourceLocations.
14432   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
14433   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
14434   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
14435 
14436   // Internal variable names.
14437   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
14438   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
14439   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
14440   std::string InnerTripCountName =
14441       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
14442 
14443   // Create the iteration variable for the unrolled loop.
14444   VarDecl *OuterIVDecl =
14445       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
14446   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
14447     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
14448   };
14449 
14450   // Iteration variable for the inner loop: Reuse the iteration variable created
14451   // by checkOpenMPLoop.
14452   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
14453   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
14454   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
14455     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
14456   };
14457 
14458   // Make a copy of the NumIterations expression for each use: By the AST
14459   // constraints, every expression object in a DeclContext must be unique.
14460   CaptureVars CopyTransformer(*this);
14461   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
14462     return AssertSuccess(
14463         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
14464   };
14465 
14466   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
14467   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
14468   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
14469   StmtResult InnerInit = new (Context)
14470       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
14471   if (!InnerInit.isUsable())
14472     return StmtError();
14473 
14474   // Inner For cond-expression:
14475   // \code
14476   //   .unroll_inner.iv < .unrolled.iv + Factor &&
14477   //   .unroll_inner.iv < NumIterations
14478   // \endcode
14479   // This conjunction of two conditions allows ScalarEvolution to derive the
14480   // maximum trip count of the inner loop.
14481   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14482                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
14483   if (!EndOfTile.isUsable())
14484     return StmtError();
14485   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
14486                                      BO_LE, MakeInnerRef(), EndOfTile.get());
14487   if (!InnerCond1.isUsable())
14488     return StmtError();
14489   ExprResult InnerCond2 =
14490       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
14491                  MakeNumIterations());
14492   if (!InnerCond2.isUsable())
14493     return StmtError();
14494   ExprResult InnerCond =
14495       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
14496                  InnerCond1.get(), InnerCond2.get());
14497   if (!InnerCond.isUsable())
14498     return StmtError();
14499 
14500   // Inner For incr-statement: ++.unroll_inner.iv
14501   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
14502                                       UO_PreInc, MakeInnerRef());
14503   if (!InnerIncr.isUsable())
14504     return StmtError();
14505 
14506   // Inner For statement.
14507   SmallVector<Stmt *> InnerBodyStmts;
14508   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
14509   InnerBodyStmts.push_back(Body);
14510   CompoundStmt *InnerBody = CompoundStmt::Create(
14511       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
14512   ForStmt *InnerFor = new (Context)
14513       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
14514               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
14515               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14516 
14517   // Unroll metadata for the inner loop.
14518   // This needs to take into account the remainder portion of the unrolled loop,
14519   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
14520   // supports multiple loop exits. Instead, unroll using a factor equivalent to
14521   // the maximum trip count, which will also generate a remainder loop. Just
14522   // `unroll(enable)` (which could have been useful if the user has not
14523   // specified a concrete factor; even though the outer loop cannot be
14524   // influenced anymore, would avoid more code bloat than necessary) will refuse
14525   // the loop because "Won't unroll; remainder loop could not be generated when
14526   // assuming runtime trip count". Even if it did work, it must not choose a
14527   // larger unroll factor than the maximum loop length, or it would always just
14528   // execute the remainder loop.
14529   LoopHintAttr *UnrollHintAttr =
14530       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
14531                                    LoopHintAttr::Numeric, MakeFactorExpr());
14532   AttributedStmt *InnerUnrolled =
14533       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
14534 
14535   // Outer For init-statement: auto .unrolled.iv = 0
14536   AddInitializerToDecl(
14537       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
14538       /*DirectInit=*/false);
14539   StmtResult OuterInit = new (Context)
14540       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
14541   if (!OuterInit.isUsable())
14542     return StmtError();
14543 
14544   // Outer For cond-expression: .unrolled.iv < NumIterations
14545   ExprResult OuterConde =
14546       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
14547                  MakeNumIterations());
14548   if (!OuterConde.isUsable())
14549     return StmtError();
14550 
14551   // Outer For incr-statement: .unrolled.iv += Factor
14552   ExprResult OuterIncr =
14553       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
14554                  MakeOuterRef(), MakeFactorExpr());
14555   if (!OuterIncr.isUsable())
14556     return StmtError();
14557 
14558   // Outer For statement.
14559   ForStmt *OuterFor = new (Context)
14560       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
14561               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
14562               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
14563 
14564   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
14565                                     NumGeneratedLoops, OuterFor,
14566                                     buildPreInits(Context, PreInits));
14567 }
14568 
14569 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
14570                                              SourceLocation StartLoc,
14571                                              SourceLocation LParenLoc,
14572                                              SourceLocation EndLoc) {
14573   OMPClause *Res = nullptr;
14574   switch (Kind) {
14575   case OMPC_final:
14576     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
14577     break;
14578   case OMPC_num_threads:
14579     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
14580     break;
14581   case OMPC_safelen:
14582     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
14583     break;
14584   case OMPC_simdlen:
14585     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
14586     break;
14587   case OMPC_allocator:
14588     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
14589     break;
14590   case OMPC_collapse:
14591     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
14592     break;
14593   case OMPC_ordered:
14594     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
14595     break;
14596   case OMPC_num_teams:
14597     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
14598     break;
14599   case OMPC_thread_limit:
14600     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
14601     break;
14602   case OMPC_priority:
14603     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
14604     break;
14605   case OMPC_grainsize:
14606     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
14607     break;
14608   case OMPC_num_tasks:
14609     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
14610     break;
14611   case OMPC_hint:
14612     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
14613     break;
14614   case OMPC_depobj:
14615     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
14616     break;
14617   case OMPC_detach:
14618     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
14619     break;
14620   case OMPC_novariants:
14621     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
14622     break;
14623   case OMPC_nocontext:
14624     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
14625     break;
14626   case OMPC_filter:
14627     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
14628     break;
14629   case OMPC_partial:
14630     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
14631     break;
14632   case OMPC_align:
14633     Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
14634     break;
14635   case OMPC_device:
14636   case OMPC_if:
14637   case OMPC_default:
14638   case OMPC_proc_bind:
14639   case OMPC_schedule:
14640   case OMPC_private:
14641   case OMPC_firstprivate:
14642   case OMPC_lastprivate:
14643   case OMPC_shared:
14644   case OMPC_reduction:
14645   case OMPC_task_reduction:
14646   case OMPC_in_reduction:
14647   case OMPC_linear:
14648   case OMPC_aligned:
14649   case OMPC_copyin:
14650   case OMPC_copyprivate:
14651   case OMPC_nowait:
14652   case OMPC_untied:
14653   case OMPC_mergeable:
14654   case OMPC_threadprivate:
14655   case OMPC_sizes:
14656   case OMPC_allocate:
14657   case OMPC_flush:
14658   case OMPC_read:
14659   case OMPC_write:
14660   case OMPC_update:
14661   case OMPC_capture:
14662   case OMPC_compare:
14663   case OMPC_seq_cst:
14664   case OMPC_acq_rel:
14665   case OMPC_acquire:
14666   case OMPC_release:
14667   case OMPC_relaxed:
14668   case OMPC_depend:
14669   case OMPC_threads:
14670   case OMPC_simd:
14671   case OMPC_map:
14672   case OMPC_nogroup:
14673   case OMPC_dist_schedule:
14674   case OMPC_defaultmap:
14675   case OMPC_unknown:
14676   case OMPC_uniform:
14677   case OMPC_to:
14678   case OMPC_from:
14679   case OMPC_use_device_ptr:
14680   case OMPC_use_device_addr:
14681   case OMPC_is_device_ptr:
14682   case OMPC_unified_address:
14683   case OMPC_unified_shared_memory:
14684   case OMPC_reverse_offload:
14685   case OMPC_dynamic_allocators:
14686   case OMPC_atomic_default_mem_order:
14687   case OMPC_device_type:
14688   case OMPC_match:
14689   case OMPC_nontemporal:
14690   case OMPC_order:
14691   case OMPC_destroy:
14692   case OMPC_inclusive:
14693   case OMPC_exclusive:
14694   case OMPC_uses_allocators:
14695   case OMPC_affinity:
14696   case OMPC_when:
14697   case OMPC_bind:
14698   default:
14699     llvm_unreachable("Clause is not allowed.");
14700   }
14701   return Res;
14702 }
14703 
14704 // An OpenMP directive such as 'target parallel' has two captured regions:
14705 // for the 'target' and 'parallel' respectively.  This function returns
14706 // the region in which to capture expressions associated with a clause.
14707 // A return value of OMPD_unknown signifies that the expression should not
14708 // be captured.
14709 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
14710     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
14711     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
14712   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14713   switch (CKind) {
14714   case OMPC_if:
14715     switch (DKind) {
14716     case OMPD_target_parallel_for_simd:
14717       if (OpenMPVersion >= 50 &&
14718           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
14719         CaptureRegion = OMPD_parallel;
14720         break;
14721       }
14722       LLVM_FALLTHROUGH;
14723     case OMPD_target_parallel:
14724     case OMPD_target_parallel_for:
14725     case OMPD_target_parallel_loop:
14726       // If this clause applies to the nested 'parallel' region, capture within
14727       // the 'target' region, otherwise do not capture.
14728       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
14729         CaptureRegion = OMPD_target;
14730       break;
14731     case OMPD_target_teams_distribute_parallel_for_simd:
14732       if (OpenMPVersion >= 50 &&
14733           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
14734         CaptureRegion = OMPD_parallel;
14735         break;
14736       }
14737       LLVM_FALLTHROUGH;
14738     case OMPD_target_teams_distribute_parallel_for:
14739       // If this clause applies to the nested 'parallel' region, capture within
14740       // the 'teams' region, otherwise do not capture.
14741       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
14742         CaptureRegion = OMPD_teams;
14743       break;
14744     case OMPD_teams_distribute_parallel_for_simd:
14745       if (OpenMPVersion >= 50 &&
14746           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
14747         CaptureRegion = OMPD_parallel;
14748         break;
14749       }
14750       LLVM_FALLTHROUGH;
14751     case OMPD_teams_distribute_parallel_for:
14752       CaptureRegion = OMPD_teams;
14753       break;
14754     case OMPD_target_update:
14755     case OMPD_target_enter_data:
14756     case OMPD_target_exit_data:
14757       CaptureRegion = OMPD_task;
14758       break;
14759     case OMPD_parallel_master_taskloop:
14760       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
14761         CaptureRegion = OMPD_parallel;
14762       break;
14763     case OMPD_parallel_master_taskloop_simd:
14764       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
14765           NameModifier == OMPD_taskloop) {
14766         CaptureRegion = OMPD_parallel;
14767         break;
14768       }
14769       if (OpenMPVersion <= 45)
14770         break;
14771       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14772         CaptureRegion = OMPD_taskloop;
14773       break;
14774     case OMPD_parallel_for_simd:
14775       if (OpenMPVersion <= 45)
14776         break;
14777       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14778         CaptureRegion = OMPD_parallel;
14779       break;
14780     case OMPD_taskloop_simd:
14781     case OMPD_master_taskloop_simd:
14782       if (OpenMPVersion <= 45)
14783         break;
14784       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14785         CaptureRegion = OMPD_taskloop;
14786       break;
14787     case OMPD_distribute_parallel_for_simd:
14788       if (OpenMPVersion <= 45)
14789         break;
14790       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
14791         CaptureRegion = OMPD_parallel;
14792       break;
14793     case OMPD_target_simd:
14794       if (OpenMPVersion >= 50 &&
14795           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
14796         CaptureRegion = OMPD_target;
14797       break;
14798     case OMPD_teams_distribute_simd:
14799     case OMPD_target_teams_distribute_simd:
14800       if (OpenMPVersion >= 50 &&
14801           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
14802         CaptureRegion = OMPD_teams;
14803       break;
14804     case OMPD_cancel:
14805     case OMPD_parallel:
14806     case OMPD_parallel_master:
14807     case OMPD_parallel_sections:
14808     case OMPD_parallel_for:
14809     case OMPD_parallel_loop:
14810     case OMPD_target:
14811     case OMPD_target_teams:
14812     case OMPD_target_teams_distribute:
14813     case OMPD_target_teams_loop:
14814     case OMPD_distribute_parallel_for:
14815     case OMPD_task:
14816     case OMPD_taskloop:
14817     case OMPD_master_taskloop:
14818     case OMPD_target_data:
14819     case OMPD_simd:
14820     case OMPD_for_simd:
14821     case OMPD_distribute_simd:
14822       // Do not capture if-clause expressions.
14823       break;
14824     case OMPD_threadprivate:
14825     case OMPD_allocate:
14826     case OMPD_taskyield:
14827     case OMPD_barrier:
14828     case OMPD_taskwait:
14829     case OMPD_cancellation_point:
14830     case OMPD_flush:
14831     case OMPD_depobj:
14832     case OMPD_scan:
14833     case OMPD_declare_reduction:
14834     case OMPD_declare_mapper:
14835     case OMPD_declare_simd:
14836     case OMPD_declare_variant:
14837     case OMPD_begin_declare_variant:
14838     case OMPD_end_declare_variant:
14839     case OMPD_declare_target:
14840     case OMPD_end_declare_target:
14841     case OMPD_loop:
14842     case OMPD_teams_loop:
14843     case OMPD_teams:
14844     case OMPD_tile:
14845     case OMPD_unroll:
14846     case OMPD_for:
14847     case OMPD_sections:
14848     case OMPD_section:
14849     case OMPD_single:
14850     case OMPD_master:
14851     case OMPD_masked:
14852     case OMPD_critical:
14853     case OMPD_taskgroup:
14854     case OMPD_distribute:
14855     case OMPD_ordered:
14856     case OMPD_atomic:
14857     case OMPD_teams_distribute:
14858     case OMPD_requires:
14859     case OMPD_metadirective:
14860       llvm_unreachable("Unexpected OpenMP directive with if-clause");
14861     case OMPD_unknown:
14862     default:
14863       llvm_unreachable("Unknown OpenMP directive");
14864     }
14865     break;
14866   case OMPC_num_threads:
14867     switch (DKind) {
14868     case OMPD_target_parallel:
14869     case OMPD_target_parallel_for:
14870     case OMPD_target_parallel_for_simd:
14871     case OMPD_target_parallel_loop:
14872       CaptureRegion = OMPD_target;
14873       break;
14874     case OMPD_teams_distribute_parallel_for:
14875     case OMPD_teams_distribute_parallel_for_simd:
14876     case OMPD_target_teams_distribute_parallel_for:
14877     case OMPD_target_teams_distribute_parallel_for_simd:
14878       CaptureRegion = OMPD_teams;
14879       break;
14880     case OMPD_parallel:
14881     case OMPD_parallel_master:
14882     case OMPD_parallel_sections:
14883     case OMPD_parallel_for:
14884     case OMPD_parallel_for_simd:
14885     case OMPD_parallel_loop:
14886     case OMPD_distribute_parallel_for:
14887     case OMPD_distribute_parallel_for_simd:
14888     case OMPD_parallel_master_taskloop:
14889     case OMPD_parallel_master_taskloop_simd:
14890       // Do not capture num_threads-clause expressions.
14891       break;
14892     case OMPD_target_data:
14893     case OMPD_target_enter_data:
14894     case OMPD_target_exit_data:
14895     case OMPD_target_update:
14896     case OMPD_target:
14897     case OMPD_target_simd:
14898     case OMPD_target_teams:
14899     case OMPD_target_teams_distribute:
14900     case OMPD_target_teams_distribute_simd:
14901     case OMPD_cancel:
14902     case OMPD_task:
14903     case OMPD_taskloop:
14904     case OMPD_taskloop_simd:
14905     case OMPD_master_taskloop:
14906     case OMPD_master_taskloop_simd:
14907     case OMPD_threadprivate:
14908     case OMPD_allocate:
14909     case OMPD_taskyield:
14910     case OMPD_barrier:
14911     case OMPD_taskwait:
14912     case OMPD_cancellation_point:
14913     case OMPD_flush:
14914     case OMPD_depobj:
14915     case OMPD_scan:
14916     case OMPD_declare_reduction:
14917     case OMPD_declare_mapper:
14918     case OMPD_declare_simd:
14919     case OMPD_declare_variant:
14920     case OMPD_begin_declare_variant:
14921     case OMPD_end_declare_variant:
14922     case OMPD_declare_target:
14923     case OMPD_end_declare_target:
14924     case OMPD_loop:
14925     case OMPD_teams_loop:
14926     case OMPD_target_teams_loop:
14927     case OMPD_teams:
14928     case OMPD_simd:
14929     case OMPD_tile:
14930     case OMPD_unroll:
14931     case OMPD_for:
14932     case OMPD_for_simd:
14933     case OMPD_sections:
14934     case OMPD_section:
14935     case OMPD_single:
14936     case OMPD_master:
14937     case OMPD_masked:
14938     case OMPD_critical:
14939     case OMPD_taskgroup:
14940     case OMPD_distribute:
14941     case OMPD_ordered:
14942     case OMPD_atomic:
14943     case OMPD_distribute_simd:
14944     case OMPD_teams_distribute:
14945     case OMPD_teams_distribute_simd:
14946     case OMPD_requires:
14947     case OMPD_metadirective:
14948       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
14949     case OMPD_unknown:
14950     default:
14951       llvm_unreachable("Unknown OpenMP directive");
14952     }
14953     break;
14954   case OMPC_num_teams:
14955     switch (DKind) {
14956     case OMPD_target_teams:
14957     case OMPD_target_teams_distribute:
14958     case OMPD_target_teams_distribute_simd:
14959     case OMPD_target_teams_distribute_parallel_for:
14960     case OMPD_target_teams_distribute_parallel_for_simd:
14961     case OMPD_target_teams_loop:
14962       CaptureRegion = OMPD_target;
14963       break;
14964     case OMPD_teams_distribute_parallel_for:
14965     case OMPD_teams_distribute_parallel_for_simd:
14966     case OMPD_teams:
14967     case OMPD_teams_distribute:
14968     case OMPD_teams_distribute_simd:
14969     case OMPD_teams_loop:
14970       // Do not capture num_teams-clause expressions.
14971       break;
14972     case OMPD_distribute_parallel_for:
14973     case OMPD_distribute_parallel_for_simd:
14974     case OMPD_task:
14975     case OMPD_taskloop:
14976     case OMPD_taskloop_simd:
14977     case OMPD_master_taskloop:
14978     case OMPD_master_taskloop_simd:
14979     case OMPD_parallel_master_taskloop:
14980     case OMPD_parallel_master_taskloop_simd:
14981     case OMPD_target_data:
14982     case OMPD_target_enter_data:
14983     case OMPD_target_exit_data:
14984     case OMPD_target_update:
14985     case OMPD_cancel:
14986     case OMPD_parallel:
14987     case OMPD_parallel_master:
14988     case OMPD_parallel_sections:
14989     case OMPD_parallel_for:
14990     case OMPD_parallel_for_simd:
14991     case OMPD_parallel_loop:
14992     case OMPD_target:
14993     case OMPD_target_simd:
14994     case OMPD_target_parallel:
14995     case OMPD_target_parallel_for:
14996     case OMPD_target_parallel_for_simd:
14997     case OMPD_target_parallel_loop:
14998     case OMPD_threadprivate:
14999     case OMPD_allocate:
15000     case OMPD_taskyield:
15001     case OMPD_barrier:
15002     case OMPD_taskwait:
15003     case OMPD_cancellation_point:
15004     case OMPD_flush:
15005     case OMPD_depobj:
15006     case OMPD_scan:
15007     case OMPD_declare_reduction:
15008     case OMPD_declare_mapper:
15009     case OMPD_declare_simd:
15010     case OMPD_declare_variant:
15011     case OMPD_begin_declare_variant:
15012     case OMPD_end_declare_variant:
15013     case OMPD_declare_target:
15014     case OMPD_end_declare_target:
15015     case OMPD_loop:
15016     case OMPD_simd:
15017     case OMPD_tile:
15018     case OMPD_unroll:
15019     case OMPD_for:
15020     case OMPD_for_simd:
15021     case OMPD_sections:
15022     case OMPD_section:
15023     case OMPD_single:
15024     case OMPD_master:
15025     case OMPD_masked:
15026     case OMPD_critical:
15027     case OMPD_taskgroup:
15028     case OMPD_distribute:
15029     case OMPD_ordered:
15030     case OMPD_atomic:
15031     case OMPD_distribute_simd:
15032     case OMPD_requires:
15033     case OMPD_metadirective:
15034       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
15035     case OMPD_unknown:
15036     default:
15037       llvm_unreachable("Unknown OpenMP directive");
15038     }
15039     break;
15040   case OMPC_thread_limit:
15041     switch (DKind) {
15042     case OMPD_target_teams:
15043     case OMPD_target_teams_distribute:
15044     case OMPD_target_teams_distribute_simd:
15045     case OMPD_target_teams_distribute_parallel_for:
15046     case OMPD_target_teams_distribute_parallel_for_simd:
15047     case OMPD_target_teams_loop:
15048       CaptureRegion = OMPD_target;
15049       break;
15050     case OMPD_teams_distribute_parallel_for:
15051     case OMPD_teams_distribute_parallel_for_simd:
15052     case OMPD_teams:
15053     case OMPD_teams_distribute:
15054     case OMPD_teams_distribute_simd:
15055     case OMPD_teams_loop:
15056       // Do not capture thread_limit-clause expressions.
15057       break;
15058     case OMPD_distribute_parallel_for:
15059     case OMPD_distribute_parallel_for_simd:
15060     case OMPD_task:
15061     case OMPD_taskloop:
15062     case OMPD_taskloop_simd:
15063     case OMPD_master_taskloop:
15064     case OMPD_master_taskloop_simd:
15065     case OMPD_parallel_master_taskloop:
15066     case OMPD_parallel_master_taskloop_simd:
15067     case OMPD_target_data:
15068     case OMPD_target_enter_data:
15069     case OMPD_target_exit_data:
15070     case OMPD_target_update:
15071     case OMPD_cancel:
15072     case OMPD_parallel:
15073     case OMPD_parallel_master:
15074     case OMPD_parallel_sections:
15075     case OMPD_parallel_for:
15076     case OMPD_parallel_for_simd:
15077     case OMPD_parallel_loop:
15078     case OMPD_target:
15079     case OMPD_target_simd:
15080     case OMPD_target_parallel:
15081     case OMPD_target_parallel_for:
15082     case OMPD_target_parallel_for_simd:
15083     case OMPD_target_parallel_loop:
15084     case OMPD_threadprivate:
15085     case OMPD_allocate:
15086     case OMPD_taskyield:
15087     case OMPD_barrier:
15088     case OMPD_taskwait:
15089     case OMPD_cancellation_point:
15090     case OMPD_flush:
15091     case OMPD_depobj:
15092     case OMPD_scan:
15093     case OMPD_declare_reduction:
15094     case OMPD_declare_mapper:
15095     case OMPD_declare_simd:
15096     case OMPD_declare_variant:
15097     case OMPD_begin_declare_variant:
15098     case OMPD_end_declare_variant:
15099     case OMPD_declare_target:
15100     case OMPD_end_declare_target:
15101     case OMPD_loop:
15102     case OMPD_simd:
15103     case OMPD_tile:
15104     case OMPD_unroll:
15105     case OMPD_for:
15106     case OMPD_for_simd:
15107     case OMPD_sections:
15108     case OMPD_section:
15109     case OMPD_single:
15110     case OMPD_master:
15111     case OMPD_masked:
15112     case OMPD_critical:
15113     case OMPD_taskgroup:
15114     case OMPD_distribute:
15115     case OMPD_ordered:
15116     case OMPD_atomic:
15117     case OMPD_distribute_simd:
15118     case OMPD_requires:
15119     case OMPD_metadirective:
15120       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
15121     case OMPD_unknown:
15122     default:
15123       llvm_unreachable("Unknown OpenMP directive");
15124     }
15125     break;
15126   case OMPC_schedule:
15127     switch (DKind) {
15128     case OMPD_parallel_for:
15129     case OMPD_parallel_for_simd:
15130     case OMPD_distribute_parallel_for:
15131     case OMPD_distribute_parallel_for_simd:
15132     case OMPD_teams_distribute_parallel_for:
15133     case OMPD_teams_distribute_parallel_for_simd:
15134     case OMPD_target_parallel_for:
15135     case OMPD_target_parallel_for_simd:
15136     case OMPD_target_teams_distribute_parallel_for:
15137     case OMPD_target_teams_distribute_parallel_for_simd:
15138       CaptureRegion = OMPD_parallel;
15139       break;
15140     case OMPD_for:
15141     case OMPD_for_simd:
15142       // Do not capture schedule-clause expressions.
15143       break;
15144     case OMPD_task:
15145     case OMPD_taskloop:
15146     case OMPD_taskloop_simd:
15147     case OMPD_master_taskloop:
15148     case OMPD_master_taskloop_simd:
15149     case OMPD_parallel_master_taskloop:
15150     case OMPD_parallel_master_taskloop_simd:
15151     case OMPD_target_data:
15152     case OMPD_target_enter_data:
15153     case OMPD_target_exit_data:
15154     case OMPD_target_update:
15155     case OMPD_teams:
15156     case OMPD_teams_distribute:
15157     case OMPD_teams_distribute_simd:
15158     case OMPD_target_teams_distribute:
15159     case OMPD_target_teams_distribute_simd:
15160     case OMPD_target:
15161     case OMPD_target_simd:
15162     case OMPD_target_parallel:
15163     case OMPD_cancel:
15164     case OMPD_parallel:
15165     case OMPD_parallel_master:
15166     case OMPD_parallel_sections:
15167     case OMPD_threadprivate:
15168     case OMPD_allocate:
15169     case OMPD_taskyield:
15170     case OMPD_barrier:
15171     case OMPD_taskwait:
15172     case OMPD_cancellation_point:
15173     case OMPD_flush:
15174     case OMPD_depobj:
15175     case OMPD_scan:
15176     case OMPD_declare_reduction:
15177     case OMPD_declare_mapper:
15178     case OMPD_declare_simd:
15179     case OMPD_declare_variant:
15180     case OMPD_begin_declare_variant:
15181     case OMPD_end_declare_variant:
15182     case OMPD_declare_target:
15183     case OMPD_end_declare_target:
15184     case OMPD_loop:
15185     case OMPD_teams_loop:
15186     case OMPD_target_teams_loop:
15187     case OMPD_parallel_loop:
15188     case OMPD_target_parallel_loop:
15189     case OMPD_simd:
15190     case OMPD_tile:
15191     case OMPD_unroll:
15192     case OMPD_sections:
15193     case OMPD_section:
15194     case OMPD_single:
15195     case OMPD_master:
15196     case OMPD_masked:
15197     case OMPD_critical:
15198     case OMPD_taskgroup:
15199     case OMPD_distribute:
15200     case OMPD_ordered:
15201     case OMPD_atomic:
15202     case OMPD_distribute_simd:
15203     case OMPD_target_teams:
15204     case OMPD_requires:
15205     case OMPD_metadirective:
15206       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
15207     case OMPD_unknown:
15208     default:
15209       llvm_unreachable("Unknown OpenMP directive");
15210     }
15211     break;
15212   case OMPC_dist_schedule:
15213     switch (DKind) {
15214     case OMPD_teams_distribute_parallel_for:
15215     case OMPD_teams_distribute_parallel_for_simd:
15216     case OMPD_teams_distribute:
15217     case OMPD_teams_distribute_simd:
15218     case OMPD_target_teams_distribute_parallel_for:
15219     case OMPD_target_teams_distribute_parallel_for_simd:
15220     case OMPD_target_teams_distribute:
15221     case OMPD_target_teams_distribute_simd:
15222       CaptureRegion = OMPD_teams;
15223       break;
15224     case OMPD_distribute_parallel_for:
15225     case OMPD_distribute_parallel_for_simd:
15226     case OMPD_distribute:
15227     case OMPD_distribute_simd:
15228       // Do not capture dist_schedule-clause expressions.
15229       break;
15230     case OMPD_parallel_for:
15231     case OMPD_parallel_for_simd:
15232     case OMPD_target_parallel_for_simd:
15233     case OMPD_target_parallel_for:
15234     case OMPD_task:
15235     case OMPD_taskloop:
15236     case OMPD_taskloop_simd:
15237     case OMPD_master_taskloop:
15238     case OMPD_master_taskloop_simd:
15239     case OMPD_parallel_master_taskloop:
15240     case OMPD_parallel_master_taskloop_simd:
15241     case OMPD_target_data:
15242     case OMPD_target_enter_data:
15243     case OMPD_target_exit_data:
15244     case OMPD_target_update:
15245     case OMPD_teams:
15246     case OMPD_target:
15247     case OMPD_target_simd:
15248     case OMPD_target_parallel:
15249     case OMPD_cancel:
15250     case OMPD_parallel:
15251     case OMPD_parallel_master:
15252     case OMPD_parallel_sections:
15253     case OMPD_threadprivate:
15254     case OMPD_allocate:
15255     case OMPD_taskyield:
15256     case OMPD_barrier:
15257     case OMPD_taskwait:
15258     case OMPD_cancellation_point:
15259     case OMPD_flush:
15260     case OMPD_depobj:
15261     case OMPD_scan:
15262     case OMPD_declare_reduction:
15263     case OMPD_declare_mapper:
15264     case OMPD_declare_simd:
15265     case OMPD_declare_variant:
15266     case OMPD_begin_declare_variant:
15267     case OMPD_end_declare_variant:
15268     case OMPD_declare_target:
15269     case OMPD_end_declare_target:
15270     case OMPD_loop:
15271     case OMPD_teams_loop:
15272     case OMPD_target_teams_loop:
15273     case OMPD_parallel_loop:
15274     case OMPD_target_parallel_loop:
15275     case OMPD_simd:
15276     case OMPD_tile:
15277     case OMPD_unroll:
15278     case OMPD_for:
15279     case OMPD_for_simd:
15280     case OMPD_sections:
15281     case OMPD_section:
15282     case OMPD_single:
15283     case OMPD_master:
15284     case OMPD_masked:
15285     case OMPD_critical:
15286     case OMPD_taskgroup:
15287     case OMPD_ordered:
15288     case OMPD_atomic:
15289     case OMPD_target_teams:
15290     case OMPD_requires:
15291     case OMPD_metadirective:
15292       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
15293     case OMPD_unknown:
15294     default:
15295       llvm_unreachable("Unknown OpenMP directive");
15296     }
15297     break;
15298   case OMPC_device:
15299     switch (DKind) {
15300     case OMPD_target_update:
15301     case OMPD_target_enter_data:
15302     case OMPD_target_exit_data:
15303     case OMPD_target:
15304     case OMPD_target_simd:
15305     case OMPD_target_teams:
15306     case OMPD_target_parallel:
15307     case OMPD_target_teams_distribute:
15308     case OMPD_target_teams_distribute_simd:
15309     case OMPD_target_parallel_for:
15310     case OMPD_target_parallel_for_simd:
15311     case OMPD_target_parallel_loop:
15312     case OMPD_target_teams_distribute_parallel_for:
15313     case OMPD_target_teams_distribute_parallel_for_simd:
15314     case OMPD_target_teams_loop:
15315     case OMPD_dispatch:
15316       CaptureRegion = OMPD_task;
15317       break;
15318     case OMPD_target_data:
15319     case OMPD_interop:
15320       // Do not capture device-clause expressions.
15321       break;
15322     case OMPD_teams_distribute_parallel_for:
15323     case OMPD_teams_distribute_parallel_for_simd:
15324     case OMPD_teams:
15325     case OMPD_teams_distribute:
15326     case OMPD_teams_distribute_simd:
15327     case OMPD_distribute_parallel_for:
15328     case OMPD_distribute_parallel_for_simd:
15329     case OMPD_task:
15330     case OMPD_taskloop:
15331     case OMPD_taskloop_simd:
15332     case OMPD_master_taskloop:
15333     case OMPD_master_taskloop_simd:
15334     case OMPD_parallel_master_taskloop:
15335     case OMPD_parallel_master_taskloop_simd:
15336     case OMPD_cancel:
15337     case OMPD_parallel:
15338     case OMPD_parallel_master:
15339     case OMPD_parallel_sections:
15340     case OMPD_parallel_for:
15341     case OMPD_parallel_for_simd:
15342     case OMPD_threadprivate:
15343     case OMPD_allocate:
15344     case OMPD_taskyield:
15345     case OMPD_barrier:
15346     case OMPD_taskwait:
15347     case OMPD_cancellation_point:
15348     case OMPD_flush:
15349     case OMPD_depobj:
15350     case OMPD_scan:
15351     case OMPD_declare_reduction:
15352     case OMPD_declare_mapper:
15353     case OMPD_declare_simd:
15354     case OMPD_declare_variant:
15355     case OMPD_begin_declare_variant:
15356     case OMPD_end_declare_variant:
15357     case OMPD_declare_target:
15358     case OMPD_end_declare_target:
15359     case OMPD_loop:
15360     case OMPD_teams_loop:
15361     case OMPD_parallel_loop:
15362     case OMPD_simd:
15363     case OMPD_tile:
15364     case OMPD_unroll:
15365     case OMPD_for:
15366     case OMPD_for_simd:
15367     case OMPD_sections:
15368     case OMPD_section:
15369     case OMPD_single:
15370     case OMPD_master:
15371     case OMPD_masked:
15372     case OMPD_critical:
15373     case OMPD_taskgroup:
15374     case OMPD_distribute:
15375     case OMPD_ordered:
15376     case OMPD_atomic:
15377     case OMPD_distribute_simd:
15378     case OMPD_requires:
15379     case OMPD_metadirective:
15380       llvm_unreachable("Unexpected OpenMP directive with device-clause");
15381     case OMPD_unknown:
15382     default:
15383       llvm_unreachable("Unknown OpenMP directive");
15384     }
15385     break;
15386   case OMPC_grainsize:
15387   case OMPC_num_tasks:
15388   case OMPC_final:
15389   case OMPC_priority:
15390     switch (DKind) {
15391     case OMPD_task:
15392     case OMPD_taskloop:
15393     case OMPD_taskloop_simd:
15394     case OMPD_master_taskloop:
15395     case OMPD_master_taskloop_simd:
15396       break;
15397     case OMPD_parallel_master_taskloop:
15398     case OMPD_parallel_master_taskloop_simd:
15399       CaptureRegion = OMPD_parallel;
15400       break;
15401     case OMPD_target_update:
15402     case OMPD_target_enter_data:
15403     case OMPD_target_exit_data:
15404     case OMPD_target:
15405     case OMPD_target_simd:
15406     case OMPD_target_teams:
15407     case OMPD_target_parallel:
15408     case OMPD_target_teams_distribute:
15409     case OMPD_target_teams_distribute_simd:
15410     case OMPD_target_parallel_for:
15411     case OMPD_target_parallel_for_simd:
15412     case OMPD_target_teams_distribute_parallel_for:
15413     case OMPD_target_teams_distribute_parallel_for_simd:
15414     case OMPD_target_data:
15415     case OMPD_teams_distribute_parallel_for:
15416     case OMPD_teams_distribute_parallel_for_simd:
15417     case OMPD_teams:
15418     case OMPD_teams_distribute:
15419     case OMPD_teams_distribute_simd:
15420     case OMPD_distribute_parallel_for:
15421     case OMPD_distribute_parallel_for_simd:
15422     case OMPD_cancel:
15423     case OMPD_parallel:
15424     case OMPD_parallel_master:
15425     case OMPD_parallel_sections:
15426     case OMPD_parallel_for:
15427     case OMPD_parallel_for_simd:
15428     case OMPD_threadprivate:
15429     case OMPD_allocate:
15430     case OMPD_taskyield:
15431     case OMPD_barrier:
15432     case OMPD_taskwait:
15433     case OMPD_cancellation_point:
15434     case OMPD_flush:
15435     case OMPD_depobj:
15436     case OMPD_scan:
15437     case OMPD_declare_reduction:
15438     case OMPD_declare_mapper:
15439     case OMPD_declare_simd:
15440     case OMPD_declare_variant:
15441     case OMPD_begin_declare_variant:
15442     case OMPD_end_declare_variant:
15443     case OMPD_declare_target:
15444     case OMPD_end_declare_target:
15445     case OMPD_loop:
15446     case OMPD_teams_loop:
15447     case OMPD_target_teams_loop:
15448     case OMPD_parallel_loop:
15449     case OMPD_target_parallel_loop:
15450     case OMPD_simd:
15451     case OMPD_tile:
15452     case OMPD_unroll:
15453     case OMPD_for:
15454     case OMPD_for_simd:
15455     case OMPD_sections:
15456     case OMPD_section:
15457     case OMPD_single:
15458     case OMPD_master:
15459     case OMPD_masked:
15460     case OMPD_critical:
15461     case OMPD_taskgroup:
15462     case OMPD_distribute:
15463     case OMPD_ordered:
15464     case OMPD_atomic:
15465     case OMPD_distribute_simd:
15466     case OMPD_requires:
15467     case OMPD_metadirective:
15468       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
15469     case OMPD_unknown:
15470     default:
15471       llvm_unreachable("Unknown OpenMP directive");
15472     }
15473     break;
15474   case OMPC_novariants:
15475   case OMPC_nocontext:
15476     switch (DKind) {
15477     case OMPD_dispatch:
15478       CaptureRegion = OMPD_task;
15479       break;
15480     default:
15481       llvm_unreachable("Unexpected OpenMP directive");
15482     }
15483     break;
15484   case OMPC_filter:
15485     // Do not capture filter-clause expressions.
15486     break;
15487   case OMPC_when:
15488     if (DKind == OMPD_metadirective) {
15489       CaptureRegion = OMPD_metadirective;
15490     } else if (DKind == OMPD_unknown) {
15491       llvm_unreachable("Unknown OpenMP directive");
15492     } else {
15493       llvm_unreachable("Unexpected OpenMP directive with when clause");
15494     }
15495     break;
15496   case OMPC_firstprivate:
15497   case OMPC_lastprivate:
15498   case OMPC_reduction:
15499   case OMPC_task_reduction:
15500   case OMPC_in_reduction:
15501   case OMPC_linear:
15502   case OMPC_default:
15503   case OMPC_proc_bind:
15504   case OMPC_safelen:
15505   case OMPC_simdlen:
15506   case OMPC_sizes:
15507   case OMPC_allocator:
15508   case OMPC_collapse:
15509   case OMPC_private:
15510   case OMPC_shared:
15511   case OMPC_aligned:
15512   case OMPC_copyin:
15513   case OMPC_copyprivate:
15514   case OMPC_ordered:
15515   case OMPC_nowait:
15516   case OMPC_untied:
15517   case OMPC_mergeable:
15518   case OMPC_threadprivate:
15519   case OMPC_allocate:
15520   case OMPC_flush:
15521   case OMPC_depobj:
15522   case OMPC_read:
15523   case OMPC_write:
15524   case OMPC_update:
15525   case OMPC_capture:
15526   case OMPC_compare:
15527   case OMPC_seq_cst:
15528   case OMPC_acq_rel:
15529   case OMPC_acquire:
15530   case OMPC_release:
15531   case OMPC_relaxed:
15532   case OMPC_depend:
15533   case OMPC_threads:
15534   case OMPC_simd:
15535   case OMPC_map:
15536   case OMPC_nogroup:
15537   case OMPC_hint:
15538   case OMPC_defaultmap:
15539   case OMPC_unknown:
15540   case OMPC_uniform:
15541   case OMPC_to:
15542   case OMPC_from:
15543   case OMPC_use_device_ptr:
15544   case OMPC_use_device_addr:
15545   case OMPC_is_device_ptr:
15546   case OMPC_unified_address:
15547   case OMPC_unified_shared_memory:
15548   case OMPC_reverse_offload:
15549   case OMPC_dynamic_allocators:
15550   case OMPC_atomic_default_mem_order:
15551   case OMPC_device_type:
15552   case OMPC_match:
15553   case OMPC_nontemporal:
15554   case OMPC_order:
15555   case OMPC_destroy:
15556   case OMPC_detach:
15557   case OMPC_inclusive:
15558   case OMPC_exclusive:
15559   case OMPC_uses_allocators:
15560   case OMPC_affinity:
15561   case OMPC_bind:
15562   default:
15563     llvm_unreachable("Unexpected OpenMP clause.");
15564   }
15565   return CaptureRegion;
15566 }
15567 
15568 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
15569                                      Expr *Condition, SourceLocation StartLoc,
15570                                      SourceLocation LParenLoc,
15571                                      SourceLocation NameModifierLoc,
15572                                      SourceLocation ColonLoc,
15573                                      SourceLocation EndLoc) {
15574   Expr *ValExpr = Condition;
15575   Stmt *HelperValStmt = nullptr;
15576   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15577   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15578       !Condition->isInstantiationDependent() &&
15579       !Condition->containsUnexpandedParameterPack()) {
15580     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15581     if (Val.isInvalid())
15582       return nullptr;
15583 
15584     ValExpr = Val.get();
15585 
15586     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15587     CaptureRegion = getOpenMPCaptureRegionForClause(
15588         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
15589     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15590       ValExpr = MakeFullExpr(ValExpr).get();
15591       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15592       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15593       HelperValStmt = buildPreInits(Context, Captures);
15594     }
15595   }
15596 
15597   return new (Context)
15598       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
15599                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
15600 }
15601 
15602 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
15603                                         SourceLocation StartLoc,
15604                                         SourceLocation LParenLoc,
15605                                         SourceLocation EndLoc) {
15606   Expr *ValExpr = Condition;
15607   Stmt *HelperValStmt = nullptr;
15608   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15609   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15610       !Condition->isInstantiationDependent() &&
15611       !Condition->containsUnexpandedParameterPack()) {
15612     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15613     if (Val.isInvalid())
15614       return nullptr;
15615 
15616     ValExpr = MakeFullExpr(Val.get()).get();
15617 
15618     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15619     CaptureRegion =
15620         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
15621     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15622       ValExpr = MakeFullExpr(ValExpr).get();
15623       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15624       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15625       HelperValStmt = buildPreInits(Context, Captures);
15626     }
15627   }
15628 
15629   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
15630                                       StartLoc, LParenLoc, EndLoc);
15631 }
15632 
15633 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
15634                                                         Expr *Op) {
15635   if (!Op)
15636     return ExprError();
15637 
15638   class IntConvertDiagnoser : public ICEConvertDiagnoser {
15639   public:
15640     IntConvertDiagnoser()
15641         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
15642     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15643                                          QualType T) override {
15644       return S.Diag(Loc, diag::err_omp_not_integral) << T;
15645     }
15646     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
15647                                              QualType T) override {
15648       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
15649     }
15650     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
15651                                                QualType T,
15652                                                QualType ConvTy) override {
15653       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
15654     }
15655     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
15656                                            QualType ConvTy) override {
15657       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
15658              << ConvTy->isEnumeralType() << ConvTy;
15659     }
15660     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
15661                                             QualType T) override {
15662       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
15663     }
15664     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
15665                                         QualType ConvTy) override {
15666       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
15667              << ConvTy->isEnumeralType() << ConvTy;
15668     }
15669     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
15670                                              QualType) override {
15671       llvm_unreachable("conversion functions are permitted");
15672     }
15673   } ConvertDiagnoser;
15674   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
15675 }
15676 
15677 static bool
15678 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
15679                           bool StrictlyPositive, bool BuildCapture = false,
15680                           OpenMPDirectiveKind DKind = OMPD_unknown,
15681                           OpenMPDirectiveKind *CaptureRegion = nullptr,
15682                           Stmt **HelperValStmt = nullptr) {
15683   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
15684       !ValExpr->isInstantiationDependent()) {
15685     SourceLocation Loc = ValExpr->getExprLoc();
15686     ExprResult Value =
15687         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
15688     if (Value.isInvalid())
15689       return false;
15690 
15691     ValExpr = Value.get();
15692     // The expression must evaluate to a non-negative integer value.
15693     if (Optional<llvm::APSInt> Result =
15694             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
15695       if (Result->isSigned() &&
15696           !((!StrictlyPositive && Result->isNonNegative()) ||
15697             (StrictlyPositive && Result->isStrictlyPositive()))) {
15698         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
15699             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
15700             << ValExpr->getSourceRange();
15701         return false;
15702       }
15703     }
15704     if (!BuildCapture)
15705       return true;
15706     *CaptureRegion =
15707         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
15708     if (*CaptureRegion != OMPD_unknown &&
15709         !SemaRef.CurContext->isDependentContext()) {
15710       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
15711       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15712       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
15713       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
15714     }
15715   }
15716   return true;
15717 }
15718 
15719 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
15720                                              SourceLocation StartLoc,
15721                                              SourceLocation LParenLoc,
15722                                              SourceLocation EndLoc) {
15723   Expr *ValExpr = NumThreads;
15724   Stmt *HelperValStmt = nullptr;
15725 
15726   // OpenMP [2.5, Restrictions]
15727   //  The num_threads expression must evaluate to a positive integer value.
15728   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
15729                                  /*StrictlyPositive=*/true))
15730     return nullptr;
15731 
15732   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15733   OpenMPDirectiveKind CaptureRegion =
15734       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
15735   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15736     ValExpr = MakeFullExpr(ValExpr).get();
15737     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15738     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15739     HelperValStmt = buildPreInits(Context, Captures);
15740   }
15741 
15742   return new (Context) OMPNumThreadsClause(
15743       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15744 }
15745 
15746 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
15747                                                        OpenMPClauseKind CKind,
15748                                                        bool StrictlyPositive,
15749                                                        bool SuppressExprDiags) {
15750   if (!E)
15751     return ExprError();
15752   if (E->isValueDependent() || E->isTypeDependent() ||
15753       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15754     return E;
15755 
15756   llvm::APSInt Result;
15757   ExprResult ICE;
15758   if (SuppressExprDiags) {
15759     // Use a custom diagnoser that suppresses 'note' diagnostics about the
15760     // expression.
15761     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
15762       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
15763       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
15764                                                  SourceLocation Loc) override {
15765         llvm_unreachable("Diagnostic suppressed");
15766       }
15767     } Diagnoser;
15768     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
15769   } else {
15770     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
15771   }
15772   if (ICE.isInvalid())
15773     return ExprError();
15774 
15775   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
15776       (!StrictlyPositive && !Result.isNonNegative())) {
15777     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
15778         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
15779         << E->getSourceRange();
15780     return ExprError();
15781   }
15782   if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
15783     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
15784         << E->getSourceRange();
15785     return ExprError();
15786   }
15787   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
15788     DSAStack->setAssociatedLoops(Result.getExtValue());
15789   else if (CKind == OMPC_ordered)
15790     DSAStack->setAssociatedLoops(Result.getExtValue());
15791   return ICE;
15792 }
15793 
15794 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
15795                                           SourceLocation LParenLoc,
15796                                           SourceLocation EndLoc) {
15797   // OpenMP [2.8.1, simd construct, Description]
15798   // The parameter of the safelen clause must be a constant
15799   // positive integer expression.
15800   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
15801   if (Safelen.isInvalid())
15802     return nullptr;
15803   return new (Context)
15804       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
15805 }
15806 
15807 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
15808                                           SourceLocation LParenLoc,
15809                                           SourceLocation EndLoc) {
15810   // OpenMP [2.8.1, simd construct, Description]
15811   // The parameter of the simdlen clause must be a constant
15812   // positive integer expression.
15813   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
15814   if (Simdlen.isInvalid())
15815     return nullptr;
15816   return new (Context)
15817       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
15818 }
15819 
15820 /// Tries to find omp_allocator_handle_t type.
15821 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
15822                                     DSAStackTy *Stack) {
15823   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
15824   if (!OMPAllocatorHandleT.isNull())
15825     return true;
15826   // Build the predefined allocator expressions.
15827   bool ErrorFound = false;
15828   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
15829     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
15830     StringRef Allocator =
15831         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
15832     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
15833     auto *VD = dyn_cast_or_null<ValueDecl>(
15834         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
15835     if (!VD) {
15836       ErrorFound = true;
15837       break;
15838     }
15839     QualType AllocatorType =
15840         VD->getType().getNonLValueExprType(S.getASTContext());
15841     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
15842     if (!Res.isUsable()) {
15843       ErrorFound = true;
15844       break;
15845     }
15846     if (OMPAllocatorHandleT.isNull())
15847       OMPAllocatorHandleT = AllocatorType;
15848     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
15849       ErrorFound = true;
15850       break;
15851     }
15852     Stack->setAllocator(AllocatorKind, Res.get());
15853   }
15854   if (ErrorFound) {
15855     S.Diag(Loc, diag::err_omp_implied_type_not_found)
15856         << "omp_allocator_handle_t";
15857     return false;
15858   }
15859   OMPAllocatorHandleT.addConst();
15860   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
15861   return true;
15862 }
15863 
15864 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
15865                                             SourceLocation LParenLoc,
15866                                             SourceLocation EndLoc) {
15867   // OpenMP [2.11.3, allocate Directive, Description]
15868   // allocator is an expression of omp_allocator_handle_t type.
15869   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
15870     return nullptr;
15871 
15872   ExprResult Allocator = DefaultLvalueConversion(A);
15873   if (Allocator.isInvalid())
15874     return nullptr;
15875   Allocator = PerformImplicitConversion(Allocator.get(),
15876                                         DSAStack->getOMPAllocatorHandleT(),
15877                                         Sema::AA_Initializing,
15878                                         /*AllowExplicit=*/true);
15879   if (Allocator.isInvalid())
15880     return nullptr;
15881   return new (Context)
15882       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
15883 }
15884 
15885 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
15886                                            SourceLocation StartLoc,
15887                                            SourceLocation LParenLoc,
15888                                            SourceLocation EndLoc) {
15889   // OpenMP [2.7.1, loop construct, Description]
15890   // OpenMP [2.8.1, simd construct, Description]
15891   // OpenMP [2.9.6, distribute construct, Description]
15892   // The parameter of the collapse clause must be a constant
15893   // positive integer expression.
15894   ExprResult NumForLoopsResult =
15895       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
15896   if (NumForLoopsResult.isInvalid())
15897     return nullptr;
15898   return new (Context)
15899       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
15900 }
15901 
15902 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
15903                                           SourceLocation EndLoc,
15904                                           SourceLocation LParenLoc,
15905                                           Expr *NumForLoops) {
15906   // OpenMP [2.7.1, loop construct, Description]
15907   // OpenMP [2.8.1, simd construct, Description]
15908   // OpenMP [2.9.6, distribute construct, Description]
15909   // The parameter of the ordered clause must be a constant
15910   // positive integer expression if any.
15911   if (NumForLoops && LParenLoc.isValid()) {
15912     ExprResult NumForLoopsResult =
15913         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
15914     if (NumForLoopsResult.isInvalid())
15915       return nullptr;
15916     NumForLoops = NumForLoopsResult.get();
15917   } else {
15918     NumForLoops = nullptr;
15919   }
15920   auto *Clause = OMPOrderedClause::Create(
15921       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
15922       StartLoc, LParenLoc, EndLoc);
15923   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
15924   return Clause;
15925 }
15926 
15927 OMPClause *Sema::ActOnOpenMPSimpleClause(
15928     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
15929     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15930   OMPClause *Res = nullptr;
15931   switch (Kind) {
15932   case OMPC_default:
15933     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
15934                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15935     break;
15936   case OMPC_proc_bind:
15937     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
15938                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15939     break;
15940   case OMPC_atomic_default_mem_order:
15941     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
15942         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
15943         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15944     break;
15945   case OMPC_order:
15946     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
15947                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15948     break;
15949   case OMPC_update:
15950     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
15951                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15952     break;
15953   case OMPC_bind:
15954     Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
15955                                 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15956     break;
15957   case OMPC_if:
15958   case OMPC_final:
15959   case OMPC_num_threads:
15960   case OMPC_safelen:
15961   case OMPC_simdlen:
15962   case OMPC_sizes:
15963   case OMPC_allocator:
15964   case OMPC_collapse:
15965   case OMPC_schedule:
15966   case OMPC_private:
15967   case OMPC_firstprivate:
15968   case OMPC_lastprivate:
15969   case OMPC_shared:
15970   case OMPC_reduction:
15971   case OMPC_task_reduction:
15972   case OMPC_in_reduction:
15973   case OMPC_linear:
15974   case OMPC_aligned:
15975   case OMPC_copyin:
15976   case OMPC_copyprivate:
15977   case OMPC_ordered:
15978   case OMPC_nowait:
15979   case OMPC_untied:
15980   case OMPC_mergeable:
15981   case OMPC_threadprivate:
15982   case OMPC_allocate:
15983   case OMPC_flush:
15984   case OMPC_depobj:
15985   case OMPC_read:
15986   case OMPC_write:
15987   case OMPC_capture:
15988   case OMPC_compare:
15989   case OMPC_seq_cst:
15990   case OMPC_acq_rel:
15991   case OMPC_acquire:
15992   case OMPC_release:
15993   case OMPC_relaxed:
15994   case OMPC_depend:
15995   case OMPC_device:
15996   case OMPC_threads:
15997   case OMPC_simd:
15998   case OMPC_map:
15999   case OMPC_num_teams:
16000   case OMPC_thread_limit:
16001   case OMPC_priority:
16002   case OMPC_grainsize:
16003   case OMPC_nogroup:
16004   case OMPC_num_tasks:
16005   case OMPC_hint:
16006   case OMPC_dist_schedule:
16007   case OMPC_defaultmap:
16008   case OMPC_unknown:
16009   case OMPC_uniform:
16010   case OMPC_to:
16011   case OMPC_from:
16012   case OMPC_use_device_ptr:
16013   case OMPC_use_device_addr:
16014   case OMPC_is_device_ptr:
16015   case OMPC_has_device_addr:
16016   case OMPC_unified_address:
16017   case OMPC_unified_shared_memory:
16018   case OMPC_reverse_offload:
16019   case OMPC_dynamic_allocators:
16020   case OMPC_device_type:
16021   case OMPC_match:
16022   case OMPC_nontemporal:
16023   case OMPC_destroy:
16024   case OMPC_novariants:
16025   case OMPC_nocontext:
16026   case OMPC_detach:
16027   case OMPC_inclusive:
16028   case OMPC_exclusive:
16029   case OMPC_uses_allocators:
16030   case OMPC_affinity:
16031   case OMPC_when:
16032   default:
16033     llvm_unreachable("Clause is not allowed.");
16034   }
16035   return Res;
16036 }
16037 
16038 static std::string
16039 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
16040                         ArrayRef<unsigned> Exclude = llvm::None) {
16041   SmallString<256> Buffer;
16042   llvm::raw_svector_ostream Out(Buffer);
16043   unsigned Skipped = Exclude.size();
16044   auto S = Exclude.begin(), E = Exclude.end();
16045   for (unsigned I = First; I < Last; ++I) {
16046     if (std::find(S, E, I) != E) {
16047       --Skipped;
16048       continue;
16049     }
16050     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
16051     if (I + Skipped + 2 == Last)
16052       Out << " or ";
16053     else if (I + Skipped + 1 != Last)
16054       Out << ", ";
16055   }
16056   return std::string(Out.str());
16057 }
16058 
16059 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
16060                                           SourceLocation KindKwLoc,
16061                                           SourceLocation StartLoc,
16062                                           SourceLocation LParenLoc,
16063                                           SourceLocation EndLoc) {
16064   if (Kind == OMP_DEFAULT_unknown) {
16065     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16066         << getListOfPossibleValues(OMPC_default, /*First=*/0,
16067                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
16068         << getOpenMPClauseName(OMPC_default);
16069     return nullptr;
16070   }
16071 
16072   switch (Kind) {
16073   case OMP_DEFAULT_none:
16074     DSAStack->setDefaultDSANone(KindKwLoc);
16075     break;
16076   case OMP_DEFAULT_shared:
16077     DSAStack->setDefaultDSAShared(KindKwLoc);
16078     break;
16079   case OMP_DEFAULT_firstprivate:
16080     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
16081     break;
16082   case OMP_DEFAULT_private:
16083     DSAStack->setDefaultDSAPrivate(KindKwLoc);
16084     break;
16085   default:
16086     llvm_unreachable("DSA unexpected in OpenMP default clause");
16087   }
16088 
16089   return new (Context)
16090       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
16091 }
16092 
16093 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
16094                                            SourceLocation KindKwLoc,
16095                                            SourceLocation StartLoc,
16096                                            SourceLocation LParenLoc,
16097                                            SourceLocation EndLoc) {
16098   if (Kind == OMP_PROC_BIND_unknown) {
16099     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16100         << getListOfPossibleValues(OMPC_proc_bind,
16101                                    /*First=*/unsigned(OMP_PROC_BIND_master),
16102                                    /*Last=*/
16103                                    unsigned(LangOpts.OpenMP > 50
16104                                                 ? OMP_PROC_BIND_primary
16105                                                 : OMP_PROC_BIND_spread) +
16106                                        1)
16107         << getOpenMPClauseName(OMPC_proc_bind);
16108     return nullptr;
16109   }
16110   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
16111     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16112         << getListOfPossibleValues(OMPC_proc_bind,
16113                                    /*First=*/unsigned(OMP_PROC_BIND_master),
16114                                    /*Last=*/
16115                                    unsigned(OMP_PROC_BIND_spread) + 1)
16116         << getOpenMPClauseName(OMPC_proc_bind);
16117   return new (Context)
16118       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
16119 }
16120 
16121 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
16122     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
16123     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16124   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
16125     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16126         << getListOfPossibleValues(
16127                OMPC_atomic_default_mem_order, /*First=*/0,
16128                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
16129         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
16130     return nullptr;
16131   }
16132   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
16133                                                       LParenLoc, EndLoc);
16134 }
16135 
16136 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
16137                                         SourceLocation KindKwLoc,
16138                                         SourceLocation StartLoc,
16139                                         SourceLocation LParenLoc,
16140                                         SourceLocation EndLoc) {
16141   if (Kind == OMPC_ORDER_unknown) {
16142     static_assert(OMPC_ORDER_unknown > 0,
16143                   "OMPC_ORDER_unknown not greater than 0");
16144     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16145         << getListOfPossibleValues(OMPC_order, /*First=*/0,
16146                                    /*Last=*/OMPC_ORDER_unknown)
16147         << getOpenMPClauseName(OMPC_order);
16148     return nullptr;
16149   }
16150   return new (Context)
16151       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
16152 }
16153 
16154 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
16155                                          SourceLocation KindKwLoc,
16156                                          SourceLocation StartLoc,
16157                                          SourceLocation LParenLoc,
16158                                          SourceLocation EndLoc) {
16159   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
16160       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
16161     SmallVector<unsigned> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
16162                                     OMPC_DEPEND_depobj};
16163     if (LangOpts.OpenMP < 51)
16164       Except.push_back(OMPC_DEPEND_inoutset);
16165     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
16166         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
16167                                    /*Last=*/OMPC_DEPEND_unknown, Except)
16168         << getOpenMPClauseName(OMPC_update);
16169     return nullptr;
16170   }
16171   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
16172                                  EndLoc);
16173 }
16174 
16175 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
16176                                         SourceLocation StartLoc,
16177                                         SourceLocation LParenLoc,
16178                                         SourceLocation EndLoc) {
16179   for (Expr *SizeExpr : SizeExprs) {
16180     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
16181         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
16182     if (!NumForLoopsResult.isUsable())
16183       return nullptr;
16184   }
16185 
16186   DSAStack->setAssociatedLoops(SizeExprs.size());
16187   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16188                                 SizeExprs);
16189 }
16190 
16191 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
16192                                        SourceLocation EndLoc) {
16193   return OMPFullClause::Create(Context, StartLoc, EndLoc);
16194 }
16195 
16196 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
16197                                           SourceLocation StartLoc,
16198                                           SourceLocation LParenLoc,
16199                                           SourceLocation EndLoc) {
16200   if (FactorExpr) {
16201     // If an argument is specified, it must be a constant (or an unevaluated
16202     // template expression).
16203     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
16204         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
16205     if (FactorResult.isInvalid())
16206       return nullptr;
16207     FactorExpr = FactorResult.get();
16208   }
16209 
16210   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16211                                   FactorExpr);
16212 }
16213 
16214 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
16215                                         SourceLocation LParenLoc,
16216                                         SourceLocation EndLoc) {
16217   ExprResult AlignVal;
16218   AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
16219   if (AlignVal.isInvalid())
16220     return nullptr;
16221   return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
16222                                 EndLoc);
16223 }
16224 
16225 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
16226     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
16227     SourceLocation StartLoc, SourceLocation LParenLoc,
16228     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
16229     SourceLocation EndLoc) {
16230   OMPClause *Res = nullptr;
16231   switch (Kind) {
16232   case OMPC_schedule:
16233     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
16234     assert(Argument.size() == NumberOfElements &&
16235            ArgumentLoc.size() == NumberOfElements);
16236     Res = ActOnOpenMPScheduleClause(
16237         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
16238         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
16239         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
16240         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
16241         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
16242     break;
16243   case OMPC_if:
16244     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
16245     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
16246                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
16247                               DelimLoc, EndLoc);
16248     break;
16249   case OMPC_dist_schedule:
16250     Res = ActOnOpenMPDistScheduleClause(
16251         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
16252         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
16253     break;
16254   case OMPC_defaultmap:
16255     enum { Modifier, DefaultmapKind };
16256     Res = ActOnOpenMPDefaultmapClause(
16257         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
16258         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
16259         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
16260         EndLoc);
16261     break;
16262   case OMPC_device:
16263     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
16264     Res = ActOnOpenMPDeviceClause(
16265         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
16266         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
16267     break;
16268   case OMPC_final:
16269   case OMPC_num_threads:
16270   case OMPC_safelen:
16271   case OMPC_simdlen:
16272   case OMPC_sizes:
16273   case OMPC_allocator:
16274   case OMPC_collapse:
16275   case OMPC_default:
16276   case OMPC_proc_bind:
16277   case OMPC_private:
16278   case OMPC_firstprivate:
16279   case OMPC_lastprivate:
16280   case OMPC_shared:
16281   case OMPC_reduction:
16282   case OMPC_task_reduction:
16283   case OMPC_in_reduction:
16284   case OMPC_linear:
16285   case OMPC_aligned:
16286   case OMPC_copyin:
16287   case OMPC_copyprivate:
16288   case OMPC_ordered:
16289   case OMPC_nowait:
16290   case OMPC_untied:
16291   case OMPC_mergeable:
16292   case OMPC_threadprivate:
16293   case OMPC_allocate:
16294   case OMPC_flush:
16295   case OMPC_depobj:
16296   case OMPC_read:
16297   case OMPC_write:
16298   case OMPC_update:
16299   case OMPC_capture:
16300   case OMPC_compare:
16301   case OMPC_seq_cst:
16302   case OMPC_acq_rel:
16303   case OMPC_acquire:
16304   case OMPC_release:
16305   case OMPC_relaxed:
16306   case OMPC_depend:
16307   case OMPC_threads:
16308   case OMPC_simd:
16309   case OMPC_map:
16310   case OMPC_num_teams:
16311   case OMPC_thread_limit:
16312   case OMPC_priority:
16313   case OMPC_grainsize:
16314   case OMPC_nogroup:
16315   case OMPC_num_tasks:
16316   case OMPC_hint:
16317   case OMPC_unknown:
16318   case OMPC_uniform:
16319   case OMPC_to:
16320   case OMPC_from:
16321   case OMPC_use_device_ptr:
16322   case OMPC_use_device_addr:
16323   case OMPC_is_device_ptr:
16324   case OMPC_has_device_addr:
16325   case OMPC_unified_address:
16326   case OMPC_unified_shared_memory:
16327   case OMPC_reverse_offload:
16328   case OMPC_dynamic_allocators:
16329   case OMPC_atomic_default_mem_order:
16330   case OMPC_device_type:
16331   case OMPC_match:
16332   case OMPC_nontemporal:
16333   case OMPC_order:
16334   case OMPC_destroy:
16335   case OMPC_novariants:
16336   case OMPC_nocontext:
16337   case OMPC_detach:
16338   case OMPC_inclusive:
16339   case OMPC_exclusive:
16340   case OMPC_uses_allocators:
16341   case OMPC_affinity:
16342   case OMPC_when:
16343   case OMPC_bind:
16344   default:
16345     llvm_unreachable("Clause is not allowed.");
16346   }
16347   return Res;
16348 }
16349 
16350 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
16351                                    OpenMPScheduleClauseModifier M2,
16352                                    SourceLocation M1Loc, SourceLocation M2Loc) {
16353   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
16354     SmallVector<unsigned, 2> Excluded;
16355     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
16356       Excluded.push_back(M2);
16357     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
16358       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
16359     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
16360       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
16361     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
16362         << getListOfPossibleValues(OMPC_schedule,
16363                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
16364                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
16365                                    Excluded)
16366         << getOpenMPClauseName(OMPC_schedule);
16367     return true;
16368   }
16369   return false;
16370 }
16371 
16372 OMPClause *Sema::ActOnOpenMPScheduleClause(
16373     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
16374     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16375     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
16376     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
16377   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
16378       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
16379     return nullptr;
16380   // OpenMP, 2.7.1, Loop Construct, Restrictions
16381   // Either the monotonic modifier or the nonmonotonic modifier can be specified
16382   // but not both.
16383   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
16384       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
16385        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
16386       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
16387        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
16388     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
16389         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
16390         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
16391     return nullptr;
16392   }
16393   if (Kind == OMPC_SCHEDULE_unknown) {
16394     std::string Values;
16395     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
16396       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
16397       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
16398                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
16399                                        Exclude);
16400     } else {
16401       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
16402                                        /*Last=*/OMPC_SCHEDULE_unknown);
16403     }
16404     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16405         << Values << getOpenMPClauseName(OMPC_schedule);
16406     return nullptr;
16407   }
16408   // OpenMP, 2.7.1, Loop Construct, Restrictions
16409   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
16410   // schedule(guided).
16411   // OpenMP 5.0 does not have this restriction.
16412   if (LangOpts.OpenMP < 50 &&
16413       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
16414        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
16415       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
16416     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
16417          diag::err_omp_schedule_nonmonotonic_static);
16418     return nullptr;
16419   }
16420   Expr *ValExpr = ChunkSize;
16421   Stmt *HelperValStmt = nullptr;
16422   if (ChunkSize) {
16423     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16424         !ChunkSize->isInstantiationDependent() &&
16425         !ChunkSize->containsUnexpandedParameterPack()) {
16426       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
16427       ExprResult Val =
16428           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16429       if (Val.isInvalid())
16430         return nullptr;
16431 
16432       ValExpr = Val.get();
16433 
16434       // OpenMP [2.7.1, Restrictions]
16435       //  chunk_size must be a loop invariant integer expression with a positive
16436       //  value.
16437       if (Optional<llvm::APSInt> Result =
16438               ValExpr->getIntegerConstantExpr(Context)) {
16439         if (Result->isSigned() && !Result->isStrictlyPositive()) {
16440           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16441               << "schedule" << 1 << ChunkSize->getSourceRange();
16442           return nullptr;
16443         }
16444       } else if (getOpenMPCaptureRegionForClause(
16445                      DSAStack->getCurrentDirective(), OMPC_schedule,
16446                      LangOpts.OpenMP) != OMPD_unknown &&
16447                  !CurContext->isDependentContext()) {
16448         ValExpr = MakeFullExpr(ValExpr).get();
16449         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16450         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16451         HelperValStmt = buildPreInits(Context, Captures);
16452       }
16453     }
16454   }
16455 
16456   return new (Context)
16457       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
16458                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
16459 }
16460 
16461 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
16462                                    SourceLocation StartLoc,
16463                                    SourceLocation EndLoc) {
16464   OMPClause *Res = nullptr;
16465   switch (Kind) {
16466   case OMPC_ordered:
16467     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
16468     break;
16469   case OMPC_nowait:
16470     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
16471     break;
16472   case OMPC_untied:
16473     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
16474     break;
16475   case OMPC_mergeable:
16476     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
16477     break;
16478   case OMPC_read:
16479     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
16480     break;
16481   case OMPC_write:
16482     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
16483     break;
16484   case OMPC_update:
16485     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
16486     break;
16487   case OMPC_capture:
16488     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
16489     break;
16490   case OMPC_compare:
16491     Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
16492     break;
16493   case OMPC_seq_cst:
16494     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
16495     break;
16496   case OMPC_acq_rel:
16497     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
16498     break;
16499   case OMPC_acquire:
16500     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
16501     break;
16502   case OMPC_release:
16503     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
16504     break;
16505   case OMPC_relaxed:
16506     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
16507     break;
16508   case OMPC_threads:
16509     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
16510     break;
16511   case OMPC_simd:
16512     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
16513     break;
16514   case OMPC_nogroup:
16515     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
16516     break;
16517   case OMPC_unified_address:
16518     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
16519     break;
16520   case OMPC_unified_shared_memory:
16521     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
16522     break;
16523   case OMPC_reverse_offload:
16524     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
16525     break;
16526   case OMPC_dynamic_allocators:
16527     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
16528     break;
16529   case OMPC_destroy:
16530     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
16531                                    /*LParenLoc=*/SourceLocation(),
16532                                    /*VarLoc=*/SourceLocation(), EndLoc);
16533     break;
16534   case OMPC_full:
16535     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
16536     break;
16537   case OMPC_partial:
16538     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
16539     break;
16540   case OMPC_if:
16541   case OMPC_final:
16542   case OMPC_num_threads:
16543   case OMPC_safelen:
16544   case OMPC_simdlen:
16545   case OMPC_sizes:
16546   case OMPC_allocator:
16547   case OMPC_collapse:
16548   case OMPC_schedule:
16549   case OMPC_private:
16550   case OMPC_firstprivate:
16551   case OMPC_lastprivate:
16552   case OMPC_shared:
16553   case OMPC_reduction:
16554   case OMPC_task_reduction:
16555   case OMPC_in_reduction:
16556   case OMPC_linear:
16557   case OMPC_aligned:
16558   case OMPC_copyin:
16559   case OMPC_copyprivate:
16560   case OMPC_default:
16561   case OMPC_proc_bind:
16562   case OMPC_threadprivate:
16563   case OMPC_allocate:
16564   case OMPC_flush:
16565   case OMPC_depobj:
16566   case OMPC_depend:
16567   case OMPC_device:
16568   case OMPC_map:
16569   case OMPC_num_teams:
16570   case OMPC_thread_limit:
16571   case OMPC_priority:
16572   case OMPC_grainsize:
16573   case OMPC_num_tasks:
16574   case OMPC_hint:
16575   case OMPC_dist_schedule:
16576   case OMPC_defaultmap:
16577   case OMPC_unknown:
16578   case OMPC_uniform:
16579   case OMPC_to:
16580   case OMPC_from:
16581   case OMPC_use_device_ptr:
16582   case OMPC_use_device_addr:
16583   case OMPC_is_device_ptr:
16584   case OMPC_has_device_addr:
16585   case OMPC_atomic_default_mem_order:
16586   case OMPC_device_type:
16587   case OMPC_match:
16588   case OMPC_nontemporal:
16589   case OMPC_order:
16590   case OMPC_novariants:
16591   case OMPC_nocontext:
16592   case OMPC_detach:
16593   case OMPC_inclusive:
16594   case OMPC_exclusive:
16595   case OMPC_uses_allocators:
16596   case OMPC_affinity:
16597   case OMPC_when:
16598   default:
16599     llvm_unreachable("Clause is not allowed.");
16600   }
16601   return Res;
16602 }
16603 
16604 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
16605                                          SourceLocation EndLoc) {
16606   DSAStack->setNowaitRegion();
16607   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
16608 }
16609 
16610 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
16611                                          SourceLocation EndLoc) {
16612   DSAStack->setUntiedRegion();
16613   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
16614 }
16615 
16616 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
16617                                             SourceLocation EndLoc) {
16618   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
16619 }
16620 
16621 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
16622                                        SourceLocation EndLoc) {
16623   return new (Context) OMPReadClause(StartLoc, EndLoc);
16624 }
16625 
16626 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
16627                                         SourceLocation EndLoc) {
16628   return new (Context) OMPWriteClause(StartLoc, EndLoc);
16629 }
16630 
16631 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
16632                                          SourceLocation EndLoc) {
16633   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
16634 }
16635 
16636 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
16637                                           SourceLocation EndLoc) {
16638   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
16639 }
16640 
16641 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc,
16642                                           SourceLocation EndLoc) {
16643   return new (Context) OMPCompareClause(StartLoc, EndLoc);
16644 }
16645 
16646 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
16647                                          SourceLocation EndLoc) {
16648   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
16649 }
16650 
16651 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
16652                                          SourceLocation EndLoc) {
16653   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
16654 }
16655 
16656 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
16657                                           SourceLocation EndLoc) {
16658   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
16659 }
16660 
16661 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
16662                                           SourceLocation EndLoc) {
16663   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
16664 }
16665 
16666 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
16667                                           SourceLocation EndLoc) {
16668   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
16669 }
16670 
16671 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
16672                                           SourceLocation EndLoc) {
16673   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
16674 }
16675 
16676 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
16677                                        SourceLocation EndLoc) {
16678   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
16679 }
16680 
16681 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
16682                                           SourceLocation EndLoc) {
16683   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
16684 }
16685 
16686 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
16687                                                  SourceLocation EndLoc) {
16688   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
16689 }
16690 
16691 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
16692                                                       SourceLocation EndLoc) {
16693   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
16694 }
16695 
16696 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
16697                                                  SourceLocation EndLoc) {
16698   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
16699 }
16700 
16701 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
16702                                                     SourceLocation EndLoc) {
16703   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
16704 }
16705 
16706 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
16707                                              SourceLocation StartLoc,
16708                                              SourceLocation EndLoc) {
16709 
16710   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16711   // At least one action-clause must appear on a directive.
16712   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
16713     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
16714     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
16715         << Expected << getOpenMPDirectiveName(OMPD_interop);
16716     return StmtError();
16717   }
16718 
16719   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16720   // A depend clause can only appear on the directive if a targetsync
16721   // interop-type is present or the interop-var was initialized with
16722   // the targetsync interop-type.
16723 
16724   // If there is any 'init' clause diagnose if there is no 'init' clause with
16725   // interop-type of 'targetsync'. Cases involving other directives cannot be
16726   // diagnosed.
16727   const OMPDependClause *DependClause = nullptr;
16728   bool HasInitClause = false;
16729   bool IsTargetSync = false;
16730   for (const OMPClause *C : Clauses) {
16731     if (IsTargetSync)
16732       break;
16733     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
16734       HasInitClause = true;
16735       if (InitClause->getIsTargetSync())
16736         IsTargetSync = true;
16737     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
16738       DependClause = DC;
16739     }
16740   }
16741   if (DependClause && HasInitClause && !IsTargetSync) {
16742     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
16743     return StmtError();
16744   }
16745 
16746   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16747   // Each interop-var may be specified for at most one action-clause of each
16748   // interop construct.
16749   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
16750   for (const OMPClause *C : Clauses) {
16751     OpenMPClauseKind ClauseKind = C->getClauseKind();
16752     const DeclRefExpr *DRE = nullptr;
16753     SourceLocation VarLoc;
16754 
16755     if (ClauseKind == OMPC_init) {
16756       const auto *IC = cast<OMPInitClause>(C);
16757       VarLoc = IC->getVarLoc();
16758       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
16759     } else if (ClauseKind == OMPC_use) {
16760       const auto *UC = cast<OMPUseClause>(C);
16761       VarLoc = UC->getVarLoc();
16762       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
16763     } else if (ClauseKind == OMPC_destroy) {
16764       const auto *DC = cast<OMPDestroyClause>(C);
16765       VarLoc = DC->getVarLoc();
16766       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
16767     }
16768 
16769     if (!DRE)
16770       continue;
16771 
16772     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
16773       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
16774         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
16775         return StmtError();
16776       }
16777     }
16778   }
16779 
16780   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
16781 }
16782 
16783 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
16784                                    SourceLocation VarLoc,
16785                                    OpenMPClauseKind Kind) {
16786   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
16787       InteropVarExpr->isInstantiationDependent() ||
16788       InteropVarExpr->containsUnexpandedParameterPack())
16789     return true;
16790 
16791   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
16792   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
16793     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
16794     return false;
16795   }
16796 
16797   // Interop variable should be of type omp_interop_t.
16798   bool HasError = false;
16799   QualType InteropType;
16800   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
16801                       VarLoc, Sema::LookupOrdinaryName);
16802   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
16803     NamedDecl *ND = Result.getFoundDecl();
16804     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
16805       InteropType = QualType(TD->getTypeForDecl(), 0);
16806     } else {
16807       HasError = true;
16808     }
16809   } else {
16810     HasError = true;
16811   }
16812 
16813   if (HasError) {
16814     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
16815         << "omp_interop_t";
16816     return false;
16817   }
16818 
16819   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
16820   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
16821     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
16822     return false;
16823   }
16824 
16825   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
16826   // The interop-var passed to init or destroy must be non-const.
16827   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
16828       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
16829     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
16830         << /*non-const*/ 1;
16831     return false;
16832   }
16833   return true;
16834 }
16835 
16836 OMPClause *
16837 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
16838                             bool IsTarget, bool IsTargetSync,
16839                             SourceLocation StartLoc, SourceLocation LParenLoc,
16840                             SourceLocation VarLoc, SourceLocation EndLoc) {
16841 
16842   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
16843     return nullptr;
16844 
16845   // Check prefer_type values.  These foreign-runtime-id values are either
16846   // string literals or constant integral expressions.
16847   for (const Expr *E : PrefExprs) {
16848     if (E->isValueDependent() || E->isTypeDependent() ||
16849         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
16850       continue;
16851     if (E->isIntegerConstantExpr(Context))
16852       continue;
16853     if (isa<StringLiteral>(E))
16854       continue;
16855     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
16856     return nullptr;
16857   }
16858 
16859   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
16860                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
16861                                EndLoc);
16862 }
16863 
16864 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
16865                                       SourceLocation LParenLoc,
16866                                       SourceLocation VarLoc,
16867                                       SourceLocation EndLoc) {
16868 
16869   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
16870     return nullptr;
16871 
16872   return new (Context)
16873       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
16874 }
16875 
16876 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
16877                                           SourceLocation StartLoc,
16878                                           SourceLocation LParenLoc,
16879                                           SourceLocation VarLoc,
16880                                           SourceLocation EndLoc) {
16881   if (InteropVar &&
16882       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
16883     return nullptr;
16884 
16885   return new (Context)
16886       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
16887 }
16888 
16889 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
16890                                              SourceLocation StartLoc,
16891                                              SourceLocation LParenLoc,
16892                                              SourceLocation EndLoc) {
16893   Expr *ValExpr = Condition;
16894   Stmt *HelperValStmt = nullptr;
16895   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
16896   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
16897       !Condition->isInstantiationDependent() &&
16898       !Condition->containsUnexpandedParameterPack()) {
16899     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
16900     if (Val.isInvalid())
16901       return nullptr;
16902 
16903     ValExpr = MakeFullExpr(Val.get()).get();
16904 
16905     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16906     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
16907                                                     LangOpts.OpenMP);
16908     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16909       ValExpr = MakeFullExpr(ValExpr).get();
16910       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16911       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16912       HelperValStmt = buildPreInits(Context, Captures);
16913     }
16914   }
16915 
16916   return new (Context) OMPNovariantsClause(
16917       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
16918 }
16919 
16920 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
16921                                             SourceLocation StartLoc,
16922                                             SourceLocation LParenLoc,
16923                                             SourceLocation EndLoc) {
16924   Expr *ValExpr = Condition;
16925   Stmt *HelperValStmt = nullptr;
16926   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
16927   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
16928       !Condition->isInstantiationDependent() &&
16929       !Condition->containsUnexpandedParameterPack()) {
16930     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
16931     if (Val.isInvalid())
16932       return nullptr;
16933 
16934     ValExpr = MakeFullExpr(Val.get()).get();
16935 
16936     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16937     CaptureRegion =
16938         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
16939     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16940       ValExpr = MakeFullExpr(ValExpr).get();
16941       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16942       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16943       HelperValStmt = buildPreInits(Context, Captures);
16944     }
16945   }
16946 
16947   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
16948                                           StartLoc, LParenLoc, EndLoc);
16949 }
16950 
16951 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
16952                                          SourceLocation StartLoc,
16953                                          SourceLocation LParenLoc,
16954                                          SourceLocation EndLoc) {
16955   Expr *ValExpr = ThreadID;
16956   Stmt *HelperValStmt = nullptr;
16957 
16958   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16959   OpenMPDirectiveKind CaptureRegion =
16960       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
16961   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16962     ValExpr = MakeFullExpr(ValExpr).get();
16963     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16964     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16965     HelperValStmt = buildPreInits(Context, Captures);
16966   }
16967 
16968   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
16969                                        StartLoc, LParenLoc, EndLoc);
16970 }
16971 
16972 OMPClause *Sema::ActOnOpenMPVarListClause(
16973     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
16974     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
16975     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
16976     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
16977     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16978     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
16979     SourceLocation ExtraModifierLoc,
16980     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
16981     ArrayRef<SourceLocation> MotionModifiersLoc) {
16982   SourceLocation StartLoc = Locs.StartLoc;
16983   SourceLocation LParenLoc = Locs.LParenLoc;
16984   SourceLocation EndLoc = Locs.EndLoc;
16985   OMPClause *Res = nullptr;
16986   switch (Kind) {
16987   case OMPC_private:
16988     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16989     break;
16990   case OMPC_firstprivate:
16991     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16992     break;
16993   case OMPC_lastprivate:
16994     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
16995            "Unexpected lastprivate modifier.");
16996     Res = ActOnOpenMPLastprivateClause(
16997         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
16998         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
16999     break;
17000   case OMPC_shared:
17001     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
17002     break;
17003   case OMPC_reduction:
17004     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
17005            "Unexpected lastprivate modifier.");
17006     Res = ActOnOpenMPReductionClause(
17007         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
17008         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
17009         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
17010     break;
17011   case OMPC_task_reduction:
17012     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
17013                                          EndLoc, ReductionOrMapperIdScopeSpec,
17014                                          ReductionOrMapperId);
17015     break;
17016   case OMPC_in_reduction:
17017     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
17018                                        EndLoc, ReductionOrMapperIdScopeSpec,
17019                                        ReductionOrMapperId);
17020     break;
17021   case OMPC_linear:
17022     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
17023            "Unexpected linear modifier.");
17024     Res = ActOnOpenMPLinearClause(
17025         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
17026         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
17027         ColonLoc, EndLoc);
17028     break;
17029   case OMPC_aligned:
17030     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
17031                                    LParenLoc, ColonLoc, EndLoc);
17032     break;
17033   case OMPC_copyin:
17034     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
17035     break;
17036   case OMPC_copyprivate:
17037     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
17038     break;
17039   case OMPC_flush:
17040     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
17041     break;
17042   case OMPC_depend:
17043     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
17044            "Unexpected depend modifier.");
17045     Res = ActOnOpenMPDependClause(
17046         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
17047         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
17048     break;
17049   case OMPC_map:
17050     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
17051            "Unexpected map modifier.");
17052     Res = ActOnOpenMPMapClause(
17053         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
17054         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
17055         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
17056     break;
17057   case OMPC_to:
17058     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
17059                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
17060                               ColonLoc, VarList, Locs);
17061     break;
17062   case OMPC_from:
17063     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
17064                                 ReductionOrMapperIdScopeSpec,
17065                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
17066     break;
17067   case OMPC_use_device_ptr:
17068     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
17069     break;
17070   case OMPC_use_device_addr:
17071     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
17072     break;
17073   case OMPC_is_device_ptr:
17074     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
17075     break;
17076   case OMPC_has_device_addr:
17077     Res = ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
17078     break;
17079   case OMPC_allocate:
17080     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
17081                                     LParenLoc, ColonLoc, EndLoc);
17082     break;
17083   case OMPC_nontemporal:
17084     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
17085     break;
17086   case OMPC_inclusive:
17087     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
17088     break;
17089   case OMPC_exclusive:
17090     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
17091     break;
17092   case OMPC_affinity:
17093     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
17094                                     DepModOrTailExpr, VarList);
17095     break;
17096   case OMPC_if:
17097   case OMPC_depobj:
17098   case OMPC_final:
17099   case OMPC_num_threads:
17100   case OMPC_safelen:
17101   case OMPC_simdlen:
17102   case OMPC_sizes:
17103   case OMPC_allocator:
17104   case OMPC_collapse:
17105   case OMPC_default:
17106   case OMPC_proc_bind:
17107   case OMPC_schedule:
17108   case OMPC_ordered:
17109   case OMPC_nowait:
17110   case OMPC_untied:
17111   case OMPC_mergeable:
17112   case OMPC_threadprivate:
17113   case OMPC_read:
17114   case OMPC_write:
17115   case OMPC_update:
17116   case OMPC_capture:
17117   case OMPC_compare:
17118   case OMPC_seq_cst:
17119   case OMPC_acq_rel:
17120   case OMPC_acquire:
17121   case OMPC_release:
17122   case OMPC_relaxed:
17123   case OMPC_device:
17124   case OMPC_threads:
17125   case OMPC_simd:
17126   case OMPC_num_teams:
17127   case OMPC_thread_limit:
17128   case OMPC_priority:
17129   case OMPC_grainsize:
17130   case OMPC_nogroup:
17131   case OMPC_num_tasks:
17132   case OMPC_hint:
17133   case OMPC_dist_schedule:
17134   case OMPC_defaultmap:
17135   case OMPC_unknown:
17136   case OMPC_uniform:
17137   case OMPC_unified_address:
17138   case OMPC_unified_shared_memory:
17139   case OMPC_reverse_offload:
17140   case OMPC_dynamic_allocators:
17141   case OMPC_atomic_default_mem_order:
17142   case OMPC_device_type:
17143   case OMPC_match:
17144   case OMPC_order:
17145   case OMPC_destroy:
17146   case OMPC_novariants:
17147   case OMPC_nocontext:
17148   case OMPC_detach:
17149   case OMPC_uses_allocators:
17150   case OMPC_when:
17151   case OMPC_bind:
17152   default:
17153     llvm_unreachable("Clause is not allowed.");
17154   }
17155   return Res;
17156 }
17157 
17158 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
17159                                        ExprObjectKind OK, SourceLocation Loc) {
17160   ExprResult Res = BuildDeclRefExpr(
17161       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
17162   if (!Res.isUsable())
17163     return ExprError();
17164   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
17165     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
17166     if (!Res.isUsable())
17167       return ExprError();
17168   }
17169   if (VK != VK_LValue && Res.get()->isGLValue()) {
17170     Res = DefaultLvalueConversion(Res.get());
17171     if (!Res.isUsable())
17172       return ExprError();
17173   }
17174   return Res;
17175 }
17176 
17177 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
17178                                           SourceLocation StartLoc,
17179                                           SourceLocation LParenLoc,
17180                                           SourceLocation EndLoc) {
17181   SmallVector<Expr *, 8> Vars;
17182   SmallVector<Expr *, 8> PrivateCopies;
17183   for (Expr *RefExpr : VarList) {
17184     assert(RefExpr && "NULL expr in OpenMP private clause.");
17185     SourceLocation ELoc;
17186     SourceRange ERange;
17187     Expr *SimpleRefExpr = RefExpr;
17188     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17189     if (Res.second) {
17190       // It will be analyzed later.
17191       Vars.push_back(RefExpr);
17192       PrivateCopies.push_back(nullptr);
17193     }
17194     ValueDecl *D = Res.first;
17195     if (!D)
17196       continue;
17197 
17198     QualType Type = D->getType();
17199     auto *VD = dyn_cast<VarDecl>(D);
17200 
17201     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17202     //  A variable that appears in a private clause must not have an incomplete
17203     //  type or a reference type.
17204     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
17205       continue;
17206     Type = Type.getNonReferenceType();
17207 
17208     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17209     // A variable that is privatized must not have a const-qualified type
17210     // unless it is of class type with a mutable member. This restriction does
17211     // not apply to the firstprivate clause.
17212     //
17213     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
17214     // A variable that appears in a private clause must not have a
17215     // const-qualified type unless it is of class type with a mutable member.
17216     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
17217       continue;
17218 
17219     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17220     // in a Construct]
17221     //  Variables with the predetermined data-sharing attributes may not be
17222     //  listed in data-sharing attributes clauses, except for the cases
17223     //  listed below. For these exceptions only, listing a predetermined
17224     //  variable in a data-sharing attribute clause is allowed and overrides
17225     //  the variable's predetermined data-sharing attributes.
17226     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17227     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
17228       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17229                                           << getOpenMPClauseName(OMPC_private);
17230       reportOriginalDsa(*this, DSAStack, D, DVar);
17231       continue;
17232     }
17233 
17234     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
17235     // Variably modified types are not supported for tasks.
17236     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
17237         isOpenMPTaskingDirective(CurrDir)) {
17238       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17239           << getOpenMPClauseName(OMPC_private) << Type
17240           << getOpenMPDirectiveName(CurrDir);
17241       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17242                                VarDecl::DeclarationOnly;
17243       Diag(D->getLocation(),
17244            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17245           << D;
17246       continue;
17247     }
17248 
17249     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17250     // A list item cannot appear in both a map clause and a data-sharing
17251     // attribute clause on the same construct
17252     //
17253     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17254     // A list item cannot appear in both a map clause and a data-sharing
17255     // attribute clause on the same construct unless the construct is a
17256     // combined construct.
17257     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
17258         CurrDir == OMPD_target) {
17259       OpenMPClauseKind ConflictKind;
17260       if (DSAStack->checkMappableExprComponentListsForDecl(
17261               VD, /*CurrentRegionOnly=*/true,
17262               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
17263                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
17264                 ConflictKind = WhereFoundClauseKind;
17265                 return true;
17266               })) {
17267         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17268             << getOpenMPClauseName(OMPC_private)
17269             << getOpenMPClauseName(ConflictKind)
17270             << getOpenMPDirectiveName(CurrDir);
17271         reportOriginalDsa(*this, DSAStack, D, DVar);
17272         continue;
17273       }
17274     }
17275 
17276     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
17277     //  A variable of class type (or array thereof) that appears in a private
17278     //  clause requires an accessible, unambiguous default constructor for the
17279     //  class type.
17280     // Generate helper private variable and initialize it with the default
17281     // value. The address of the original variable is replaced by the address of
17282     // the new private variable in CodeGen. This new variable is not added to
17283     // IdResolver, so the code in the OpenMP region uses original variable for
17284     // proper diagnostics.
17285     Type = Type.getUnqualifiedType();
17286     VarDecl *VDPrivate =
17287         buildVarDecl(*this, ELoc, Type, D->getName(),
17288                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17289                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17290     ActOnUninitializedDecl(VDPrivate);
17291     if (VDPrivate->isInvalidDecl())
17292       continue;
17293     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
17294         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17295 
17296     DeclRefExpr *Ref = nullptr;
17297     if (!VD && !CurContext->isDependentContext())
17298       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17299     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
17300     Vars.push_back((VD || CurContext->isDependentContext())
17301                        ? RefExpr->IgnoreParens()
17302                        : Ref);
17303     PrivateCopies.push_back(VDPrivateRefExpr);
17304   }
17305 
17306   if (Vars.empty())
17307     return nullptr;
17308 
17309   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17310                                   PrivateCopies);
17311 }
17312 
17313 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
17314                                                SourceLocation StartLoc,
17315                                                SourceLocation LParenLoc,
17316                                                SourceLocation EndLoc) {
17317   SmallVector<Expr *, 8> Vars;
17318   SmallVector<Expr *, 8> PrivateCopies;
17319   SmallVector<Expr *, 8> Inits;
17320   SmallVector<Decl *, 4> ExprCaptures;
17321   bool IsImplicitClause =
17322       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
17323   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
17324 
17325   for (Expr *RefExpr : VarList) {
17326     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
17327     SourceLocation ELoc;
17328     SourceRange ERange;
17329     Expr *SimpleRefExpr = RefExpr;
17330     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17331     if (Res.second) {
17332       // It will be analyzed later.
17333       Vars.push_back(RefExpr);
17334       PrivateCopies.push_back(nullptr);
17335       Inits.push_back(nullptr);
17336     }
17337     ValueDecl *D = Res.first;
17338     if (!D)
17339       continue;
17340 
17341     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
17342     QualType Type = D->getType();
17343     auto *VD = dyn_cast<VarDecl>(D);
17344 
17345     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17346     //  A variable that appears in a private clause must not have an incomplete
17347     //  type or a reference type.
17348     if (RequireCompleteType(ELoc, Type,
17349                             diag::err_omp_firstprivate_incomplete_type))
17350       continue;
17351     Type = Type.getNonReferenceType();
17352 
17353     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
17354     //  A variable of class type (or array thereof) that appears in a private
17355     //  clause requires an accessible, unambiguous copy constructor for the
17356     //  class type.
17357     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17358 
17359     // If an implicit firstprivate variable found it was checked already.
17360     DSAStackTy::DSAVarData TopDVar;
17361     if (!IsImplicitClause) {
17362       DSAStackTy::DSAVarData DVar =
17363           DSAStack->getTopDSA(D, /*FromParent=*/false);
17364       TopDVar = DVar;
17365       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
17366       bool IsConstant = ElemType.isConstant(Context);
17367       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
17368       //  A list item that specifies a given variable may not appear in more
17369       // than one clause on the same directive, except that a variable may be
17370       //  specified in both firstprivate and lastprivate clauses.
17371       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
17372       // A list item may appear in a firstprivate or lastprivate clause but not
17373       // both.
17374       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
17375           (isOpenMPDistributeDirective(CurrDir) ||
17376            DVar.CKind != OMPC_lastprivate) &&
17377           DVar.RefExpr) {
17378         Diag(ELoc, diag::err_omp_wrong_dsa)
17379             << getOpenMPClauseName(DVar.CKind)
17380             << getOpenMPClauseName(OMPC_firstprivate);
17381         reportOriginalDsa(*this, DSAStack, D, DVar);
17382         continue;
17383       }
17384 
17385       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17386       // in a Construct]
17387       //  Variables with the predetermined data-sharing attributes may not be
17388       //  listed in data-sharing attributes clauses, except for the cases
17389       //  listed below. For these exceptions only, listing a predetermined
17390       //  variable in a data-sharing attribute clause is allowed and overrides
17391       //  the variable's predetermined data-sharing attributes.
17392       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17393       // in a Construct, C/C++, p.2]
17394       //  Variables with const-qualified type having no mutable member may be
17395       //  listed in a firstprivate clause, even if they are static data members.
17396       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
17397           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
17398         Diag(ELoc, diag::err_omp_wrong_dsa)
17399             << getOpenMPClauseName(DVar.CKind)
17400             << getOpenMPClauseName(OMPC_firstprivate);
17401         reportOriginalDsa(*this, DSAStack, D, DVar);
17402         continue;
17403       }
17404 
17405       // OpenMP [2.9.3.4, Restrictions, p.2]
17406       //  A list item that is private within a parallel region must not appear
17407       //  in a firstprivate clause on a worksharing construct if any of the
17408       //  worksharing regions arising from the worksharing construct ever bind
17409       //  to any of the parallel regions arising from the parallel construct.
17410       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
17411       // A list item that is private within a teams region must not appear in a
17412       // firstprivate clause on a distribute construct if any of the distribute
17413       // regions arising from the distribute construct ever bind to any of the
17414       // teams regions arising from the teams construct.
17415       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
17416       // A list item that appears in a reduction clause of a teams construct
17417       // must not appear in a firstprivate clause on a distribute construct if
17418       // any of the distribute regions arising from the distribute construct
17419       // ever bind to any of the teams regions arising from the teams construct.
17420       if ((isOpenMPWorksharingDirective(CurrDir) ||
17421            isOpenMPDistributeDirective(CurrDir)) &&
17422           !isOpenMPParallelDirective(CurrDir) &&
17423           !isOpenMPTeamsDirective(CurrDir)) {
17424         DVar = DSAStack->getImplicitDSA(D, true);
17425         if (DVar.CKind != OMPC_shared &&
17426             (isOpenMPParallelDirective(DVar.DKind) ||
17427              isOpenMPTeamsDirective(DVar.DKind) ||
17428              DVar.DKind == OMPD_unknown)) {
17429           Diag(ELoc, diag::err_omp_required_access)
17430               << getOpenMPClauseName(OMPC_firstprivate)
17431               << getOpenMPClauseName(OMPC_shared);
17432           reportOriginalDsa(*this, DSAStack, D, DVar);
17433           continue;
17434         }
17435       }
17436       // OpenMP [2.9.3.4, Restrictions, p.3]
17437       //  A list item that appears in a reduction clause of a parallel construct
17438       //  must not appear in a firstprivate clause on a worksharing or task
17439       //  construct if any of the worksharing or task regions arising from the
17440       //  worksharing or task construct ever bind to any of the parallel regions
17441       //  arising from the parallel construct.
17442       // OpenMP [2.9.3.4, Restrictions, p.4]
17443       //  A list item that appears in a reduction clause in worksharing
17444       //  construct must not appear in a firstprivate clause in a task construct
17445       //  encountered during execution of any of the worksharing regions arising
17446       //  from the worksharing construct.
17447       if (isOpenMPTaskingDirective(CurrDir)) {
17448         DVar = DSAStack->hasInnermostDSA(
17449             D,
17450             [](OpenMPClauseKind C, bool AppliedToPointee) {
17451               return C == OMPC_reduction && !AppliedToPointee;
17452             },
17453             [](OpenMPDirectiveKind K) {
17454               return isOpenMPParallelDirective(K) ||
17455                      isOpenMPWorksharingDirective(K) ||
17456                      isOpenMPTeamsDirective(K);
17457             },
17458             /*FromParent=*/true);
17459         if (DVar.CKind == OMPC_reduction &&
17460             (isOpenMPParallelDirective(DVar.DKind) ||
17461              isOpenMPWorksharingDirective(DVar.DKind) ||
17462              isOpenMPTeamsDirective(DVar.DKind))) {
17463           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
17464               << getOpenMPDirectiveName(DVar.DKind);
17465           reportOriginalDsa(*this, DSAStack, D, DVar);
17466           continue;
17467         }
17468       }
17469 
17470       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17471       // A list item cannot appear in both a map clause and a data-sharing
17472       // attribute clause on the same construct
17473       //
17474       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17475       // A list item cannot appear in both a map clause and a data-sharing
17476       // attribute clause on the same construct unless the construct is a
17477       // combined construct.
17478       if ((LangOpts.OpenMP <= 45 &&
17479            isOpenMPTargetExecutionDirective(CurrDir)) ||
17480           CurrDir == OMPD_target) {
17481         OpenMPClauseKind ConflictKind;
17482         if (DSAStack->checkMappableExprComponentListsForDecl(
17483                 VD, /*CurrentRegionOnly=*/true,
17484                 [&ConflictKind](
17485                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
17486                     OpenMPClauseKind WhereFoundClauseKind) {
17487                   ConflictKind = WhereFoundClauseKind;
17488                   return true;
17489                 })) {
17490           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17491               << getOpenMPClauseName(OMPC_firstprivate)
17492               << getOpenMPClauseName(ConflictKind)
17493               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17494           reportOriginalDsa(*this, DSAStack, D, DVar);
17495           continue;
17496         }
17497       }
17498     }
17499 
17500     // Variably modified types are not supported for tasks.
17501     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
17502         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
17503       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17504           << getOpenMPClauseName(OMPC_firstprivate) << Type
17505           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17506       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17507                                VarDecl::DeclarationOnly;
17508       Diag(D->getLocation(),
17509            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17510           << D;
17511       continue;
17512     }
17513 
17514     Type = Type.getUnqualifiedType();
17515     VarDecl *VDPrivate =
17516         buildVarDecl(*this, ELoc, Type, D->getName(),
17517                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17518                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17519     // Generate helper private variable and initialize it with the value of the
17520     // original variable. The address of the original variable is replaced by
17521     // the address of the new private variable in the CodeGen. This new variable
17522     // is not added to IdResolver, so the code in the OpenMP region uses
17523     // original variable for proper diagnostics and variable capturing.
17524     Expr *VDInitRefExpr = nullptr;
17525     // For arrays generate initializer for single element and replace it by the
17526     // original array element in CodeGen.
17527     if (Type->isArrayType()) {
17528       VarDecl *VDInit =
17529           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
17530       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
17531       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
17532       ElemType = ElemType.getUnqualifiedType();
17533       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
17534                                          ".firstprivate.temp");
17535       InitializedEntity Entity =
17536           InitializedEntity::InitializeVariable(VDInitTemp);
17537       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
17538 
17539       InitializationSequence InitSeq(*this, Entity, Kind, Init);
17540       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
17541       if (Result.isInvalid())
17542         VDPrivate->setInvalidDecl();
17543       else
17544         VDPrivate->setInit(Result.getAs<Expr>());
17545       // Remove temp variable declaration.
17546       Context.Deallocate(VDInitTemp);
17547     } else {
17548       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
17549                                      ".firstprivate.temp");
17550       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
17551                                        RefExpr->getExprLoc());
17552       AddInitializerToDecl(VDPrivate,
17553                            DefaultLvalueConversion(VDInitRefExpr).get(),
17554                            /*DirectInit=*/false);
17555     }
17556     if (VDPrivate->isInvalidDecl()) {
17557       if (IsImplicitClause) {
17558         Diag(RefExpr->getExprLoc(),
17559              diag::note_omp_task_predetermined_firstprivate_here);
17560       }
17561       continue;
17562     }
17563     CurContext->addDecl(VDPrivate);
17564     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
17565         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
17566         RefExpr->getExprLoc());
17567     DeclRefExpr *Ref = nullptr;
17568     if (!VD && !CurContext->isDependentContext()) {
17569       if (TopDVar.CKind == OMPC_lastprivate) {
17570         Ref = TopDVar.PrivateCopy;
17571       } else {
17572         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17573         if (!isOpenMPCapturedDecl(D))
17574           ExprCaptures.push_back(Ref->getDecl());
17575       }
17576     }
17577     if (!IsImplicitClause)
17578       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17579     Vars.push_back((VD || CurContext->isDependentContext())
17580                        ? RefExpr->IgnoreParens()
17581                        : Ref);
17582     PrivateCopies.push_back(VDPrivateRefExpr);
17583     Inits.push_back(VDInitRefExpr);
17584   }
17585 
17586   if (Vars.empty())
17587     return nullptr;
17588 
17589   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17590                                        Vars, PrivateCopies, Inits,
17591                                        buildPreInits(Context, ExprCaptures));
17592 }
17593 
17594 OMPClause *Sema::ActOnOpenMPLastprivateClause(
17595     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
17596     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
17597     SourceLocation LParenLoc, SourceLocation EndLoc) {
17598   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
17599     assert(ColonLoc.isValid() && "Colon location must be valid.");
17600     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
17601         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
17602                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
17603         << getOpenMPClauseName(OMPC_lastprivate);
17604     return nullptr;
17605   }
17606 
17607   SmallVector<Expr *, 8> Vars;
17608   SmallVector<Expr *, 8> SrcExprs;
17609   SmallVector<Expr *, 8> DstExprs;
17610   SmallVector<Expr *, 8> AssignmentOps;
17611   SmallVector<Decl *, 4> ExprCaptures;
17612   SmallVector<Expr *, 4> ExprPostUpdates;
17613   for (Expr *RefExpr : VarList) {
17614     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
17615     SourceLocation ELoc;
17616     SourceRange ERange;
17617     Expr *SimpleRefExpr = RefExpr;
17618     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17619     if (Res.second) {
17620       // It will be analyzed later.
17621       Vars.push_back(RefExpr);
17622       SrcExprs.push_back(nullptr);
17623       DstExprs.push_back(nullptr);
17624       AssignmentOps.push_back(nullptr);
17625     }
17626     ValueDecl *D = Res.first;
17627     if (!D)
17628       continue;
17629 
17630     QualType Type = D->getType();
17631     auto *VD = dyn_cast<VarDecl>(D);
17632 
17633     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
17634     //  A variable that appears in a lastprivate clause must not have an
17635     //  incomplete type or a reference type.
17636     if (RequireCompleteType(ELoc, Type,
17637                             diag::err_omp_lastprivate_incomplete_type))
17638       continue;
17639     Type = Type.getNonReferenceType();
17640 
17641     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17642     // A variable that is privatized must not have a const-qualified type
17643     // unless it is of class type with a mutable member. This restriction does
17644     // not apply to the firstprivate clause.
17645     //
17646     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
17647     // A variable that appears in a lastprivate clause must not have a
17648     // const-qualified type unless it is of class type with a mutable member.
17649     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
17650       continue;
17651 
17652     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
17653     // A list item that appears in a lastprivate clause with the conditional
17654     // modifier must be a scalar variable.
17655     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
17656       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
17657       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17658                                VarDecl::DeclarationOnly;
17659       Diag(D->getLocation(),
17660            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17661           << D;
17662       continue;
17663     }
17664 
17665     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
17666     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
17667     // in a Construct]
17668     //  Variables with the predetermined data-sharing attributes may not be
17669     //  listed in data-sharing attributes clauses, except for the cases
17670     //  listed below.
17671     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
17672     // A list item may appear in a firstprivate or lastprivate clause but not
17673     // both.
17674     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17675     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
17676         (isOpenMPDistributeDirective(CurrDir) ||
17677          DVar.CKind != OMPC_firstprivate) &&
17678         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
17679       Diag(ELoc, diag::err_omp_wrong_dsa)
17680           << getOpenMPClauseName(DVar.CKind)
17681           << getOpenMPClauseName(OMPC_lastprivate);
17682       reportOriginalDsa(*this, DSAStack, D, DVar);
17683       continue;
17684     }
17685 
17686     // OpenMP [2.14.3.5, Restrictions, p.2]
17687     // A list item that is private within a parallel region, or that appears in
17688     // the reduction clause of a parallel construct, must not appear in a
17689     // lastprivate clause on a worksharing construct if any of the corresponding
17690     // worksharing regions ever binds to any of the corresponding parallel
17691     // regions.
17692     DSAStackTy::DSAVarData TopDVar = DVar;
17693     if (isOpenMPWorksharingDirective(CurrDir) &&
17694         !isOpenMPParallelDirective(CurrDir) &&
17695         !isOpenMPTeamsDirective(CurrDir)) {
17696       DVar = DSAStack->getImplicitDSA(D, true);
17697       if (DVar.CKind != OMPC_shared) {
17698         Diag(ELoc, diag::err_omp_required_access)
17699             << getOpenMPClauseName(OMPC_lastprivate)
17700             << getOpenMPClauseName(OMPC_shared);
17701         reportOriginalDsa(*this, DSAStack, D, DVar);
17702         continue;
17703       }
17704     }
17705 
17706     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
17707     //  A variable of class type (or array thereof) that appears in a
17708     //  lastprivate clause requires an accessible, unambiguous default
17709     //  constructor for the class type, unless the list item is also specified
17710     //  in a firstprivate clause.
17711     //  A variable of class type (or array thereof) that appears in a
17712     //  lastprivate clause requires an accessible, unambiguous copy assignment
17713     //  operator for the class type.
17714     Type = Context.getBaseElementType(Type).getNonReferenceType();
17715     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
17716                                   Type.getUnqualifiedType(), ".lastprivate.src",
17717                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17718     DeclRefExpr *PseudoSrcExpr =
17719         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
17720     VarDecl *DstVD =
17721         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
17722                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17723     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
17724     // For arrays generate assignment operation for single element and replace
17725     // it by the original array element in CodeGen.
17726     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
17727                                          PseudoDstExpr, PseudoSrcExpr);
17728     if (AssignmentOp.isInvalid())
17729       continue;
17730     AssignmentOp =
17731         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
17732     if (AssignmentOp.isInvalid())
17733       continue;
17734 
17735     DeclRefExpr *Ref = nullptr;
17736     if (!VD && !CurContext->isDependentContext()) {
17737       if (TopDVar.CKind == OMPC_firstprivate) {
17738         Ref = TopDVar.PrivateCopy;
17739       } else {
17740         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17741         if (!isOpenMPCapturedDecl(D))
17742           ExprCaptures.push_back(Ref->getDecl());
17743       }
17744       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
17745           (!isOpenMPCapturedDecl(D) &&
17746            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
17747         ExprResult RefRes = DefaultLvalueConversion(Ref);
17748         if (!RefRes.isUsable())
17749           continue;
17750         ExprResult PostUpdateRes =
17751             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17752                        RefRes.get());
17753         if (!PostUpdateRes.isUsable())
17754           continue;
17755         ExprPostUpdates.push_back(
17756             IgnoredValueConversions(PostUpdateRes.get()).get());
17757       }
17758     }
17759     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
17760     Vars.push_back((VD || CurContext->isDependentContext())
17761                        ? RefExpr->IgnoreParens()
17762                        : Ref);
17763     SrcExprs.push_back(PseudoSrcExpr);
17764     DstExprs.push_back(PseudoDstExpr);
17765     AssignmentOps.push_back(AssignmentOp.get());
17766   }
17767 
17768   if (Vars.empty())
17769     return nullptr;
17770 
17771   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17772                                       Vars, SrcExprs, DstExprs, AssignmentOps,
17773                                       LPKind, LPKindLoc, ColonLoc,
17774                                       buildPreInits(Context, ExprCaptures),
17775                                       buildPostUpdate(*this, ExprPostUpdates));
17776 }
17777 
17778 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
17779                                          SourceLocation StartLoc,
17780                                          SourceLocation LParenLoc,
17781                                          SourceLocation EndLoc) {
17782   SmallVector<Expr *, 8> Vars;
17783   for (Expr *RefExpr : VarList) {
17784     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
17785     SourceLocation ELoc;
17786     SourceRange ERange;
17787     Expr *SimpleRefExpr = RefExpr;
17788     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17789     if (Res.second) {
17790       // It will be analyzed later.
17791       Vars.push_back(RefExpr);
17792     }
17793     ValueDecl *D = Res.first;
17794     if (!D)
17795       continue;
17796 
17797     auto *VD = dyn_cast<VarDecl>(D);
17798     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
17799     // in a Construct]
17800     //  Variables with the predetermined data-sharing attributes may not be
17801     //  listed in data-sharing attributes clauses, except for the cases
17802     //  listed below. For these exceptions only, listing a predetermined
17803     //  variable in a data-sharing attribute clause is allowed and overrides
17804     //  the variable's predetermined data-sharing attributes.
17805     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17806     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
17807         DVar.RefExpr) {
17808       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17809                                           << getOpenMPClauseName(OMPC_shared);
17810       reportOriginalDsa(*this, DSAStack, D, DVar);
17811       continue;
17812     }
17813 
17814     DeclRefExpr *Ref = nullptr;
17815     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
17816       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17817     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
17818     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
17819                        ? RefExpr->IgnoreParens()
17820                        : Ref);
17821   }
17822 
17823   if (Vars.empty())
17824     return nullptr;
17825 
17826   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
17827 }
17828 
17829 namespace {
17830 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
17831   DSAStackTy *Stack;
17832 
17833 public:
17834   bool VisitDeclRefExpr(DeclRefExpr *E) {
17835     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
17836       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
17837       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
17838         return false;
17839       if (DVar.CKind != OMPC_unknown)
17840         return true;
17841       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
17842           VD,
17843           [](OpenMPClauseKind C, bool AppliedToPointee) {
17844             return isOpenMPPrivate(C) && !AppliedToPointee;
17845           },
17846           [](OpenMPDirectiveKind) { return true; },
17847           /*FromParent=*/true);
17848       return DVarPrivate.CKind != OMPC_unknown;
17849     }
17850     return false;
17851   }
17852   bool VisitStmt(Stmt *S) {
17853     for (Stmt *Child : S->children()) {
17854       if (Child && Visit(Child))
17855         return true;
17856     }
17857     return false;
17858   }
17859   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
17860 };
17861 } // namespace
17862 
17863 namespace {
17864 // Transform MemberExpression for specified FieldDecl of current class to
17865 // DeclRefExpr to specified OMPCapturedExprDecl.
17866 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
17867   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
17868   ValueDecl *Field = nullptr;
17869   DeclRefExpr *CapturedExpr = nullptr;
17870 
17871 public:
17872   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
17873       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
17874 
17875   ExprResult TransformMemberExpr(MemberExpr *E) {
17876     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
17877         E->getMemberDecl() == Field) {
17878       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
17879       return CapturedExpr;
17880     }
17881     return BaseTransform::TransformMemberExpr(E);
17882   }
17883   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
17884 };
17885 } // namespace
17886 
17887 template <typename T, typename U>
17888 static T filterLookupForUDReductionAndMapper(
17889     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
17890   for (U &Set : Lookups) {
17891     for (auto *D : Set) {
17892       if (T Res = Gen(cast<ValueDecl>(D)))
17893         return Res;
17894     }
17895   }
17896   return T();
17897 }
17898 
17899 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
17900   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
17901 
17902   for (auto RD : D->redecls()) {
17903     // Don't bother with extra checks if we already know this one isn't visible.
17904     if (RD == D)
17905       continue;
17906 
17907     auto ND = cast<NamedDecl>(RD);
17908     if (LookupResult::isVisible(SemaRef, ND))
17909       return ND;
17910   }
17911 
17912   return nullptr;
17913 }
17914 
17915 static void
17916 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
17917                         SourceLocation Loc, QualType Ty,
17918                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
17919   // Find all of the associated namespaces and classes based on the
17920   // arguments we have.
17921   Sema::AssociatedNamespaceSet AssociatedNamespaces;
17922   Sema::AssociatedClassSet AssociatedClasses;
17923   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
17924   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
17925                                              AssociatedClasses);
17926 
17927   // C++ [basic.lookup.argdep]p3:
17928   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
17929   //   and let Y be the lookup set produced by argument dependent
17930   //   lookup (defined as follows). If X contains [...] then Y is
17931   //   empty. Otherwise Y is the set of declarations found in the
17932   //   namespaces associated with the argument types as described
17933   //   below. The set of declarations found by the lookup of the name
17934   //   is the union of X and Y.
17935   //
17936   // Here, we compute Y and add its members to the overloaded
17937   // candidate set.
17938   for (auto *NS : AssociatedNamespaces) {
17939     //   When considering an associated namespace, the lookup is the
17940     //   same as the lookup performed when the associated namespace is
17941     //   used as a qualifier (3.4.3.2) except that:
17942     //
17943     //     -- Any using-directives in the associated namespace are
17944     //        ignored.
17945     //
17946     //     -- Any namespace-scope friend functions declared in
17947     //        associated classes are visible within their respective
17948     //        namespaces even if they are not visible during an ordinary
17949     //        lookup (11.4).
17950     DeclContext::lookup_result R = NS->lookup(Id.getName());
17951     for (auto *D : R) {
17952       auto *Underlying = D;
17953       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
17954         Underlying = USD->getTargetDecl();
17955 
17956       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
17957           !isa<OMPDeclareMapperDecl>(Underlying))
17958         continue;
17959 
17960       if (!SemaRef.isVisible(D)) {
17961         D = findAcceptableDecl(SemaRef, D);
17962         if (!D)
17963           continue;
17964         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
17965           Underlying = USD->getTargetDecl();
17966       }
17967       Lookups.emplace_back();
17968       Lookups.back().addDecl(Underlying);
17969     }
17970   }
17971 }
17972 
17973 static ExprResult
17974 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
17975                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
17976                          const DeclarationNameInfo &ReductionId, QualType Ty,
17977                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
17978   if (ReductionIdScopeSpec.isInvalid())
17979     return ExprError();
17980   SmallVector<UnresolvedSet<8>, 4> Lookups;
17981   if (S) {
17982     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
17983     Lookup.suppressDiagnostics();
17984     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
17985       NamedDecl *D = Lookup.getRepresentativeDecl();
17986       do {
17987         S = S->getParent();
17988       } while (S && !S->isDeclScope(D));
17989       if (S)
17990         S = S->getParent();
17991       Lookups.emplace_back();
17992       Lookups.back().append(Lookup.begin(), Lookup.end());
17993       Lookup.clear();
17994     }
17995   } else if (auto *ULE =
17996                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
17997     Lookups.push_back(UnresolvedSet<8>());
17998     Decl *PrevD = nullptr;
17999     for (NamedDecl *D : ULE->decls()) {
18000       if (D == PrevD)
18001         Lookups.push_back(UnresolvedSet<8>());
18002       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
18003         Lookups.back().addDecl(DRD);
18004       PrevD = D;
18005     }
18006   }
18007   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
18008       Ty->isInstantiationDependentType() ||
18009       Ty->containsUnexpandedParameterPack() ||
18010       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
18011         return !D->isInvalidDecl() &&
18012                (D->getType()->isDependentType() ||
18013                 D->getType()->isInstantiationDependentType() ||
18014                 D->getType()->containsUnexpandedParameterPack());
18015       })) {
18016     UnresolvedSet<8> ResSet;
18017     for (const UnresolvedSet<8> &Set : Lookups) {
18018       if (Set.empty())
18019         continue;
18020       ResSet.append(Set.begin(), Set.end());
18021       // The last item marks the end of all declarations at the specified scope.
18022       ResSet.addDecl(Set[Set.size() - 1]);
18023     }
18024     return UnresolvedLookupExpr::Create(
18025         SemaRef.Context, /*NamingClass=*/nullptr,
18026         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
18027         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
18028   }
18029   // Lookup inside the classes.
18030   // C++ [over.match.oper]p3:
18031   //   For a unary operator @ with an operand of a type whose
18032   //   cv-unqualified version is T1, and for a binary operator @ with
18033   //   a left operand of a type whose cv-unqualified version is T1 and
18034   //   a right operand of a type whose cv-unqualified version is T2,
18035   //   three sets of candidate functions, designated member
18036   //   candidates, non-member candidates and built-in candidates, are
18037   //   constructed as follows:
18038   //     -- If T1 is a complete class type or a class currently being
18039   //        defined, the set of member candidates is the result of the
18040   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
18041   //        the set of member candidates is empty.
18042   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
18043   Lookup.suppressDiagnostics();
18044   if (const auto *TyRec = Ty->getAs<RecordType>()) {
18045     // Complete the type if it can be completed.
18046     // If the type is neither complete nor being defined, bail out now.
18047     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
18048         TyRec->getDecl()->getDefinition()) {
18049       Lookup.clear();
18050       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
18051       if (Lookup.empty()) {
18052         Lookups.emplace_back();
18053         Lookups.back().append(Lookup.begin(), Lookup.end());
18054       }
18055     }
18056   }
18057   // Perform ADL.
18058   if (SemaRef.getLangOpts().CPlusPlus)
18059     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
18060   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18061           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
18062             if (!D->isInvalidDecl() &&
18063                 SemaRef.Context.hasSameType(D->getType(), Ty))
18064               return D;
18065             return nullptr;
18066           }))
18067     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
18068                                     VK_LValue, Loc);
18069   if (SemaRef.getLangOpts().CPlusPlus) {
18070     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18071             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
18072               if (!D->isInvalidDecl() &&
18073                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
18074                   !Ty.isMoreQualifiedThan(D->getType()))
18075                 return D;
18076               return nullptr;
18077             })) {
18078       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
18079                          /*DetectVirtual=*/false);
18080       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
18081         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
18082                 VD->getType().getUnqualifiedType()))) {
18083           if (SemaRef.CheckBaseClassAccess(
18084                   Loc, VD->getType(), Ty, Paths.front(),
18085                   /*DiagID=*/0) != Sema::AR_inaccessible) {
18086             SemaRef.BuildBasePathArray(Paths, BasePath);
18087             return SemaRef.BuildDeclRefExpr(
18088                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
18089           }
18090         }
18091       }
18092     }
18093   }
18094   if (ReductionIdScopeSpec.isSet()) {
18095     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
18096         << Ty << Range;
18097     return ExprError();
18098   }
18099   return ExprEmpty();
18100 }
18101 
18102 namespace {
18103 /// Data for the reduction-based clauses.
18104 struct ReductionData {
18105   /// List of original reduction items.
18106   SmallVector<Expr *, 8> Vars;
18107   /// List of private copies of the reduction items.
18108   SmallVector<Expr *, 8> Privates;
18109   /// LHS expressions for the reduction_op expressions.
18110   SmallVector<Expr *, 8> LHSs;
18111   /// RHS expressions for the reduction_op expressions.
18112   SmallVector<Expr *, 8> RHSs;
18113   /// Reduction operation expression.
18114   SmallVector<Expr *, 8> ReductionOps;
18115   /// inscan copy operation expressions.
18116   SmallVector<Expr *, 8> InscanCopyOps;
18117   /// inscan copy temp array expressions for prefix sums.
18118   SmallVector<Expr *, 8> InscanCopyArrayTemps;
18119   /// inscan copy temp array element expressions for prefix sums.
18120   SmallVector<Expr *, 8> InscanCopyArrayElems;
18121   /// Taskgroup descriptors for the corresponding reduction items in
18122   /// in_reduction clauses.
18123   SmallVector<Expr *, 8> TaskgroupDescriptors;
18124   /// List of captures for clause.
18125   SmallVector<Decl *, 4> ExprCaptures;
18126   /// List of postupdate expressions.
18127   SmallVector<Expr *, 4> ExprPostUpdates;
18128   /// Reduction modifier.
18129   unsigned RedModifier = 0;
18130   ReductionData() = delete;
18131   /// Reserves required memory for the reduction data.
18132   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
18133     Vars.reserve(Size);
18134     Privates.reserve(Size);
18135     LHSs.reserve(Size);
18136     RHSs.reserve(Size);
18137     ReductionOps.reserve(Size);
18138     if (RedModifier == OMPC_REDUCTION_inscan) {
18139       InscanCopyOps.reserve(Size);
18140       InscanCopyArrayTemps.reserve(Size);
18141       InscanCopyArrayElems.reserve(Size);
18142     }
18143     TaskgroupDescriptors.reserve(Size);
18144     ExprCaptures.reserve(Size);
18145     ExprPostUpdates.reserve(Size);
18146   }
18147   /// Stores reduction item and reduction operation only (required for dependent
18148   /// reduction item).
18149   void push(Expr *Item, Expr *ReductionOp) {
18150     Vars.emplace_back(Item);
18151     Privates.emplace_back(nullptr);
18152     LHSs.emplace_back(nullptr);
18153     RHSs.emplace_back(nullptr);
18154     ReductionOps.emplace_back(ReductionOp);
18155     TaskgroupDescriptors.emplace_back(nullptr);
18156     if (RedModifier == OMPC_REDUCTION_inscan) {
18157       InscanCopyOps.push_back(nullptr);
18158       InscanCopyArrayTemps.push_back(nullptr);
18159       InscanCopyArrayElems.push_back(nullptr);
18160     }
18161   }
18162   /// Stores reduction data.
18163   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
18164             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
18165             Expr *CopyArrayElem) {
18166     Vars.emplace_back(Item);
18167     Privates.emplace_back(Private);
18168     LHSs.emplace_back(LHS);
18169     RHSs.emplace_back(RHS);
18170     ReductionOps.emplace_back(ReductionOp);
18171     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
18172     if (RedModifier == OMPC_REDUCTION_inscan) {
18173       InscanCopyOps.push_back(CopyOp);
18174       InscanCopyArrayTemps.push_back(CopyArrayTemp);
18175       InscanCopyArrayElems.push_back(CopyArrayElem);
18176     } else {
18177       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
18178              CopyArrayElem == nullptr &&
18179              "Copy operation must be used for inscan reductions only.");
18180     }
18181   }
18182 };
18183 } // namespace
18184 
18185 static bool checkOMPArraySectionConstantForReduction(
18186     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
18187     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
18188   const Expr *Length = OASE->getLength();
18189   if (Length == nullptr) {
18190     // For array sections of the form [1:] or [:], we would need to analyze
18191     // the lower bound...
18192     if (OASE->getColonLocFirst().isValid())
18193       return false;
18194 
18195     // This is an array subscript which has implicit length 1!
18196     SingleElement = true;
18197     ArraySizes.push_back(llvm::APSInt::get(1));
18198   } else {
18199     Expr::EvalResult Result;
18200     if (!Length->EvaluateAsInt(Result, Context))
18201       return false;
18202 
18203     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
18204     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
18205     ArraySizes.push_back(ConstantLengthValue);
18206   }
18207 
18208   // Get the base of this array section and walk up from there.
18209   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
18210 
18211   // We require length = 1 for all array sections except the right-most to
18212   // guarantee that the memory region is contiguous and has no holes in it.
18213   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
18214     Length = TempOASE->getLength();
18215     if (Length == nullptr) {
18216       // For array sections of the form [1:] or [:], we would need to analyze
18217       // the lower bound...
18218       if (OASE->getColonLocFirst().isValid())
18219         return false;
18220 
18221       // This is an array subscript which has implicit length 1!
18222       ArraySizes.push_back(llvm::APSInt::get(1));
18223     } else {
18224       Expr::EvalResult Result;
18225       if (!Length->EvaluateAsInt(Result, Context))
18226         return false;
18227 
18228       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
18229       if (ConstantLengthValue.getSExtValue() != 1)
18230         return false;
18231 
18232       ArraySizes.push_back(ConstantLengthValue);
18233     }
18234     Base = TempOASE->getBase()->IgnoreParenImpCasts();
18235   }
18236 
18237   // If we have a single element, we don't need to add the implicit lengths.
18238   if (!SingleElement) {
18239     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
18240       // Has implicit length 1!
18241       ArraySizes.push_back(llvm::APSInt::get(1));
18242       Base = TempASE->getBase()->IgnoreParenImpCasts();
18243     }
18244   }
18245 
18246   // This array section can be privatized as a single value or as a constant
18247   // sized array.
18248   return true;
18249 }
18250 
18251 static BinaryOperatorKind
18252 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
18253   if (BOK == BO_Add)
18254     return BO_AddAssign;
18255   if (BOK == BO_Mul)
18256     return BO_MulAssign;
18257   if (BOK == BO_And)
18258     return BO_AndAssign;
18259   if (BOK == BO_Or)
18260     return BO_OrAssign;
18261   if (BOK == BO_Xor)
18262     return BO_XorAssign;
18263   return BOK;
18264 }
18265 
18266 static bool actOnOMPReductionKindClause(
18267     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
18268     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
18269     SourceLocation ColonLoc, SourceLocation EndLoc,
18270     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18271     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
18272   DeclarationName DN = ReductionId.getName();
18273   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
18274   BinaryOperatorKind BOK = BO_Comma;
18275 
18276   ASTContext &Context = S.Context;
18277   // OpenMP [2.14.3.6, reduction clause]
18278   // C
18279   // reduction-identifier is either an identifier or one of the following
18280   // operators: +, -, *,  &, |, ^, && and ||
18281   // C++
18282   // reduction-identifier is either an id-expression or one of the following
18283   // operators: +, -, *, &, |, ^, && and ||
18284   switch (OOK) {
18285   case OO_Plus:
18286   case OO_Minus:
18287     BOK = BO_Add;
18288     break;
18289   case OO_Star:
18290     BOK = BO_Mul;
18291     break;
18292   case OO_Amp:
18293     BOK = BO_And;
18294     break;
18295   case OO_Pipe:
18296     BOK = BO_Or;
18297     break;
18298   case OO_Caret:
18299     BOK = BO_Xor;
18300     break;
18301   case OO_AmpAmp:
18302     BOK = BO_LAnd;
18303     break;
18304   case OO_PipePipe:
18305     BOK = BO_LOr;
18306     break;
18307   case OO_New:
18308   case OO_Delete:
18309   case OO_Array_New:
18310   case OO_Array_Delete:
18311   case OO_Slash:
18312   case OO_Percent:
18313   case OO_Tilde:
18314   case OO_Exclaim:
18315   case OO_Equal:
18316   case OO_Less:
18317   case OO_Greater:
18318   case OO_LessEqual:
18319   case OO_GreaterEqual:
18320   case OO_PlusEqual:
18321   case OO_MinusEqual:
18322   case OO_StarEqual:
18323   case OO_SlashEqual:
18324   case OO_PercentEqual:
18325   case OO_CaretEqual:
18326   case OO_AmpEqual:
18327   case OO_PipeEqual:
18328   case OO_LessLess:
18329   case OO_GreaterGreater:
18330   case OO_LessLessEqual:
18331   case OO_GreaterGreaterEqual:
18332   case OO_EqualEqual:
18333   case OO_ExclaimEqual:
18334   case OO_Spaceship:
18335   case OO_PlusPlus:
18336   case OO_MinusMinus:
18337   case OO_Comma:
18338   case OO_ArrowStar:
18339   case OO_Arrow:
18340   case OO_Call:
18341   case OO_Subscript:
18342   case OO_Conditional:
18343   case OO_Coawait:
18344   case NUM_OVERLOADED_OPERATORS:
18345     llvm_unreachable("Unexpected reduction identifier");
18346   case OO_None:
18347     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
18348       if (II->isStr("max"))
18349         BOK = BO_GT;
18350       else if (II->isStr("min"))
18351         BOK = BO_LT;
18352     }
18353     break;
18354   }
18355   SourceRange ReductionIdRange;
18356   if (ReductionIdScopeSpec.isValid())
18357     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
18358   else
18359     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
18360   ReductionIdRange.setEnd(ReductionId.getEndLoc());
18361 
18362   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
18363   bool FirstIter = true;
18364   for (Expr *RefExpr : VarList) {
18365     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
18366     // OpenMP [2.1, C/C++]
18367     //  A list item is a variable or array section, subject to the restrictions
18368     //  specified in Section 2.4 on page 42 and in each of the sections
18369     // describing clauses and directives for which a list appears.
18370     // OpenMP  [2.14.3.3, Restrictions, p.1]
18371     //  A variable that is part of another variable (as an array or
18372     //  structure element) cannot appear in a private clause.
18373     if (!FirstIter && IR != ER)
18374       ++IR;
18375     FirstIter = false;
18376     SourceLocation ELoc;
18377     SourceRange ERange;
18378     Expr *SimpleRefExpr = RefExpr;
18379     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
18380                               /*AllowArraySection=*/true);
18381     if (Res.second) {
18382       // Try to find 'declare reduction' corresponding construct before using
18383       // builtin/overloaded operators.
18384       QualType Type = Context.DependentTy;
18385       CXXCastPath BasePath;
18386       ExprResult DeclareReductionRef = buildDeclareReductionRef(
18387           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
18388           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
18389       Expr *ReductionOp = nullptr;
18390       if (S.CurContext->isDependentContext() &&
18391           (DeclareReductionRef.isUnset() ||
18392            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
18393         ReductionOp = DeclareReductionRef.get();
18394       // It will be analyzed later.
18395       RD.push(RefExpr, ReductionOp);
18396     }
18397     ValueDecl *D = Res.first;
18398     if (!D)
18399       continue;
18400 
18401     Expr *TaskgroupDescriptor = nullptr;
18402     QualType Type;
18403     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
18404     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
18405     if (ASE) {
18406       Type = ASE->getType().getNonReferenceType();
18407     } else if (OASE) {
18408       QualType BaseType =
18409           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18410       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18411         Type = ATy->getElementType();
18412       else
18413         Type = BaseType->getPointeeType();
18414       Type = Type.getNonReferenceType();
18415     } else {
18416       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
18417     }
18418     auto *VD = dyn_cast<VarDecl>(D);
18419 
18420     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
18421     //  A variable that appears in a private clause must not have an incomplete
18422     //  type or a reference type.
18423     if (S.RequireCompleteType(ELoc, D->getType(),
18424                               diag::err_omp_reduction_incomplete_type))
18425       continue;
18426     // OpenMP [2.14.3.6, reduction clause, Restrictions]
18427     // A list item that appears in a reduction clause must not be
18428     // const-qualified.
18429     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
18430                                   /*AcceptIfMutable*/ false, ASE || OASE))
18431       continue;
18432 
18433     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
18434     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
18435     //  If a list-item is a reference type then it must bind to the same object
18436     //  for all threads of the team.
18437     if (!ASE && !OASE) {
18438       if (VD) {
18439         VarDecl *VDDef = VD->getDefinition();
18440         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
18441           DSARefChecker Check(Stack);
18442           if (Check.Visit(VDDef->getInit())) {
18443             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
18444                 << getOpenMPClauseName(ClauseKind) << ERange;
18445             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
18446             continue;
18447           }
18448         }
18449       }
18450 
18451       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
18452       // in a Construct]
18453       //  Variables with the predetermined data-sharing attributes may not be
18454       //  listed in data-sharing attributes clauses, except for the cases
18455       //  listed below. For these exceptions only, listing a predetermined
18456       //  variable in a data-sharing attribute clause is allowed and overrides
18457       //  the variable's predetermined data-sharing attributes.
18458       // OpenMP [2.14.3.6, Restrictions, p.3]
18459       //  Any number of reduction clauses can be specified on the directive,
18460       //  but a list item can appear only once in the reduction clauses for that
18461       //  directive.
18462       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
18463       if (DVar.CKind == OMPC_reduction) {
18464         S.Diag(ELoc, diag::err_omp_once_referenced)
18465             << getOpenMPClauseName(ClauseKind);
18466         if (DVar.RefExpr)
18467           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
18468         continue;
18469       }
18470       if (DVar.CKind != OMPC_unknown) {
18471         S.Diag(ELoc, diag::err_omp_wrong_dsa)
18472             << getOpenMPClauseName(DVar.CKind)
18473             << getOpenMPClauseName(OMPC_reduction);
18474         reportOriginalDsa(S, Stack, D, DVar);
18475         continue;
18476       }
18477 
18478       // OpenMP [2.14.3.6, Restrictions, p.1]
18479       //  A list item that appears in a reduction clause of a worksharing
18480       //  construct must be shared in the parallel regions to which any of the
18481       //  worksharing regions arising from the worksharing construct bind.
18482       if (isOpenMPWorksharingDirective(CurrDir) &&
18483           !isOpenMPParallelDirective(CurrDir) &&
18484           !isOpenMPTeamsDirective(CurrDir)) {
18485         DVar = Stack->getImplicitDSA(D, true);
18486         if (DVar.CKind != OMPC_shared) {
18487           S.Diag(ELoc, diag::err_omp_required_access)
18488               << getOpenMPClauseName(OMPC_reduction)
18489               << getOpenMPClauseName(OMPC_shared);
18490           reportOriginalDsa(S, Stack, D, DVar);
18491           continue;
18492         }
18493       }
18494     } else {
18495       // Threadprivates cannot be shared between threads, so dignose if the base
18496       // is a threadprivate variable.
18497       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
18498       if (DVar.CKind == OMPC_threadprivate) {
18499         S.Diag(ELoc, diag::err_omp_wrong_dsa)
18500             << getOpenMPClauseName(DVar.CKind)
18501             << getOpenMPClauseName(OMPC_reduction);
18502         reportOriginalDsa(S, Stack, D, DVar);
18503         continue;
18504       }
18505     }
18506 
18507     // Try to find 'declare reduction' corresponding construct before using
18508     // builtin/overloaded operators.
18509     CXXCastPath BasePath;
18510     ExprResult DeclareReductionRef = buildDeclareReductionRef(
18511         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
18512         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
18513     if (DeclareReductionRef.isInvalid())
18514       continue;
18515     if (S.CurContext->isDependentContext() &&
18516         (DeclareReductionRef.isUnset() ||
18517          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
18518       RD.push(RefExpr, DeclareReductionRef.get());
18519       continue;
18520     }
18521     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
18522       // Not allowed reduction identifier is found.
18523       S.Diag(ReductionId.getBeginLoc(),
18524              diag::err_omp_unknown_reduction_identifier)
18525           << Type << ReductionIdRange;
18526       continue;
18527     }
18528 
18529     // OpenMP [2.14.3.6, reduction clause, Restrictions]
18530     // The type of a list item that appears in a reduction clause must be valid
18531     // for the reduction-identifier. For a max or min reduction in C, the type
18532     // of the list item must be an allowed arithmetic data type: char, int,
18533     // float, double, or _Bool, possibly modified with long, short, signed, or
18534     // unsigned. For a max or min reduction in C++, the type of the list item
18535     // must be an allowed arithmetic data type: char, wchar_t, int, float,
18536     // double, or bool, possibly modified with long, short, signed, or unsigned.
18537     if (DeclareReductionRef.isUnset()) {
18538       if ((BOK == BO_GT || BOK == BO_LT) &&
18539           !(Type->isScalarType() ||
18540             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
18541         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
18542             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
18543         if (!ASE && !OASE) {
18544           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18545                                    VarDecl::DeclarationOnly;
18546           S.Diag(D->getLocation(),
18547                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18548               << D;
18549         }
18550         continue;
18551       }
18552       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
18553           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
18554         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
18555             << getOpenMPClauseName(ClauseKind);
18556         if (!ASE && !OASE) {
18557           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18558                                    VarDecl::DeclarationOnly;
18559           S.Diag(D->getLocation(),
18560                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18561               << D;
18562         }
18563         continue;
18564       }
18565     }
18566 
18567     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
18568     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
18569                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
18570     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
18571                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
18572     QualType PrivateTy = Type;
18573 
18574     // Try if we can determine constant lengths for all array sections and avoid
18575     // the VLA.
18576     bool ConstantLengthOASE = false;
18577     if (OASE) {
18578       bool SingleElement;
18579       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
18580       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
18581           Context, OASE, SingleElement, ArraySizes);
18582 
18583       // If we don't have a single element, we must emit a constant array type.
18584       if (ConstantLengthOASE && !SingleElement) {
18585         for (llvm::APSInt &Size : ArraySizes)
18586           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
18587                                                    ArrayType::Normal,
18588                                                    /*IndexTypeQuals=*/0);
18589       }
18590     }
18591 
18592     if ((OASE && !ConstantLengthOASE) ||
18593         (!OASE && !ASE &&
18594          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
18595       if (!Context.getTargetInfo().isVLASupported()) {
18596         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
18597           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
18598           S.Diag(ELoc, diag::note_vla_unsupported);
18599           continue;
18600         } else {
18601           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
18602           S.targetDiag(ELoc, diag::note_vla_unsupported);
18603         }
18604       }
18605       // For arrays/array sections only:
18606       // Create pseudo array type for private copy. The size for this array will
18607       // be generated during codegen.
18608       // For array subscripts or single variables Private Ty is the same as Type
18609       // (type of the variable or single array element).
18610       PrivateTy = Context.getVariableArrayType(
18611           Type,
18612           new (Context)
18613               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
18614           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
18615     } else if (!ASE && !OASE &&
18616                Context.getAsArrayType(D->getType().getNonReferenceType())) {
18617       PrivateTy = D->getType().getNonReferenceType();
18618     }
18619     // Private copy.
18620     VarDecl *PrivateVD =
18621         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
18622                      D->hasAttrs() ? &D->getAttrs() : nullptr,
18623                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
18624     // Add initializer for private variable.
18625     Expr *Init = nullptr;
18626     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
18627     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
18628     if (DeclareReductionRef.isUsable()) {
18629       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
18630       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
18631       if (DRD->getInitializer()) {
18632         Init = DRDRef;
18633         RHSVD->setInit(DRDRef);
18634         RHSVD->setInitStyle(VarDecl::CallInit);
18635       }
18636     } else {
18637       switch (BOK) {
18638       case BO_Add:
18639       case BO_Xor:
18640       case BO_Or:
18641       case BO_LOr:
18642         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
18643         if (Type->isScalarType() || Type->isAnyComplexType())
18644           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
18645         break;
18646       case BO_Mul:
18647       case BO_LAnd:
18648         if (Type->isScalarType() || Type->isAnyComplexType()) {
18649           // '*' and '&&' reduction ops - initializer is '1'.
18650           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
18651         }
18652         break;
18653       case BO_And: {
18654         // '&' reduction op - initializer is '~0'.
18655         QualType OrigType = Type;
18656         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
18657           Type = ComplexTy->getElementType();
18658         if (Type->isRealFloatingType()) {
18659           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
18660               Context.getFloatTypeSemantics(Type));
18661           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
18662                                          Type, ELoc);
18663         } else if (Type->isScalarType()) {
18664           uint64_t Size = Context.getTypeSize(Type);
18665           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
18666           llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
18667           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
18668         }
18669         if (Init && OrigType->isAnyComplexType()) {
18670           // Init = 0xFFFF + 0xFFFFi;
18671           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
18672           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
18673         }
18674         Type = OrigType;
18675         break;
18676       }
18677       case BO_LT:
18678       case BO_GT: {
18679         // 'min' reduction op - initializer is 'Largest representable number in
18680         // the reduction list item type'.
18681         // 'max' reduction op - initializer is 'Least representable number in
18682         // the reduction list item type'.
18683         if (Type->isIntegerType() || Type->isPointerType()) {
18684           bool IsSigned = Type->hasSignedIntegerRepresentation();
18685           uint64_t Size = Context.getTypeSize(Type);
18686           QualType IntTy =
18687               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
18688           llvm::APInt InitValue =
18689               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
18690                                         : llvm::APInt::getMinValue(Size)
18691               : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
18692                              : llvm::APInt::getMaxValue(Size);
18693           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
18694           if (Type->isPointerType()) {
18695             // Cast to pointer type.
18696             ExprResult CastExpr = S.BuildCStyleCastExpr(
18697                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
18698             if (CastExpr.isInvalid())
18699               continue;
18700             Init = CastExpr.get();
18701           }
18702         } else if (Type->isRealFloatingType()) {
18703           llvm::APFloat InitValue = llvm::APFloat::getLargest(
18704               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
18705           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
18706                                          Type, ELoc);
18707         }
18708         break;
18709       }
18710       case BO_PtrMemD:
18711       case BO_PtrMemI:
18712       case BO_MulAssign:
18713       case BO_Div:
18714       case BO_Rem:
18715       case BO_Sub:
18716       case BO_Shl:
18717       case BO_Shr:
18718       case BO_LE:
18719       case BO_GE:
18720       case BO_EQ:
18721       case BO_NE:
18722       case BO_Cmp:
18723       case BO_AndAssign:
18724       case BO_XorAssign:
18725       case BO_OrAssign:
18726       case BO_Assign:
18727       case BO_AddAssign:
18728       case BO_SubAssign:
18729       case BO_DivAssign:
18730       case BO_RemAssign:
18731       case BO_ShlAssign:
18732       case BO_ShrAssign:
18733       case BO_Comma:
18734         llvm_unreachable("Unexpected reduction operation");
18735       }
18736     }
18737     if (Init && DeclareReductionRef.isUnset()) {
18738       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
18739       // Store initializer for single element in private copy. Will be used
18740       // during codegen.
18741       PrivateVD->setInit(RHSVD->getInit());
18742       PrivateVD->setInitStyle(RHSVD->getInitStyle());
18743     } else if (!Init) {
18744       S.ActOnUninitializedDecl(RHSVD);
18745       // Store initializer for single element in private copy. Will be used
18746       // during codegen.
18747       PrivateVD->setInit(RHSVD->getInit());
18748       PrivateVD->setInitStyle(RHSVD->getInitStyle());
18749     }
18750     if (RHSVD->isInvalidDecl())
18751       continue;
18752     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
18753       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
18754           << Type << ReductionIdRange;
18755       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18756                                VarDecl::DeclarationOnly;
18757       S.Diag(D->getLocation(),
18758              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18759           << D;
18760       continue;
18761     }
18762     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
18763     ExprResult ReductionOp;
18764     if (DeclareReductionRef.isUsable()) {
18765       QualType RedTy = DeclareReductionRef.get()->getType();
18766       QualType PtrRedTy = Context.getPointerType(RedTy);
18767       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
18768       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
18769       if (!BasePath.empty()) {
18770         LHS = S.DefaultLvalueConversion(LHS.get());
18771         RHS = S.DefaultLvalueConversion(RHS.get());
18772         LHS = ImplicitCastExpr::Create(
18773             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
18774             LHS.get()->getValueKind(), FPOptionsOverride());
18775         RHS = ImplicitCastExpr::Create(
18776             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
18777             RHS.get()->getValueKind(), FPOptionsOverride());
18778       }
18779       FunctionProtoType::ExtProtoInfo EPI;
18780       QualType Params[] = {PtrRedTy, PtrRedTy};
18781       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
18782       auto *OVE = new (Context) OpaqueValueExpr(
18783           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
18784           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
18785       Expr *Args[] = {LHS.get(), RHS.get()};
18786       ReductionOp =
18787           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
18788                            S.CurFPFeatureOverrides());
18789     } else {
18790       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
18791       if (Type->isRecordType() && CombBOK != BOK) {
18792         Sema::TentativeAnalysisScope Trap(S);
18793         ReductionOp =
18794             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
18795                          CombBOK, LHSDRE, RHSDRE);
18796       }
18797       if (!ReductionOp.isUsable()) {
18798         ReductionOp =
18799             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
18800                          LHSDRE, RHSDRE);
18801         if (ReductionOp.isUsable()) {
18802           if (BOK != BO_LT && BOK != BO_GT) {
18803             ReductionOp =
18804                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
18805                              BO_Assign, LHSDRE, ReductionOp.get());
18806           } else {
18807             auto *ConditionalOp = new (Context)
18808                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
18809                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
18810             ReductionOp =
18811                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
18812                              BO_Assign, LHSDRE, ConditionalOp);
18813           }
18814         }
18815       }
18816       if (ReductionOp.isUsable())
18817         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
18818                                             /*DiscardedValue*/ false);
18819       if (!ReductionOp.isUsable())
18820         continue;
18821     }
18822 
18823     // Add copy operations for inscan reductions.
18824     // LHS = RHS;
18825     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
18826     if (ClauseKind == OMPC_reduction &&
18827         RD.RedModifier == OMPC_REDUCTION_inscan) {
18828       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
18829       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
18830                                RHS.get());
18831       if (!CopyOpRes.isUsable())
18832         continue;
18833       CopyOpRes =
18834           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
18835       if (!CopyOpRes.isUsable())
18836         continue;
18837       // For simd directive and simd-based directives in simd mode no need to
18838       // construct temp array, need just a single temp element.
18839       if (Stack->getCurrentDirective() == OMPD_simd ||
18840           (S.getLangOpts().OpenMPSimd &&
18841            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
18842         VarDecl *TempArrayVD =
18843             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
18844                          D->hasAttrs() ? &D->getAttrs() : nullptr);
18845         // Add a constructor to the temp decl.
18846         S.ActOnUninitializedDecl(TempArrayVD);
18847         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
18848       } else {
18849         // Build temp array for prefix sum.
18850         auto *Dim = new (S.Context)
18851             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
18852         QualType ArrayTy =
18853             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
18854                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
18855         VarDecl *TempArrayVD =
18856             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
18857                          D->hasAttrs() ? &D->getAttrs() : nullptr);
18858         // Add a constructor to the temp decl.
18859         S.ActOnUninitializedDecl(TempArrayVD);
18860         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
18861         TempArrayElem =
18862             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
18863         auto *Idx = new (S.Context)
18864             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
18865         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
18866                                                           ELoc, Idx, ELoc);
18867       }
18868     }
18869 
18870     // OpenMP [2.15.4.6, Restrictions, p.2]
18871     // A list item that appears in an in_reduction clause of a task construct
18872     // must appear in a task_reduction clause of a construct associated with a
18873     // taskgroup region that includes the participating task in its taskgroup
18874     // set. The construct associated with the innermost region that meets this
18875     // condition must specify the same reduction-identifier as the in_reduction
18876     // clause.
18877     if (ClauseKind == OMPC_in_reduction) {
18878       SourceRange ParentSR;
18879       BinaryOperatorKind ParentBOK;
18880       const Expr *ParentReductionOp = nullptr;
18881       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
18882       DSAStackTy::DSAVarData ParentBOKDSA =
18883           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
18884                                                   ParentBOKTD);
18885       DSAStackTy::DSAVarData ParentReductionOpDSA =
18886           Stack->getTopMostTaskgroupReductionData(
18887               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
18888       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
18889       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
18890       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
18891           (DeclareReductionRef.isUsable() && IsParentBOK) ||
18892           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
18893         bool EmitError = true;
18894         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
18895           llvm::FoldingSetNodeID RedId, ParentRedId;
18896           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
18897           DeclareReductionRef.get()->Profile(RedId, Context,
18898                                              /*Canonical=*/true);
18899           EmitError = RedId != ParentRedId;
18900         }
18901         if (EmitError) {
18902           S.Diag(ReductionId.getBeginLoc(),
18903                  diag::err_omp_reduction_identifier_mismatch)
18904               << ReductionIdRange << RefExpr->getSourceRange();
18905           S.Diag(ParentSR.getBegin(),
18906                  diag::note_omp_previous_reduction_identifier)
18907               << ParentSR
18908               << (IsParentBOK ? ParentBOKDSA.RefExpr
18909                               : ParentReductionOpDSA.RefExpr)
18910                      ->getSourceRange();
18911           continue;
18912         }
18913       }
18914       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
18915     }
18916 
18917     DeclRefExpr *Ref = nullptr;
18918     Expr *VarsExpr = RefExpr->IgnoreParens();
18919     if (!VD && !S.CurContext->isDependentContext()) {
18920       if (ASE || OASE) {
18921         TransformExprToCaptures RebuildToCapture(S, D);
18922         VarsExpr =
18923             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
18924         Ref = RebuildToCapture.getCapturedExpr();
18925       } else {
18926         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
18927       }
18928       if (!S.isOpenMPCapturedDecl(D)) {
18929         RD.ExprCaptures.emplace_back(Ref->getDecl());
18930         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
18931           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
18932           if (!RefRes.isUsable())
18933             continue;
18934           ExprResult PostUpdateRes =
18935               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
18936                            RefRes.get());
18937           if (!PostUpdateRes.isUsable())
18938             continue;
18939           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
18940               Stack->getCurrentDirective() == OMPD_taskgroup) {
18941             S.Diag(RefExpr->getExprLoc(),
18942                    diag::err_omp_reduction_non_addressable_expression)
18943                 << RefExpr->getSourceRange();
18944             continue;
18945           }
18946           RD.ExprPostUpdates.emplace_back(
18947               S.IgnoredValueConversions(PostUpdateRes.get()).get());
18948         }
18949       }
18950     }
18951     // All reduction items are still marked as reduction (to do not increase
18952     // code base size).
18953     unsigned Modifier = RD.RedModifier;
18954     // Consider task_reductions as reductions with task modifier. Required for
18955     // correct analysis of in_reduction clauses.
18956     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
18957       Modifier = OMPC_REDUCTION_task;
18958     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
18959                   ASE || OASE);
18960     if (Modifier == OMPC_REDUCTION_task &&
18961         (CurrDir == OMPD_taskgroup ||
18962          ((isOpenMPParallelDirective(CurrDir) ||
18963            isOpenMPWorksharingDirective(CurrDir)) &&
18964           !isOpenMPSimdDirective(CurrDir)))) {
18965       if (DeclareReductionRef.isUsable())
18966         Stack->addTaskgroupReductionData(D, ReductionIdRange,
18967                                          DeclareReductionRef.get());
18968       else
18969         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
18970     }
18971     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
18972             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
18973             TempArrayElem.get());
18974   }
18975   return RD.Vars.empty();
18976 }
18977 
18978 OMPClause *Sema::ActOnOpenMPReductionClause(
18979     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
18980     SourceLocation StartLoc, SourceLocation LParenLoc,
18981     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
18982     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18983     ArrayRef<Expr *> UnresolvedReductions) {
18984   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
18985     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
18986         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
18987                                    /*Last=*/OMPC_REDUCTION_unknown)
18988         << getOpenMPClauseName(OMPC_reduction);
18989     return nullptr;
18990   }
18991   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
18992   // A reduction clause with the inscan reduction-modifier may only appear on a
18993   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
18994   // construct, a parallel worksharing-loop construct or a parallel
18995   // worksharing-loop SIMD construct.
18996   if (Modifier == OMPC_REDUCTION_inscan &&
18997       (DSAStack->getCurrentDirective() != OMPD_for &&
18998        DSAStack->getCurrentDirective() != OMPD_for_simd &&
18999        DSAStack->getCurrentDirective() != OMPD_simd &&
19000        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
19001        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
19002     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
19003     return nullptr;
19004   }
19005 
19006   ReductionData RD(VarList.size(), Modifier);
19007   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
19008                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
19009                                   ReductionIdScopeSpec, ReductionId,
19010                                   UnresolvedReductions, RD))
19011     return nullptr;
19012 
19013   return OMPReductionClause::Create(
19014       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
19015       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
19016       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
19017       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
19018       buildPreInits(Context, RD.ExprCaptures),
19019       buildPostUpdate(*this, RD.ExprPostUpdates));
19020 }
19021 
19022 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
19023     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
19024     SourceLocation ColonLoc, SourceLocation EndLoc,
19025     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
19026     ArrayRef<Expr *> UnresolvedReductions) {
19027   ReductionData RD(VarList.size());
19028   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
19029                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
19030                                   ReductionIdScopeSpec, ReductionId,
19031                                   UnresolvedReductions, RD))
19032     return nullptr;
19033 
19034   return OMPTaskReductionClause::Create(
19035       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
19036       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
19037       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
19038       buildPreInits(Context, RD.ExprCaptures),
19039       buildPostUpdate(*this, RD.ExprPostUpdates));
19040 }
19041 
19042 OMPClause *Sema::ActOnOpenMPInReductionClause(
19043     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
19044     SourceLocation ColonLoc, SourceLocation EndLoc,
19045     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
19046     ArrayRef<Expr *> UnresolvedReductions) {
19047   ReductionData RD(VarList.size());
19048   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
19049                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
19050                                   ReductionIdScopeSpec, ReductionId,
19051                                   UnresolvedReductions, RD))
19052     return nullptr;
19053 
19054   return OMPInReductionClause::Create(
19055       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
19056       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
19057       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
19058       buildPreInits(Context, RD.ExprCaptures),
19059       buildPostUpdate(*this, RD.ExprPostUpdates));
19060 }
19061 
19062 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
19063                                      SourceLocation LinLoc) {
19064   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
19065       LinKind == OMPC_LINEAR_unknown) {
19066     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
19067     return true;
19068   }
19069   return false;
19070 }
19071 
19072 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
19073                                  OpenMPLinearClauseKind LinKind, QualType Type,
19074                                  bool IsDeclareSimd) {
19075   const auto *VD = dyn_cast_or_null<VarDecl>(D);
19076   // A variable must not have an incomplete type or a reference type.
19077   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
19078     return true;
19079   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
19080       !Type->isReferenceType()) {
19081     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
19082         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
19083     return true;
19084   }
19085   Type = Type.getNonReferenceType();
19086 
19087   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
19088   // A variable that is privatized must not have a const-qualified type
19089   // unless it is of class type with a mutable member. This restriction does
19090   // not apply to the firstprivate clause, nor to the linear clause on
19091   // declarative directives (like declare simd).
19092   if (!IsDeclareSimd &&
19093       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
19094     return true;
19095 
19096   // A list item must be of integral or pointer type.
19097   Type = Type.getUnqualifiedType().getCanonicalType();
19098   const auto *Ty = Type.getTypePtrOrNull();
19099   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
19100               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
19101     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
19102     if (D) {
19103       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
19104                                VarDecl::DeclarationOnly;
19105       Diag(D->getLocation(),
19106            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
19107           << D;
19108     }
19109     return true;
19110   }
19111   return false;
19112 }
19113 
19114 OMPClause *Sema::ActOnOpenMPLinearClause(
19115     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
19116     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
19117     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
19118   SmallVector<Expr *, 8> Vars;
19119   SmallVector<Expr *, 8> Privates;
19120   SmallVector<Expr *, 8> Inits;
19121   SmallVector<Decl *, 4> ExprCaptures;
19122   SmallVector<Expr *, 4> ExprPostUpdates;
19123   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
19124     LinKind = OMPC_LINEAR_val;
19125   for (Expr *RefExpr : VarList) {
19126     assert(RefExpr && "NULL expr in OpenMP linear clause.");
19127     SourceLocation ELoc;
19128     SourceRange ERange;
19129     Expr *SimpleRefExpr = RefExpr;
19130     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19131     if (Res.second) {
19132       // It will be analyzed later.
19133       Vars.push_back(RefExpr);
19134       Privates.push_back(nullptr);
19135       Inits.push_back(nullptr);
19136     }
19137     ValueDecl *D = Res.first;
19138     if (!D)
19139       continue;
19140 
19141     QualType Type = D->getType();
19142     auto *VD = dyn_cast<VarDecl>(D);
19143 
19144     // OpenMP [2.14.3.7, linear clause]
19145     //  A list-item cannot appear in more than one linear clause.
19146     //  A list-item that appears in a linear clause cannot appear in any
19147     //  other data-sharing attribute clause.
19148     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
19149     if (DVar.RefExpr) {
19150       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
19151                                           << getOpenMPClauseName(OMPC_linear);
19152       reportOriginalDsa(*this, DSAStack, D, DVar);
19153       continue;
19154     }
19155 
19156     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
19157       continue;
19158     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
19159 
19160     // Build private copy of original var.
19161     VarDecl *Private =
19162         buildVarDecl(*this, ELoc, Type, D->getName(),
19163                      D->hasAttrs() ? &D->getAttrs() : nullptr,
19164                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
19165     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
19166     // Build var to save initial value.
19167     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
19168     Expr *InitExpr;
19169     DeclRefExpr *Ref = nullptr;
19170     if (!VD && !CurContext->isDependentContext()) {
19171       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
19172       if (!isOpenMPCapturedDecl(D)) {
19173         ExprCaptures.push_back(Ref->getDecl());
19174         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
19175           ExprResult RefRes = DefaultLvalueConversion(Ref);
19176           if (!RefRes.isUsable())
19177             continue;
19178           ExprResult PostUpdateRes =
19179               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
19180                          SimpleRefExpr, RefRes.get());
19181           if (!PostUpdateRes.isUsable())
19182             continue;
19183           ExprPostUpdates.push_back(
19184               IgnoredValueConversions(PostUpdateRes.get()).get());
19185         }
19186       }
19187     }
19188     if (LinKind == OMPC_LINEAR_uval)
19189       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
19190     else
19191       InitExpr = VD ? SimpleRefExpr : Ref;
19192     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
19193                          /*DirectInit=*/false);
19194     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
19195 
19196     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
19197     Vars.push_back((VD || CurContext->isDependentContext())
19198                        ? RefExpr->IgnoreParens()
19199                        : Ref);
19200     Privates.push_back(PrivateRef);
19201     Inits.push_back(InitRef);
19202   }
19203 
19204   if (Vars.empty())
19205     return nullptr;
19206 
19207   Expr *StepExpr = Step;
19208   Expr *CalcStepExpr = nullptr;
19209   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
19210       !Step->isInstantiationDependent() &&
19211       !Step->containsUnexpandedParameterPack()) {
19212     SourceLocation StepLoc = Step->getBeginLoc();
19213     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
19214     if (Val.isInvalid())
19215       return nullptr;
19216     StepExpr = Val.get();
19217 
19218     // Build var to save the step value.
19219     VarDecl *SaveVar =
19220         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
19221     ExprResult SaveRef =
19222         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
19223     ExprResult CalcStep =
19224         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
19225     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
19226 
19227     // Warn about zero linear step (it would be probably better specified as
19228     // making corresponding variables 'const').
19229     if (Optional<llvm::APSInt> Result =
19230             StepExpr->getIntegerConstantExpr(Context)) {
19231       if (!Result->isNegative() && !Result->isStrictlyPositive())
19232         Diag(StepLoc, diag::warn_omp_linear_step_zero)
19233             << Vars[0] << (Vars.size() > 1);
19234     } else if (CalcStep.isUsable()) {
19235       // Calculate the step beforehand instead of doing this on each iteration.
19236       // (This is not used if the number of iterations may be kfold-ed).
19237       CalcStepExpr = CalcStep.get();
19238     }
19239   }
19240 
19241   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
19242                                  ColonLoc, EndLoc, Vars, Privates, Inits,
19243                                  StepExpr, CalcStepExpr,
19244                                  buildPreInits(Context, ExprCaptures),
19245                                  buildPostUpdate(*this, ExprPostUpdates));
19246 }
19247 
19248 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
19249                                      Expr *NumIterations, Sema &SemaRef,
19250                                      Scope *S, DSAStackTy *Stack) {
19251   // Walk the vars and build update/final expressions for the CodeGen.
19252   SmallVector<Expr *, 8> Updates;
19253   SmallVector<Expr *, 8> Finals;
19254   SmallVector<Expr *, 8> UsedExprs;
19255   Expr *Step = Clause.getStep();
19256   Expr *CalcStep = Clause.getCalcStep();
19257   // OpenMP [2.14.3.7, linear clause]
19258   // If linear-step is not specified it is assumed to be 1.
19259   if (!Step)
19260     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
19261   else if (CalcStep)
19262     Step = cast<BinaryOperator>(CalcStep)->getLHS();
19263   bool HasErrors = false;
19264   auto CurInit = Clause.inits().begin();
19265   auto CurPrivate = Clause.privates().begin();
19266   OpenMPLinearClauseKind LinKind = Clause.getModifier();
19267   for (Expr *RefExpr : Clause.varlists()) {
19268     SourceLocation ELoc;
19269     SourceRange ERange;
19270     Expr *SimpleRefExpr = RefExpr;
19271     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
19272     ValueDecl *D = Res.first;
19273     if (Res.second || !D) {
19274       Updates.push_back(nullptr);
19275       Finals.push_back(nullptr);
19276       HasErrors = true;
19277       continue;
19278     }
19279     auto &&Info = Stack->isLoopControlVariable(D);
19280     // OpenMP [2.15.11, distribute simd Construct]
19281     // A list item may not appear in a linear clause, unless it is the loop
19282     // iteration variable.
19283     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
19284         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
19285       SemaRef.Diag(ELoc,
19286                    diag::err_omp_linear_distribute_var_non_loop_iteration);
19287       Updates.push_back(nullptr);
19288       Finals.push_back(nullptr);
19289       HasErrors = true;
19290       continue;
19291     }
19292     Expr *InitExpr = *CurInit;
19293 
19294     // Build privatized reference to the current linear var.
19295     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
19296     Expr *CapturedRef;
19297     if (LinKind == OMPC_LINEAR_uval)
19298       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
19299     else
19300       CapturedRef =
19301           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
19302                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
19303                            /*RefersToCapture=*/true);
19304 
19305     // Build update: Var = InitExpr + IV * Step
19306     ExprResult Update;
19307     if (!Info.first)
19308       Update = buildCounterUpdate(
19309           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
19310           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
19311     else
19312       Update = *CurPrivate;
19313     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
19314                                          /*DiscardedValue*/ false);
19315 
19316     // Build final: Var = PrivCopy;
19317     ExprResult Final;
19318     if (!Info.first)
19319       Final = SemaRef.BuildBinOp(
19320           S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
19321           SemaRef.DefaultLvalueConversion(*CurPrivate).get());
19322     else
19323       Final = *CurPrivate;
19324     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
19325                                         /*DiscardedValue*/ false);
19326 
19327     if (!Update.isUsable() || !Final.isUsable()) {
19328       Updates.push_back(nullptr);
19329       Finals.push_back(nullptr);
19330       UsedExprs.push_back(nullptr);
19331       HasErrors = true;
19332     } else {
19333       Updates.push_back(Update.get());
19334       Finals.push_back(Final.get());
19335       if (!Info.first)
19336         UsedExprs.push_back(SimpleRefExpr);
19337     }
19338     ++CurInit;
19339     ++CurPrivate;
19340   }
19341   if (Expr *S = Clause.getStep())
19342     UsedExprs.push_back(S);
19343   // Fill the remaining part with the nullptr.
19344   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
19345   Clause.setUpdates(Updates);
19346   Clause.setFinals(Finals);
19347   Clause.setUsedExprs(UsedExprs);
19348   return HasErrors;
19349 }
19350 
19351 OMPClause *Sema::ActOnOpenMPAlignedClause(
19352     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
19353     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
19354   SmallVector<Expr *, 8> Vars;
19355   for (Expr *RefExpr : VarList) {
19356     assert(RefExpr && "NULL expr in OpenMP linear clause.");
19357     SourceLocation ELoc;
19358     SourceRange ERange;
19359     Expr *SimpleRefExpr = RefExpr;
19360     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19361     if (Res.second) {
19362       // It will be analyzed later.
19363       Vars.push_back(RefExpr);
19364     }
19365     ValueDecl *D = Res.first;
19366     if (!D)
19367       continue;
19368 
19369     QualType QType = D->getType();
19370     auto *VD = dyn_cast<VarDecl>(D);
19371 
19372     // OpenMP  [2.8.1, simd construct, Restrictions]
19373     // The type of list items appearing in the aligned clause must be
19374     // array, pointer, reference to array, or reference to pointer.
19375     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
19376     const Type *Ty = QType.getTypePtrOrNull();
19377     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
19378       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
19379           << QType << getLangOpts().CPlusPlus << ERange;
19380       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
19381                                VarDecl::DeclarationOnly;
19382       Diag(D->getLocation(),
19383            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
19384           << D;
19385       continue;
19386     }
19387 
19388     // OpenMP  [2.8.1, simd construct, Restrictions]
19389     // A list-item cannot appear in more than one aligned clause.
19390     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
19391       Diag(ELoc, diag::err_omp_used_in_clause_twice)
19392           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
19393       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
19394           << getOpenMPClauseName(OMPC_aligned);
19395       continue;
19396     }
19397 
19398     DeclRefExpr *Ref = nullptr;
19399     if (!VD && isOpenMPCapturedDecl(D))
19400       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
19401     Vars.push_back(DefaultFunctionArrayConversion(
19402                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
19403                        .get());
19404   }
19405 
19406   // OpenMP [2.8.1, simd construct, Description]
19407   // The parameter of the aligned clause, alignment, must be a constant
19408   // positive integer expression.
19409   // If no optional parameter is specified, implementation-defined default
19410   // alignments for SIMD instructions on the target platforms are assumed.
19411   if (Alignment != nullptr) {
19412     ExprResult AlignResult =
19413         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
19414     if (AlignResult.isInvalid())
19415       return nullptr;
19416     Alignment = AlignResult.get();
19417   }
19418   if (Vars.empty())
19419     return nullptr;
19420 
19421   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
19422                                   EndLoc, Vars, Alignment);
19423 }
19424 
19425 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
19426                                          SourceLocation StartLoc,
19427                                          SourceLocation LParenLoc,
19428                                          SourceLocation EndLoc) {
19429   SmallVector<Expr *, 8> Vars;
19430   SmallVector<Expr *, 8> SrcExprs;
19431   SmallVector<Expr *, 8> DstExprs;
19432   SmallVector<Expr *, 8> AssignmentOps;
19433   for (Expr *RefExpr : VarList) {
19434     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
19435     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
19436       // It will be analyzed later.
19437       Vars.push_back(RefExpr);
19438       SrcExprs.push_back(nullptr);
19439       DstExprs.push_back(nullptr);
19440       AssignmentOps.push_back(nullptr);
19441       continue;
19442     }
19443 
19444     SourceLocation ELoc = RefExpr->getExprLoc();
19445     // OpenMP [2.1, C/C++]
19446     //  A list item is a variable name.
19447     // OpenMP  [2.14.4.1, Restrictions, p.1]
19448     //  A list item that appears in a copyin clause must be threadprivate.
19449     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
19450     if (!DE || !isa<VarDecl>(DE->getDecl())) {
19451       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
19452           << 0 << RefExpr->getSourceRange();
19453       continue;
19454     }
19455 
19456     Decl *D = DE->getDecl();
19457     auto *VD = cast<VarDecl>(D);
19458 
19459     QualType Type = VD->getType();
19460     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
19461       // It will be analyzed later.
19462       Vars.push_back(DE);
19463       SrcExprs.push_back(nullptr);
19464       DstExprs.push_back(nullptr);
19465       AssignmentOps.push_back(nullptr);
19466       continue;
19467     }
19468 
19469     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
19470     //  A list item that appears in a copyin clause must be threadprivate.
19471     if (!DSAStack->isThreadPrivate(VD)) {
19472       Diag(ELoc, diag::err_omp_required_access)
19473           << getOpenMPClauseName(OMPC_copyin)
19474           << getOpenMPDirectiveName(OMPD_threadprivate);
19475       continue;
19476     }
19477 
19478     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
19479     //  A variable of class type (or array thereof) that appears in a
19480     //  copyin clause requires an accessible, unambiguous copy assignment
19481     //  operator for the class type.
19482     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
19483     VarDecl *SrcVD =
19484         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
19485                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
19486     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
19487         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
19488     VarDecl *DstVD =
19489         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
19490                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
19491     DeclRefExpr *PseudoDstExpr =
19492         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
19493     // For arrays generate assignment operation for single element and replace
19494     // it by the original array element in CodeGen.
19495     ExprResult AssignmentOp =
19496         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
19497                    PseudoSrcExpr);
19498     if (AssignmentOp.isInvalid())
19499       continue;
19500     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
19501                                        /*DiscardedValue*/ false);
19502     if (AssignmentOp.isInvalid())
19503       continue;
19504 
19505     DSAStack->addDSA(VD, DE, OMPC_copyin);
19506     Vars.push_back(DE);
19507     SrcExprs.push_back(PseudoSrcExpr);
19508     DstExprs.push_back(PseudoDstExpr);
19509     AssignmentOps.push_back(AssignmentOp.get());
19510   }
19511 
19512   if (Vars.empty())
19513     return nullptr;
19514 
19515   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
19516                                  SrcExprs, DstExprs, AssignmentOps);
19517 }
19518 
19519 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
19520                                               SourceLocation StartLoc,
19521                                               SourceLocation LParenLoc,
19522                                               SourceLocation EndLoc) {
19523   SmallVector<Expr *, 8> Vars;
19524   SmallVector<Expr *, 8> SrcExprs;
19525   SmallVector<Expr *, 8> DstExprs;
19526   SmallVector<Expr *, 8> AssignmentOps;
19527   for (Expr *RefExpr : VarList) {
19528     assert(RefExpr && "NULL expr in OpenMP linear clause.");
19529     SourceLocation ELoc;
19530     SourceRange ERange;
19531     Expr *SimpleRefExpr = RefExpr;
19532     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19533     if (Res.second) {
19534       // It will be analyzed later.
19535       Vars.push_back(RefExpr);
19536       SrcExprs.push_back(nullptr);
19537       DstExprs.push_back(nullptr);
19538       AssignmentOps.push_back(nullptr);
19539     }
19540     ValueDecl *D = Res.first;
19541     if (!D)
19542       continue;
19543 
19544     QualType Type = D->getType();
19545     auto *VD = dyn_cast<VarDecl>(D);
19546 
19547     // OpenMP [2.14.4.2, Restrictions, p.2]
19548     //  A list item that appears in a copyprivate clause may not appear in a
19549     //  private or firstprivate clause on the single construct.
19550     if (!VD || !DSAStack->isThreadPrivate(VD)) {
19551       DSAStackTy::DSAVarData DVar =
19552           DSAStack->getTopDSA(D, /*FromParent=*/false);
19553       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
19554           DVar.RefExpr) {
19555         Diag(ELoc, diag::err_omp_wrong_dsa)
19556             << getOpenMPClauseName(DVar.CKind)
19557             << getOpenMPClauseName(OMPC_copyprivate);
19558         reportOriginalDsa(*this, DSAStack, D, DVar);
19559         continue;
19560       }
19561 
19562       // OpenMP [2.11.4.2, Restrictions, p.1]
19563       //  All list items that appear in a copyprivate clause must be either
19564       //  threadprivate or private in the enclosing context.
19565       if (DVar.CKind == OMPC_unknown) {
19566         DVar = DSAStack->getImplicitDSA(D, false);
19567         if (DVar.CKind == OMPC_shared) {
19568           Diag(ELoc, diag::err_omp_required_access)
19569               << getOpenMPClauseName(OMPC_copyprivate)
19570               << "threadprivate or private in the enclosing context";
19571           reportOriginalDsa(*this, DSAStack, D, DVar);
19572           continue;
19573         }
19574       }
19575     }
19576 
19577     // Variably modified types are not supported.
19578     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
19579       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
19580           << getOpenMPClauseName(OMPC_copyprivate) << Type
19581           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
19582       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
19583                                VarDecl::DeclarationOnly;
19584       Diag(D->getLocation(),
19585            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
19586           << D;
19587       continue;
19588     }
19589 
19590     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
19591     //  A variable of class type (or array thereof) that appears in a
19592     //  copyin clause requires an accessible, unambiguous copy assignment
19593     //  operator for the class type.
19594     Type = Context.getBaseElementType(Type.getNonReferenceType())
19595                .getUnqualifiedType();
19596     VarDecl *SrcVD =
19597         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
19598                      D->hasAttrs() ? &D->getAttrs() : nullptr);
19599     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
19600     VarDecl *DstVD =
19601         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
19602                      D->hasAttrs() ? &D->getAttrs() : nullptr);
19603     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
19604     ExprResult AssignmentOp = BuildBinOp(
19605         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
19606     if (AssignmentOp.isInvalid())
19607       continue;
19608     AssignmentOp =
19609         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
19610     if (AssignmentOp.isInvalid())
19611       continue;
19612 
19613     // No need to mark vars as copyprivate, they are already threadprivate or
19614     // implicitly private.
19615     assert(VD || isOpenMPCapturedDecl(D));
19616     Vars.push_back(
19617         VD ? RefExpr->IgnoreParens()
19618            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
19619     SrcExprs.push_back(PseudoSrcExpr);
19620     DstExprs.push_back(PseudoDstExpr);
19621     AssignmentOps.push_back(AssignmentOp.get());
19622   }
19623 
19624   if (Vars.empty())
19625     return nullptr;
19626 
19627   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19628                                       Vars, SrcExprs, DstExprs, AssignmentOps);
19629 }
19630 
19631 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
19632                                         SourceLocation StartLoc,
19633                                         SourceLocation LParenLoc,
19634                                         SourceLocation EndLoc) {
19635   if (VarList.empty())
19636     return nullptr;
19637 
19638   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
19639 }
19640 
19641 /// Tries to find omp_depend_t. type.
19642 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
19643                            bool Diagnose = true) {
19644   QualType OMPDependT = Stack->getOMPDependT();
19645   if (!OMPDependT.isNull())
19646     return true;
19647   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
19648   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
19649   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19650     if (Diagnose)
19651       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
19652     return false;
19653   }
19654   Stack->setOMPDependT(PT.get());
19655   return true;
19656 }
19657 
19658 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
19659                                          SourceLocation LParenLoc,
19660                                          SourceLocation EndLoc) {
19661   if (!Depobj)
19662     return nullptr;
19663 
19664   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
19665 
19666   // OpenMP 5.0, 2.17.10.1 depobj Construct
19667   // depobj is an lvalue expression of type omp_depend_t.
19668   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
19669       !Depobj->isInstantiationDependent() &&
19670       !Depobj->containsUnexpandedParameterPack() &&
19671       (OMPDependTFound &&
19672        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
19673                                    /*CompareUnqualified=*/true))) {
19674     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
19675         << 0 << Depobj->getType() << Depobj->getSourceRange();
19676   }
19677 
19678   if (!Depobj->isLValue()) {
19679     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
19680         << 1 << Depobj->getSourceRange();
19681   }
19682 
19683   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
19684 }
19685 
19686 OMPClause *
19687 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
19688                               SourceLocation DepLoc, SourceLocation ColonLoc,
19689                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
19690                               SourceLocation LParenLoc, SourceLocation EndLoc) {
19691   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
19692       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
19693     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
19694         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
19695     return nullptr;
19696   }
19697   if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
19698       DepKind == OMPC_DEPEND_mutexinoutset) {
19699     Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
19700     return nullptr;
19701   }
19702   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
19703        DSAStack->getCurrentDirective() == OMPD_depobj) &&
19704       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
19705        DepKind == OMPC_DEPEND_sink ||
19706        ((LangOpts.OpenMP < 50 ||
19707          DSAStack->getCurrentDirective() == OMPD_depobj) &&
19708         DepKind == OMPC_DEPEND_depobj))) {
19709     SmallVector<unsigned, 3> Except;
19710     Except.push_back(OMPC_DEPEND_source);
19711     Except.push_back(OMPC_DEPEND_sink);
19712     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
19713       Except.push_back(OMPC_DEPEND_depobj);
19714     if (LangOpts.OpenMP < 51)
19715       Except.push_back(OMPC_DEPEND_inoutset);
19716     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
19717                                ? "depend modifier(iterator) or "
19718                                : "";
19719     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
19720         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
19721                                               /*Last=*/OMPC_DEPEND_unknown,
19722                                               Except)
19723         << getOpenMPClauseName(OMPC_depend);
19724     return nullptr;
19725   }
19726   if (DepModifier &&
19727       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
19728     Diag(DepModifier->getExprLoc(),
19729          diag::err_omp_depend_sink_source_with_modifier);
19730     return nullptr;
19731   }
19732   if (DepModifier &&
19733       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
19734     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
19735 
19736   SmallVector<Expr *, 8> Vars;
19737   DSAStackTy::OperatorOffsetTy OpsOffs;
19738   llvm::APSInt DepCounter(/*BitWidth=*/32);
19739   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
19740   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
19741     if (const Expr *OrderedCountExpr =
19742             DSAStack->getParentOrderedRegionParam().first) {
19743       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
19744       TotalDepCount.setIsUnsigned(/*Val=*/true);
19745     }
19746   }
19747   for (Expr *RefExpr : VarList) {
19748     assert(RefExpr && "NULL expr in OpenMP shared clause.");
19749     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
19750       // It will be analyzed later.
19751       Vars.push_back(RefExpr);
19752       continue;
19753     }
19754 
19755     SourceLocation ELoc = RefExpr->getExprLoc();
19756     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
19757     if (DepKind == OMPC_DEPEND_sink) {
19758       if (DSAStack->getParentOrderedRegionParam().first &&
19759           DepCounter >= TotalDepCount) {
19760         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
19761         continue;
19762       }
19763       ++DepCounter;
19764       // OpenMP  [2.13.9, Summary]
19765       // depend(dependence-type : vec), where dependence-type is:
19766       // 'sink' and where vec is the iteration vector, which has the form:
19767       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
19768       // where n is the value specified by the ordered clause in the loop
19769       // directive, xi denotes the loop iteration variable of the i-th nested
19770       // loop associated with the loop directive, and di is a constant
19771       // non-negative integer.
19772       if (CurContext->isDependentContext()) {
19773         // It will be analyzed later.
19774         Vars.push_back(RefExpr);
19775         continue;
19776       }
19777       SimpleExpr = SimpleExpr->IgnoreImplicit();
19778       OverloadedOperatorKind OOK = OO_None;
19779       SourceLocation OOLoc;
19780       Expr *LHS = SimpleExpr;
19781       Expr *RHS = nullptr;
19782       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
19783         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
19784         OOLoc = BO->getOperatorLoc();
19785         LHS = BO->getLHS()->IgnoreParenImpCasts();
19786         RHS = BO->getRHS()->IgnoreParenImpCasts();
19787       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
19788         OOK = OCE->getOperator();
19789         OOLoc = OCE->getOperatorLoc();
19790         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
19791         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
19792       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
19793         OOK = MCE->getMethodDecl()
19794                   ->getNameInfo()
19795                   .getName()
19796                   .getCXXOverloadedOperator();
19797         OOLoc = MCE->getCallee()->getExprLoc();
19798         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
19799         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
19800       }
19801       SourceLocation ELoc;
19802       SourceRange ERange;
19803       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
19804       if (Res.second) {
19805         // It will be analyzed later.
19806         Vars.push_back(RefExpr);
19807       }
19808       ValueDecl *D = Res.first;
19809       if (!D)
19810         continue;
19811 
19812       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
19813         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
19814         continue;
19815       }
19816       if (RHS) {
19817         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
19818             RHS, OMPC_depend, /*StrictlyPositive=*/false);
19819         if (RHSRes.isInvalid())
19820           continue;
19821       }
19822       if (!CurContext->isDependentContext() &&
19823           DSAStack->getParentOrderedRegionParam().first &&
19824           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
19825         const ValueDecl *VD =
19826             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
19827         if (VD)
19828           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
19829               << 1 << VD;
19830         else
19831           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
19832         continue;
19833       }
19834       OpsOffs.emplace_back(RHS, OOK);
19835     } else {
19836       bool OMPDependTFound = LangOpts.OpenMP >= 50;
19837       if (OMPDependTFound)
19838         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
19839                                          DepKind == OMPC_DEPEND_depobj);
19840       if (DepKind == OMPC_DEPEND_depobj) {
19841         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
19842         // List items used in depend clauses with the depobj dependence type
19843         // must be expressions of the omp_depend_t type.
19844         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
19845             !RefExpr->isInstantiationDependent() &&
19846             !RefExpr->containsUnexpandedParameterPack() &&
19847             (OMPDependTFound &&
19848              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
19849                                              RefExpr->getType()))) {
19850           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
19851               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
19852           continue;
19853         }
19854         if (!RefExpr->isLValue()) {
19855           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
19856               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
19857           continue;
19858         }
19859       } else {
19860         // OpenMP 5.0 [2.17.11, Restrictions]
19861         // List items used in depend clauses cannot be zero-length array
19862         // sections.
19863         QualType ExprTy = RefExpr->getType().getNonReferenceType();
19864         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
19865         if (OASE) {
19866           QualType BaseType =
19867               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19868           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19869             ExprTy = ATy->getElementType();
19870           else
19871             ExprTy = BaseType->getPointeeType();
19872           ExprTy = ExprTy.getNonReferenceType();
19873           const Expr *Length = OASE->getLength();
19874           Expr::EvalResult Result;
19875           if (Length && !Length->isValueDependent() &&
19876               Length->EvaluateAsInt(Result, Context) &&
19877               Result.Val.getInt().isZero()) {
19878             Diag(ELoc,
19879                  diag::err_omp_depend_zero_length_array_section_not_allowed)
19880                 << SimpleExpr->getSourceRange();
19881             continue;
19882           }
19883         }
19884 
19885         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
19886         // List items used in depend clauses with the in, out, inout,
19887         // inoutset, or mutexinoutset dependence types cannot be
19888         // expressions of the omp_depend_t type.
19889         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
19890             !RefExpr->isInstantiationDependent() &&
19891             !RefExpr->containsUnexpandedParameterPack() &&
19892             (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
19893              (OMPDependTFound &&
19894               DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
19895           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19896               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19897               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19898           continue;
19899         }
19900 
19901         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
19902         if (ASE && !ASE->getBase()->isTypeDependent() &&
19903             !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
19904             !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
19905           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19906               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19907               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19908           continue;
19909         }
19910 
19911         ExprResult Res;
19912         {
19913           Sema::TentativeAnalysisScope Trap(*this);
19914           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
19915                                      RefExpr->IgnoreParenImpCasts());
19916         }
19917         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
19918             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
19919           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19920               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19921               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19922           continue;
19923         }
19924       }
19925     }
19926     Vars.push_back(RefExpr->IgnoreParenImpCasts());
19927   }
19928 
19929   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
19930       TotalDepCount > VarList.size() &&
19931       DSAStack->getParentOrderedRegionParam().first &&
19932       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
19933     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
19934         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
19935   }
19936   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
19937       Vars.empty())
19938     return nullptr;
19939 
19940   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19941                                     DepModifier, DepKind, DepLoc, ColonLoc,
19942                                     Vars, TotalDepCount.getZExtValue());
19943   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
19944       DSAStack->isParentOrderedRegion())
19945     DSAStack->addDoacrossDependClause(C, OpsOffs);
19946   return C;
19947 }
19948 
19949 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
19950                                          Expr *Device, SourceLocation StartLoc,
19951                                          SourceLocation LParenLoc,
19952                                          SourceLocation ModifierLoc,
19953                                          SourceLocation EndLoc) {
19954   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
19955          "Unexpected device modifier in OpenMP < 50.");
19956 
19957   bool ErrorFound = false;
19958   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
19959     std::string Values =
19960         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
19961     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
19962         << Values << getOpenMPClauseName(OMPC_device);
19963     ErrorFound = true;
19964   }
19965 
19966   Expr *ValExpr = Device;
19967   Stmt *HelperValStmt = nullptr;
19968 
19969   // OpenMP [2.9.1, Restrictions]
19970   // The device expression must evaluate to a non-negative integer value.
19971   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
19972                                           /*StrictlyPositive=*/false) ||
19973                ErrorFound;
19974   if (ErrorFound)
19975     return nullptr;
19976 
19977   // OpenMP 5.0 [2.12.5, Restrictions]
19978   // In case of ancestor device-modifier, a requires directive with
19979   // the reverse_offload clause must be specified.
19980   if (Modifier == OMPC_DEVICE_ancestor) {
19981     if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) {
19982       targetDiag(
19983           StartLoc,
19984           diag::err_omp_device_ancestor_without_requires_reverse_offload);
19985       ErrorFound = true;
19986     }
19987   }
19988 
19989   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19990   OpenMPDirectiveKind CaptureRegion =
19991       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
19992   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19993     ValExpr = MakeFullExpr(ValExpr).get();
19994     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19995     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19996     HelperValStmt = buildPreInits(Context, Captures);
19997   }
19998 
19999   return new (Context)
20000       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
20001                       LParenLoc, ModifierLoc, EndLoc);
20002 }
20003 
20004 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
20005                               DSAStackTy *Stack, QualType QTy,
20006                               bool FullCheck = true) {
20007   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
20008     return false;
20009   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
20010       !QTy.isTriviallyCopyableType(SemaRef.Context))
20011     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
20012   return true;
20013 }
20014 
20015 /// Return true if it can be proven that the provided array expression
20016 /// (array section or array subscript) does NOT specify the whole size of the
20017 /// array whose base type is \a BaseQTy.
20018 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
20019                                                         const Expr *E,
20020                                                         QualType BaseQTy) {
20021   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
20022 
20023   // If this is an array subscript, it refers to the whole size if the size of
20024   // the dimension is constant and equals 1. Also, an array section assumes the
20025   // format of an array subscript if no colon is used.
20026   if (isa<ArraySubscriptExpr>(E) ||
20027       (OASE && OASE->getColonLocFirst().isInvalid())) {
20028     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
20029       return ATy->getSize().getSExtValue() != 1;
20030     // Size can't be evaluated statically.
20031     return false;
20032   }
20033 
20034   assert(OASE && "Expecting array section if not an array subscript.");
20035   const Expr *LowerBound = OASE->getLowerBound();
20036   const Expr *Length = OASE->getLength();
20037 
20038   // If there is a lower bound that does not evaluates to zero, we are not
20039   // covering the whole dimension.
20040   if (LowerBound) {
20041     Expr::EvalResult Result;
20042     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
20043       return false; // Can't get the integer value as a constant.
20044 
20045     llvm::APSInt ConstLowerBound = Result.Val.getInt();
20046     if (ConstLowerBound.getSExtValue())
20047       return true;
20048   }
20049 
20050   // If we don't have a length we covering the whole dimension.
20051   if (!Length)
20052     return false;
20053 
20054   // If the base is a pointer, we don't have a way to get the size of the
20055   // pointee.
20056   if (BaseQTy->isPointerType())
20057     return false;
20058 
20059   // We can only check if the length is the same as the size of the dimension
20060   // if we have a constant array.
20061   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
20062   if (!CATy)
20063     return false;
20064 
20065   Expr::EvalResult Result;
20066   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
20067     return false; // Can't get the integer value as a constant.
20068 
20069   llvm::APSInt ConstLength = Result.Val.getInt();
20070   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
20071 }
20072 
20073 // Return true if it can be proven that the provided array expression (array
20074 // section or array subscript) does NOT specify a single element of the array
20075 // whose base type is \a BaseQTy.
20076 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
20077                                                         const Expr *E,
20078                                                         QualType BaseQTy) {
20079   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
20080 
20081   // An array subscript always refer to a single element. Also, an array section
20082   // assumes the format of an array subscript if no colon is used.
20083   if (isa<ArraySubscriptExpr>(E) ||
20084       (OASE && OASE->getColonLocFirst().isInvalid()))
20085     return false;
20086 
20087   assert(OASE && "Expecting array section if not an array subscript.");
20088   const Expr *Length = OASE->getLength();
20089 
20090   // If we don't have a length we have to check if the array has unitary size
20091   // for this dimension. Also, we should always expect a length if the base type
20092   // is pointer.
20093   if (!Length) {
20094     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
20095       return ATy->getSize().getSExtValue() != 1;
20096     // We cannot assume anything.
20097     return false;
20098   }
20099 
20100   // Check if the length evaluates to 1.
20101   Expr::EvalResult Result;
20102   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
20103     return false; // Can't get the integer value as a constant.
20104 
20105   llvm::APSInt ConstLength = Result.Val.getInt();
20106   return ConstLength.getSExtValue() != 1;
20107 }
20108 
20109 // The base of elements of list in a map clause have to be either:
20110 //  - a reference to variable or field.
20111 //  - a member expression.
20112 //  - an array expression.
20113 //
20114 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
20115 // reference to 'r'.
20116 //
20117 // If we have:
20118 //
20119 // struct SS {
20120 //   Bla S;
20121 //   foo() {
20122 //     #pragma omp target map (S.Arr[:12]);
20123 //   }
20124 // }
20125 //
20126 // We want to retrieve the member expression 'this->S';
20127 
20128 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
20129 //  If a list item is an array section, it must specify contiguous storage.
20130 //
20131 // For this restriction it is sufficient that we make sure only references
20132 // to variables or fields and array expressions, and that no array sections
20133 // exist except in the rightmost expression (unless they cover the whole
20134 // dimension of the array). E.g. these would be invalid:
20135 //
20136 //   r.ArrS[3:5].Arr[6:7]
20137 //
20138 //   r.ArrS[3:5].x
20139 //
20140 // but these would be valid:
20141 //   r.ArrS[3].Arr[6:7]
20142 //
20143 //   r.ArrS[3].x
20144 namespace {
20145 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
20146   Sema &SemaRef;
20147   OpenMPClauseKind CKind = OMPC_unknown;
20148   OpenMPDirectiveKind DKind = OMPD_unknown;
20149   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
20150   bool IsNonContiguous = false;
20151   bool NoDiagnose = false;
20152   const Expr *RelevantExpr = nullptr;
20153   bool AllowUnitySizeArraySection = true;
20154   bool AllowWholeSizeArraySection = true;
20155   bool AllowAnotherPtr = true;
20156   SourceLocation ELoc;
20157   SourceRange ERange;
20158 
20159   void emitErrorMsg() {
20160     // If nothing else worked, this is not a valid map clause expression.
20161     if (SemaRef.getLangOpts().OpenMP < 50) {
20162       SemaRef.Diag(ELoc,
20163                    diag::err_omp_expected_named_var_member_or_array_expression)
20164           << ERange;
20165     } else {
20166       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
20167           << getOpenMPClauseName(CKind) << ERange;
20168     }
20169   }
20170 
20171 public:
20172   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
20173     if (!isa<VarDecl>(DRE->getDecl())) {
20174       emitErrorMsg();
20175       return false;
20176     }
20177     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20178     RelevantExpr = DRE;
20179     // Record the component.
20180     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
20181     return true;
20182   }
20183 
20184   bool VisitMemberExpr(MemberExpr *ME) {
20185     Expr *E = ME;
20186     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
20187 
20188     if (isa<CXXThisExpr>(BaseE)) {
20189       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20190       // We found a base expression: this->Val.
20191       RelevantExpr = ME;
20192     } else {
20193       E = BaseE;
20194     }
20195 
20196     if (!isa<FieldDecl>(ME->getMemberDecl())) {
20197       if (!NoDiagnose) {
20198         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
20199             << ME->getSourceRange();
20200         return false;
20201       }
20202       if (RelevantExpr)
20203         return false;
20204       return Visit(E);
20205     }
20206 
20207     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
20208 
20209     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
20210     //  A bit-field cannot appear in a map clause.
20211     //
20212     if (FD->isBitField()) {
20213       if (!NoDiagnose) {
20214         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
20215             << ME->getSourceRange() << getOpenMPClauseName(CKind);
20216         return false;
20217       }
20218       if (RelevantExpr)
20219         return false;
20220       return Visit(E);
20221     }
20222 
20223     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20224     //  If the type of a list item is a reference to a type T then the type
20225     //  will be considered to be T for all purposes of this clause.
20226     QualType CurType = BaseE->getType().getNonReferenceType();
20227 
20228     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
20229     //  A list item cannot be a variable that is a member of a structure with
20230     //  a union type.
20231     //
20232     if (CurType->isUnionType()) {
20233       if (!NoDiagnose) {
20234         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
20235             << ME->getSourceRange();
20236         return false;
20237       }
20238       return RelevantExpr || Visit(E);
20239     }
20240 
20241     // If we got a member expression, we should not expect any array section
20242     // before that:
20243     //
20244     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
20245     //  If a list item is an element of a structure, only the rightmost symbol
20246     //  of the variable reference can be an array section.
20247     //
20248     AllowUnitySizeArraySection = false;
20249     AllowWholeSizeArraySection = false;
20250 
20251     // Record the component.
20252     Components.emplace_back(ME, FD, IsNonContiguous);
20253     return RelevantExpr || Visit(E);
20254   }
20255 
20256   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
20257     Expr *E = AE->getBase()->IgnoreParenImpCasts();
20258 
20259     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
20260       if (!NoDiagnose) {
20261         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
20262             << 0 << AE->getSourceRange();
20263         return false;
20264       }
20265       return RelevantExpr || Visit(E);
20266     }
20267 
20268     // If we got an array subscript that express the whole dimension we
20269     // can have any array expressions before. If it only expressing part of
20270     // the dimension, we can only have unitary-size array expressions.
20271     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
20272       AllowWholeSizeArraySection = false;
20273 
20274     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
20275       Expr::EvalResult Result;
20276       if (!AE->getIdx()->isValueDependent() &&
20277           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
20278           !Result.Val.getInt().isZero()) {
20279         SemaRef.Diag(AE->getIdx()->getExprLoc(),
20280                      diag::err_omp_invalid_map_this_expr);
20281         SemaRef.Diag(AE->getIdx()->getExprLoc(),
20282                      diag::note_omp_invalid_subscript_on_this_ptr_map);
20283       }
20284       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20285       RelevantExpr = TE;
20286     }
20287 
20288     // Record the component - we don't have any declaration associated.
20289     Components.emplace_back(AE, nullptr, IsNonContiguous);
20290 
20291     return RelevantExpr || Visit(E);
20292   }
20293 
20294   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
20295     // After OMP 5.0  Array section in reduction clause will be implicitly
20296     // mapped
20297     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
20298            "Array sections cannot be implicitly mapped.");
20299     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
20300     QualType CurType =
20301         OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
20302 
20303     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20304     //  If the type of a list item is a reference to a type T then the type
20305     //  will be considered to be T for all purposes of this clause.
20306     if (CurType->isReferenceType())
20307       CurType = CurType->getPointeeType();
20308 
20309     bool IsPointer = CurType->isAnyPointerType();
20310 
20311     if (!IsPointer && !CurType->isArrayType()) {
20312       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
20313           << 0 << OASE->getSourceRange();
20314       return false;
20315     }
20316 
20317     bool NotWhole =
20318         checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
20319     bool NotUnity =
20320         checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
20321 
20322     if (AllowWholeSizeArraySection) {
20323       // Any array section is currently allowed. Allowing a whole size array
20324       // section implies allowing a unity array section as well.
20325       //
20326       // If this array section refers to the whole dimension we can still
20327       // accept other array sections before this one, except if the base is a
20328       // pointer. Otherwise, only unitary sections are accepted.
20329       if (NotWhole || IsPointer)
20330         AllowWholeSizeArraySection = false;
20331     } else if (DKind == OMPD_target_update &&
20332                SemaRef.getLangOpts().OpenMP >= 50) {
20333       if (IsPointer && !AllowAnotherPtr)
20334         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
20335             << /*array of unknown bound */ 1;
20336       else
20337         IsNonContiguous = true;
20338     } else if (AllowUnitySizeArraySection && NotUnity) {
20339       // A unity or whole array section is not allowed and that is not
20340       // compatible with the properties of the current array section.
20341       if (NoDiagnose)
20342         return false;
20343       SemaRef.Diag(ELoc,
20344                    diag::err_array_section_does_not_specify_contiguous_storage)
20345           << OASE->getSourceRange();
20346       return false;
20347     }
20348 
20349     if (IsPointer)
20350       AllowAnotherPtr = false;
20351 
20352     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
20353       Expr::EvalResult ResultR;
20354       Expr::EvalResult ResultL;
20355       if (!OASE->getLength()->isValueDependent() &&
20356           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
20357           !ResultR.Val.getInt().isOne()) {
20358         SemaRef.Diag(OASE->getLength()->getExprLoc(),
20359                      diag::err_omp_invalid_map_this_expr);
20360         SemaRef.Diag(OASE->getLength()->getExprLoc(),
20361                      diag::note_omp_invalid_length_on_this_ptr_mapping);
20362       }
20363       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
20364           OASE->getLowerBound()->EvaluateAsInt(ResultL,
20365                                                SemaRef.getASTContext()) &&
20366           !ResultL.Val.getInt().isZero()) {
20367         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
20368                      diag::err_omp_invalid_map_this_expr);
20369         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
20370                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
20371       }
20372       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20373       RelevantExpr = TE;
20374     }
20375 
20376     // Record the component - we don't have any declaration associated.
20377     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
20378     return RelevantExpr || Visit(E);
20379   }
20380   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
20381     Expr *Base = E->getBase();
20382 
20383     // Record the component - we don't have any declaration associated.
20384     Components.emplace_back(E, nullptr, IsNonContiguous);
20385 
20386     return Visit(Base->IgnoreParenImpCasts());
20387   }
20388 
20389   bool VisitUnaryOperator(UnaryOperator *UO) {
20390     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
20391         UO->getOpcode() != UO_Deref) {
20392       emitErrorMsg();
20393       return false;
20394     }
20395     if (!RelevantExpr) {
20396       // Record the component if haven't found base decl.
20397       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
20398     }
20399     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
20400   }
20401   bool VisitBinaryOperator(BinaryOperator *BO) {
20402     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
20403       emitErrorMsg();
20404       return false;
20405     }
20406 
20407     // Pointer arithmetic is the only thing we expect to happen here so after we
20408     // make sure the binary operator is a pointer type, the we only thing need
20409     // to to is to visit the subtree that has the same type as root (so that we
20410     // know the other subtree is just an offset)
20411     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
20412     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
20413     Components.emplace_back(BO, nullptr, false);
20414     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
20415             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
20416            "Either LHS or RHS have base decl inside");
20417     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
20418       return RelevantExpr || Visit(LE);
20419     return RelevantExpr || Visit(RE);
20420   }
20421   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
20422     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20423     RelevantExpr = CTE;
20424     Components.emplace_back(CTE, nullptr, IsNonContiguous);
20425     return true;
20426   }
20427   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
20428     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
20429     Components.emplace_back(COCE, nullptr, IsNonContiguous);
20430     return true;
20431   }
20432   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
20433     Expr *Source = E->getSourceExpr();
20434     if (!Source) {
20435       emitErrorMsg();
20436       return false;
20437     }
20438     return Visit(Source);
20439   }
20440   bool VisitStmt(Stmt *) {
20441     emitErrorMsg();
20442     return false;
20443   }
20444   const Expr *getFoundBase() const { return RelevantExpr; }
20445   explicit MapBaseChecker(
20446       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
20447       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
20448       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
20449       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
20450         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
20451 };
20452 } // namespace
20453 
20454 /// Return the expression of the base of the mappable expression or null if it
20455 /// cannot be determined and do all the necessary checks to see if the
20456 /// expression is valid as a standalone mappable expression. In the process,
20457 /// record all the components of the expression.
20458 static const Expr *checkMapClauseExpressionBase(
20459     Sema &SemaRef, Expr *E,
20460     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
20461     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
20462   SourceLocation ELoc = E->getExprLoc();
20463   SourceRange ERange = E->getSourceRange();
20464   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
20465                          ERange);
20466   if (Checker.Visit(E->IgnoreParens())) {
20467     // Check if the highest dimension array section has length specified
20468     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
20469         (CKind == OMPC_to || CKind == OMPC_from)) {
20470       auto CI = CurComponents.rbegin();
20471       auto CE = CurComponents.rend();
20472       for (; CI != CE; ++CI) {
20473         const auto *OASE =
20474             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
20475         if (!OASE)
20476           continue;
20477         if (OASE && OASE->getLength())
20478           break;
20479         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
20480             << ERange;
20481       }
20482     }
20483     return Checker.getFoundBase();
20484   }
20485   return nullptr;
20486 }
20487 
20488 // Return true if expression E associated with value VD has conflicts with other
20489 // map information.
20490 static bool checkMapConflicts(
20491     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
20492     bool CurrentRegionOnly,
20493     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
20494     OpenMPClauseKind CKind) {
20495   assert(VD && E);
20496   SourceLocation ELoc = E->getExprLoc();
20497   SourceRange ERange = E->getSourceRange();
20498 
20499   // In order to easily check the conflicts we need to match each component of
20500   // the expression under test with the components of the expressions that are
20501   // already in the stack.
20502 
20503   assert(!CurComponents.empty() && "Map clause expression with no components!");
20504   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
20505          "Map clause expression with unexpected base!");
20506 
20507   // Variables to help detecting enclosing problems in data environment nests.
20508   bool IsEnclosedByDataEnvironmentExpr = false;
20509   const Expr *EnclosingExpr = nullptr;
20510 
20511   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
20512       VD, CurrentRegionOnly,
20513       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
20514        ERange, CKind, &EnclosingExpr,
20515        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
20516                           StackComponents,
20517                       OpenMPClauseKind Kind) {
20518         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
20519           return false;
20520         assert(!StackComponents.empty() &&
20521                "Map clause expression with no components!");
20522         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
20523                "Map clause expression with unexpected base!");
20524         (void)VD;
20525 
20526         // The whole expression in the stack.
20527         const Expr *RE = StackComponents.front().getAssociatedExpression();
20528 
20529         // Expressions must start from the same base. Here we detect at which
20530         // point both expressions diverge from each other and see if we can
20531         // detect if the memory referred to both expressions is contiguous and
20532         // do not overlap.
20533         auto CI = CurComponents.rbegin();
20534         auto CE = CurComponents.rend();
20535         auto SI = StackComponents.rbegin();
20536         auto SE = StackComponents.rend();
20537         for (; CI != CE && SI != SE; ++CI, ++SI) {
20538 
20539           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
20540           //  At most one list item can be an array item derived from a given
20541           //  variable in map clauses of the same construct.
20542           if (CurrentRegionOnly &&
20543               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
20544                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
20545                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
20546               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
20547                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
20548                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
20549             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
20550                          diag::err_omp_multiple_array_items_in_map_clause)
20551                 << CI->getAssociatedExpression()->getSourceRange();
20552             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
20553                          diag::note_used_here)
20554                 << SI->getAssociatedExpression()->getSourceRange();
20555             return true;
20556           }
20557 
20558           // Do both expressions have the same kind?
20559           if (CI->getAssociatedExpression()->getStmtClass() !=
20560               SI->getAssociatedExpression()->getStmtClass())
20561             break;
20562 
20563           // Are we dealing with different variables/fields?
20564           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
20565             break;
20566         }
20567         // Check if the extra components of the expressions in the enclosing
20568         // data environment are redundant for the current base declaration.
20569         // If they are, the maps completely overlap, which is legal.
20570         for (; SI != SE; ++SI) {
20571           QualType Type;
20572           if (const auto *ASE =
20573                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
20574             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
20575           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
20576                          SI->getAssociatedExpression())) {
20577             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
20578             Type =
20579                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
20580           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
20581                          SI->getAssociatedExpression())) {
20582             Type = OASE->getBase()->getType()->getPointeeType();
20583           }
20584           if (Type.isNull() || Type->isAnyPointerType() ||
20585               checkArrayExpressionDoesNotReferToWholeSize(
20586                   SemaRef, SI->getAssociatedExpression(), Type))
20587             break;
20588         }
20589 
20590         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
20591         //  List items of map clauses in the same construct must not share
20592         //  original storage.
20593         //
20594         // If the expressions are exactly the same or one is a subset of the
20595         // other, it means they are sharing storage.
20596         if (CI == CE && SI == SE) {
20597           if (CurrentRegionOnly) {
20598             if (CKind == OMPC_map) {
20599               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
20600             } else {
20601               assert(CKind == OMPC_to || CKind == OMPC_from);
20602               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
20603                   << ERange;
20604             }
20605             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20606                 << RE->getSourceRange();
20607             return true;
20608           }
20609           // If we find the same expression in the enclosing data environment,
20610           // that is legal.
20611           IsEnclosedByDataEnvironmentExpr = true;
20612           return false;
20613         }
20614 
20615         QualType DerivedType =
20616             std::prev(CI)->getAssociatedDeclaration()->getType();
20617         SourceLocation DerivedLoc =
20618             std::prev(CI)->getAssociatedExpression()->getExprLoc();
20619 
20620         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20621         //  If the type of a list item is a reference to a type T then the type
20622         //  will be considered to be T for all purposes of this clause.
20623         DerivedType = DerivedType.getNonReferenceType();
20624 
20625         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
20626         //  A variable for which the type is pointer and an array section
20627         //  derived from that variable must not appear as list items of map
20628         //  clauses of the same construct.
20629         //
20630         // Also, cover one of the cases in:
20631         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
20632         //  If any part of the original storage of a list item has corresponding
20633         //  storage in the device data environment, all of the original storage
20634         //  must have corresponding storage in the device data environment.
20635         //
20636         if (DerivedType->isAnyPointerType()) {
20637           if (CI == CE || SI == SE) {
20638             SemaRef.Diag(
20639                 DerivedLoc,
20640                 diag::err_omp_pointer_mapped_along_with_derived_section)
20641                 << DerivedLoc;
20642             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20643                 << RE->getSourceRange();
20644             return true;
20645           }
20646           if (CI->getAssociatedExpression()->getStmtClass() !=
20647                   SI->getAssociatedExpression()->getStmtClass() ||
20648               CI->getAssociatedDeclaration()->getCanonicalDecl() ==
20649                   SI->getAssociatedDeclaration()->getCanonicalDecl()) {
20650             assert(CI != CE && SI != SE);
20651             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
20652                 << DerivedLoc;
20653             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20654                 << RE->getSourceRange();
20655             return true;
20656           }
20657         }
20658 
20659         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
20660         //  List items of map clauses in the same construct must not share
20661         //  original storage.
20662         //
20663         // An expression is a subset of the other.
20664         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
20665           if (CKind == OMPC_map) {
20666             if (CI != CE || SI != SE) {
20667               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
20668               // a pointer.
20669               auto Begin =
20670                   CI != CE ? CurComponents.begin() : StackComponents.begin();
20671               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
20672               auto It = Begin;
20673               while (It != End && !It->getAssociatedDeclaration())
20674                 std::advance(It, 1);
20675               assert(It != End &&
20676                      "Expected at least one component with the declaration.");
20677               if (It != Begin && It->getAssociatedDeclaration()
20678                                      ->getType()
20679                                      .getCanonicalType()
20680                                      ->isAnyPointerType()) {
20681                 IsEnclosedByDataEnvironmentExpr = false;
20682                 EnclosingExpr = nullptr;
20683                 return false;
20684               }
20685             }
20686             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
20687           } else {
20688             assert(CKind == OMPC_to || CKind == OMPC_from);
20689             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
20690                 << ERange;
20691           }
20692           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
20693               << RE->getSourceRange();
20694           return true;
20695         }
20696 
20697         // The current expression uses the same base as other expression in the
20698         // data environment but does not contain it completely.
20699         if (!CurrentRegionOnly && SI != SE)
20700           EnclosingExpr = RE;
20701 
20702         // The current expression is a subset of the expression in the data
20703         // environment.
20704         IsEnclosedByDataEnvironmentExpr |=
20705             (!CurrentRegionOnly && CI != CE && SI == SE);
20706 
20707         return false;
20708       });
20709 
20710   if (CurrentRegionOnly)
20711     return FoundError;
20712 
20713   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
20714   //  If any part of the original storage of a list item has corresponding
20715   //  storage in the device data environment, all of the original storage must
20716   //  have corresponding storage in the device data environment.
20717   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
20718   //  If a list item is an element of a structure, and a different element of
20719   //  the structure has a corresponding list item in the device data environment
20720   //  prior to a task encountering the construct associated with the map clause,
20721   //  then the list item must also have a corresponding list item in the device
20722   //  data environment prior to the task encountering the construct.
20723   //
20724   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
20725     SemaRef.Diag(ELoc,
20726                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
20727         << ERange;
20728     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
20729         << EnclosingExpr->getSourceRange();
20730     return true;
20731   }
20732 
20733   return FoundError;
20734 }
20735 
20736 // Look up the user-defined mapper given the mapper name and mapped type, and
20737 // build a reference to it.
20738 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
20739                                             CXXScopeSpec &MapperIdScopeSpec,
20740                                             const DeclarationNameInfo &MapperId,
20741                                             QualType Type,
20742                                             Expr *UnresolvedMapper) {
20743   if (MapperIdScopeSpec.isInvalid())
20744     return ExprError();
20745   // Get the actual type for the array type.
20746   if (Type->isArrayType()) {
20747     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
20748     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
20749   }
20750   // Find all user-defined mappers with the given MapperId.
20751   SmallVector<UnresolvedSet<8>, 4> Lookups;
20752   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
20753   Lookup.suppressDiagnostics();
20754   if (S) {
20755     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
20756       NamedDecl *D = Lookup.getRepresentativeDecl();
20757       while (S && !S->isDeclScope(D))
20758         S = S->getParent();
20759       if (S)
20760         S = S->getParent();
20761       Lookups.emplace_back();
20762       Lookups.back().append(Lookup.begin(), Lookup.end());
20763       Lookup.clear();
20764     }
20765   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
20766     // Extract the user-defined mappers with the given MapperId.
20767     Lookups.push_back(UnresolvedSet<8>());
20768     for (NamedDecl *D : ULE->decls()) {
20769       auto *DMD = cast<OMPDeclareMapperDecl>(D);
20770       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
20771       Lookups.back().addDecl(DMD);
20772     }
20773   }
20774   // Defer the lookup for dependent types. The results will be passed through
20775   // UnresolvedMapper on instantiation.
20776   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
20777       Type->isInstantiationDependentType() ||
20778       Type->containsUnexpandedParameterPack() ||
20779       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
20780         return !D->isInvalidDecl() &&
20781                (D->getType()->isDependentType() ||
20782                 D->getType()->isInstantiationDependentType() ||
20783                 D->getType()->containsUnexpandedParameterPack());
20784       })) {
20785     UnresolvedSet<8> URS;
20786     for (const UnresolvedSet<8> &Set : Lookups) {
20787       if (Set.empty())
20788         continue;
20789       URS.append(Set.begin(), Set.end());
20790     }
20791     return UnresolvedLookupExpr::Create(
20792         SemaRef.Context, /*NamingClass=*/nullptr,
20793         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
20794         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
20795   }
20796   SourceLocation Loc = MapperId.getLoc();
20797   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20798   //  The type must be of struct, union or class type in C and C++
20799   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
20800       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
20801     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
20802     return ExprError();
20803   }
20804   // Perform argument dependent lookup.
20805   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
20806     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
20807   // Return the first user-defined mapper with the desired type.
20808   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
20809           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
20810             if (!D->isInvalidDecl() &&
20811                 SemaRef.Context.hasSameType(D->getType(), Type))
20812               return D;
20813             return nullptr;
20814           }))
20815     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
20816   // Find the first user-defined mapper with a type derived from the desired
20817   // type.
20818   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
20819           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
20820             if (!D->isInvalidDecl() &&
20821                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
20822                 !Type.isMoreQualifiedThan(D->getType()))
20823               return D;
20824             return nullptr;
20825           })) {
20826     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
20827                        /*DetectVirtual=*/false);
20828     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
20829       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
20830               VD->getType().getUnqualifiedType()))) {
20831         if (SemaRef.CheckBaseClassAccess(
20832                 Loc, VD->getType(), Type, Paths.front(),
20833                 /*DiagID=*/0) != Sema::AR_inaccessible) {
20834           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
20835         }
20836       }
20837     }
20838   }
20839   // Report error if a mapper is specified, but cannot be found.
20840   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
20841     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
20842         << Type << MapperId.getName();
20843     return ExprError();
20844   }
20845   return ExprEmpty();
20846 }
20847 
20848 namespace {
20849 // Utility struct that gathers all the related lists associated with a mappable
20850 // expression.
20851 struct MappableVarListInfo {
20852   // The list of expressions.
20853   ArrayRef<Expr *> VarList;
20854   // The list of processed expressions.
20855   SmallVector<Expr *, 16> ProcessedVarList;
20856   // The mappble components for each expression.
20857   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
20858   // The base declaration of the variable.
20859   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
20860   // The reference to the user-defined mapper associated with every expression.
20861   SmallVector<Expr *, 16> UDMapperList;
20862 
20863   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
20864     // We have a list of components and base declarations for each entry in the
20865     // variable list.
20866     VarComponents.reserve(VarList.size());
20867     VarBaseDeclarations.reserve(VarList.size());
20868   }
20869 };
20870 } // namespace
20871 
20872 // Check the validity of the provided variable list for the provided clause kind
20873 // \a CKind. In the check process the valid expressions, mappable expression
20874 // components, variables, and user-defined mappers are extracted and used to
20875 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
20876 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
20877 // and \a MapperId are expected to be valid if the clause kind is 'map'.
20878 static void checkMappableExpressionList(
20879     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
20880     MappableVarListInfo &MVLI, SourceLocation StartLoc,
20881     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
20882     ArrayRef<Expr *> UnresolvedMappers,
20883     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
20884     ArrayRef<OpenMPMapModifierKind> Modifiers = None,
20885     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
20886   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
20887   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
20888          "Unexpected clause kind with mappable expressions!");
20889 
20890   // If the identifier of user-defined mapper is not specified, it is "default".
20891   // We do not change the actual name in this clause to distinguish whether a
20892   // mapper is specified explicitly, i.e., it is not explicitly specified when
20893   // MapperId.getName() is empty.
20894   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
20895     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
20896     MapperId.setName(DeclNames.getIdentifier(
20897         &SemaRef.getASTContext().Idents.get("default")));
20898     MapperId.setLoc(StartLoc);
20899   }
20900 
20901   // Iterators to find the current unresolved mapper expression.
20902   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
20903   bool UpdateUMIt = false;
20904   Expr *UnresolvedMapper = nullptr;
20905 
20906   bool HasHoldModifier =
20907       llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
20908 
20909   // Keep track of the mappable components and base declarations in this clause.
20910   // Each entry in the list is going to have a list of components associated. We
20911   // record each set of the components so that we can build the clause later on.
20912   // In the end we should have the same amount of declarations and component
20913   // lists.
20914 
20915   for (Expr *RE : MVLI.VarList) {
20916     assert(RE && "Null expr in omp to/from/map clause");
20917     SourceLocation ELoc = RE->getExprLoc();
20918 
20919     // Find the current unresolved mapper expression.
20920     if (UpdateUMIt && UMIt != UMEnd) {
20921       UMIt++;
20922       assert(
20923           UMIt != UMEnd &&
20924           "Expect the size of UnresolvedMappers to match with that of VarList");
20925     }
20926     UpdateUMIt = true;
20927     if (UMIt != UMEnd)
20928       UnresolvedMapper = *UMIt;
20929 
20930     const Expr *VE = RE->IgnoreParenLValueCasts();
20931 
20932     if (VE->isValueDependent() || VE->isTypeDependent() ||
20933         VE->isInstantiationDependent() ||
20934         VE->containsUnexpandedParameterPack()) {
20935       // Try to find the associated user-defined mapper.
20936       ExprResult ER = buildUserDefinedMapperRef(
20937           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20938           VE->getType().getCanonicalType(), UnresolvedMapper);
20939       if (ER.isInvalid())
20940         continue;
20941       MVLI.UDMapperList.push_back(ER.get());
20942       // We can only analyze this information once the missing information is
20943       // resolved.
20944       MVLI.ProcessedVarList.push_back(RE);
20945       continue;
20946     }
20947 
20948     Expr *SimpleExpr = RE->IgnoreParenCasts();
20949 
20950     if (!RE->isLValue()) {
20951       if (SemaRef.getLangOpts().OpenMP < 50) {
20952         SemaRef.Diag(
20953             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
20954             << RE->getSourceRange();
20955       } else {
20956         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
20957             << getOpenMPClauseName(CKind) << RE->getSourceRange();
20958       }
20959       continue;
20960     }
20961 
20962     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
20963     ValueDecl *CurDeclaration = nullptr;
20964 
20965     // Obtain the array or member expression bases if required. Also, fill the
20966     // components array with all the components identified in the process.
20967     const Expr *BE =
20968         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
20969                                      DSAS->getCurrentDirective(), NoDiagnose);
20970     if (!BE)
20971       continue;
20972 
20973     assert(!CurComponents.empty() &&
20974            "Invalid mappable expression information.");
20975 
20976     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
20977       // Add store "this" pointer to class in DSAStackTy for future checking
20978       DSAS->addMappedClassesQualTypes(TE->getType());
20979       // Try to find the associated user-defined mapper.
20980       ExprResult ER = buildUserDefinedMapperRef(
20981           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20982           VE->getType().getCanonicalType(), UnresolvedMapper);
20983       if (ER.isInvalid())
20984         continue;
20985       MVLI.UDMapperList.push_back(ER.get());
20986       // Skip restriction checking for variable or field declarations
20987       MVLI.ProcessedVarList.push_back(RE);
20988       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20989       MVLI.VarComponents.back().append(CurComponents.begin(),
20990                                        CurComponents.end());
20991       MVLI.VarBaseDeclarations.push_back(nullptr);
20992       continue;
20993     }
20994 
20995     // For the following checks, we rely on the base declaration which is
20996     // expected to be associated with the last component. The declaration is
20997     // expected to be a variable or a field (if 'this' is being mapped).
20998     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
20999     assert(CurDeclaration && "Null decl on map clause.");
21000     assert(
21001         CurDeclaration->isCanonicalDecl() &&
21002         "Expecting components to have associated only canonical declarations.");
21003 
21004     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
21005     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
21006 
21007     assert((VD || FD) && "Only variables or fields are expected here!");
21008     (void)FD;
21009 
21010     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
21011     // threadprivate variables cannot appear in a map clause.
21012     // OpenMP 4.5 [2.10.5, target update Construct]
21013     // threadprivate variables cannot appear in a from clause.
21014     if (VD && DSAS->isThreadPrivate(VD)) {
21015       if (NoDiagnose)
21016         continue;
21017       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
21018       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
21019           << getOpenMPClauseName(CKind);
21020       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
21021       continue;
21022     }
21023 
21024     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
21025     //  A list item cannot appear in both a map clause and a data-sharing
21026     //  attribute clause on the same construct.
21027 
21028     // Check conflicts with other map clause expressions. We check the conflicts
21029     // with the current construct separately from the enclosing data
21030     // environment, because the restrictions are different. We only have to
21031     // check conflicts across regions for the map clauses.
21032     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
21033                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
21034       break;
21035     if (CKind == OMPC_map &&
21036         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
21037         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
21038                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
21039       break;
21040 
21041     // OpenMP 4.5 [2.10.5, target update Construct]
21042     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
21043     //  If the type of a list item is a reference to a type T then the type will
21044     //  be considered to be T for all purposes of this clause.
21045     auto I = llvm::find_if(
21046         CurComponents,
21047         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
21048           return MC.getAssociatedDeclaration();
21049         });
21050     assert(I != CurComponents.end() && "Null decl on map clause.");
21051     (void)I;
21052     QualType Type;
21053     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
21054     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
21055     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
21056     if (ASE) {
21057       Type = ASE->getType().getNonReferenceType();
21058     } else if (OASE) {
21059       QualType BaseType =
21060           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
21061       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
21062         Type = ATy->getElementType();
21063       else
21064         Type = BaseType->getPointeeType();
21065       Type = Type.getNonReferenceType();
21066     } else if (OAShE) {
21067       Type = OAShE->getBase()->getType()->getPointeeType();
21068     } else {
21069       Type = VE->getType();
21070     }
21071 
21072     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
21073     // A list item in a to or from clause must have a mappable type.
21074     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
21075     //  A list item must have a mappable type.
21076     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
21077                            DSAS, Type, /*FullCheck=*/true))
21078       continue;
21079 
21080     if (CKind == OMPC_map) {
21081       // target enter data
21082       // OpenMP [2.10.2, Restrictions, p. 99]
21083       // A map-type must be specified in all map clauses and must be either
21084       // to or alloc.
21085       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
21086       if (DKind == OMPD_target_enter_data &&
21087           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
21088         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
21089             << (IsMapTypeImplicit ? 1 : 0)
21090             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
21091             << getOpenMPDirectiveName(DKind);
21092         continue;
21093       }
21094 
21095       // target exit_data
21096       // OpenMP [2.10.3, Restrictions, p. 102]
21097       // A map-type must be specified in all map clauses and must be either
21098       // from, release, or delete.
21099       if (DKind == OMPD_target_exit_data &&
21100           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
21101             MapType == OMPC_MAP_delete)) {
21102         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
21103             << (IsMapTypeImplicit ? 1 : 0)
21104             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
21105             << getOpenMPDirectiveName(DKind);
21106         continue;
21107       }
21108 
21109       // The 'ompx_hold' modifier is specifically intended to be used on a
21110       // 'target' or 'target data' directive to prevent data from being unmapped
21111       // during the associated statement.  It is not permitted on a 'target
21112       // enter data' or 'target exit data' directive, which have no associated
21113       // statement.
21114       if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
21115           HasHoldModifier) {
21116         SemaRef.Diag(StartLoc,
21117                      diag::err_omp_invalid_map_type_modifier_for_directive)
21118             << getOpenMPSimpleClauseTypeName(OMPC_map,
21119                                              OMPC_MAP_MODIFIER_ompx_hold)
21120             << getOpenMPDirectiveName(DKind);
21121         continue;
21122       }
21123 
21124       // target, target data
21125       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
21126       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
21127       // A map-type in a map clause must be to, from, tofrom or alloc
21128       if ((DKind == OMPD_target_data ||
21129            isOpenMPTargetExecutionDirective(DKind)) &&
21130           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
21131             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
21132         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
21133             << (IsMapTypeImplicit ? 1 : 0)
21134             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
21135             << getOpenMPDirectiveName(DKind);
21136         continue;
21137       }
21138 
21139       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
21140       // A list item cannot appear in both a map clause and a data-sharing
21141       // attribute clause on the same construct
21142       //
21143       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
21144       // A list item cannot appear in both a map clause and a data-sharing
21145       // attribute clause on the same construct unless the construct is a
21146       // combined construct.
21147       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
21148                   isOpenMPTargetExecutionDirective(DKind)) ||
21149                  DKind == OMPD_target)) {
21150         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
21151         if (isOpenMPPrivate(DVar.CKind)) {
21152           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21153               << getOpenMPClauseName(DVar.CKind)
21154               << getOpenMPClauseName(OMPC_map)
21155               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
21156           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
21157           continue;
21158         }
21159       }
21160     }
21161 
21162     // Try to find the associated user-defined mapper.
21163     ExprResult ER = buildUserDefinedMapperRef(
21164         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
21165         Type.getCanonicalType(), UnresolvedMapper);
21166     if (ER.isInvalid())
21167       continue;
21168     MVLI.UDMapperList.push_back(ER.get());
21169 
21170     // Save the current expression.
21171     MVLI.ProcessedVarList.push_back(RE);
21172 
21173     // Store the components in the stack so that they can be used to check
21174     // against other clauses later on.
21175     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
21176                                           /*WhereFoundClauseKind=*/OMPC_map);
21177 
21178     // Save the components and declaration to create the clause. For purposes of
21179     // the clause creation, any component list that has has base 'this' uses
21180     // null as base declaration.
21181     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21182     MVLI.VarComponents.back().append(CurComponents.begin(),
21183                                      CurComponents.end());
21184     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
21185                                                            : CurDeclaration);
21186   }
21187 }
21188 
21189 OMPClause *Sema::ActOnOpenMPMapClause(
21190     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
21191     ArrayRef<SourceLocation> MapTypeModifiersLoc,
21192     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
21193     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
21194     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
21195     const OMPVarListLocTy &Locs, bool NoDiagnose,
21196     ArrayRef<Expr *> UnresolvedMappers) {
21197   OpenMPMapModifierKind Modifiers[] = {
21198       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
21199       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
21200       OMPC_MAP_MODIFIER_unknown};
21201   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
21202 
21203   // Process map-type-modifiers, flag errors for duplicate modifiers.
21204   unsigned Count = 0;
21205   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
21206     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
21207         llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
21208       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
21209       continue;
21210     }
21211     assert(Count < NumberOfOMPMapClauseModifiers &&
21212            "Modifiers exceed the allowed number of map type modifiers");
21213     Modifiers[Count] = MapTypeModifiers[I];
21214     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
21215     ++Count;
21216   }
21217 
21218   MappableVarListInfo MVLI(VarList);
21219   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
21220                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
21221                               MapType, Modifiers, IsMapTypeImplicit,
21222                               NoDiagnose);
21223 
21224   // We need to produce a map clause even if we don't have variables so that
21225   // other diagnostics related with non-existing map clauses are accurate.
21226   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
21227                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
21228                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
21229                               MapperIdScopeSpec.getWithLocInContext(Context),
21230                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
21231 }
21232 
21233 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
21234                                                TypeResult ParsedType) {
21235   assert(ParsedType.isUsable());
21236 
21237   QualType ReductionType = GetTypeFromParser(ParsedType.get());
21238   if (ReductionType.isNull())
21239     return QualType();
21240 
21241   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
21242   // A type name in a declare reduction directive cannot be a function type, an
21243   // array type, a reference type, or a type qualified with const, volatile or
21244   // restrict.
21245   if (ReductionType.hasQualifiers()) {
21246     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
21247     return QualType();
21248   }
21249 
21250   if (ReductionType->isFunctionType()) {
21251     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
21252     return QualType();
21253   }
21254   if (ReductionType->isReferenceType()) {
21255     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
21256     return QualType();
21257   }
21258   if (ReductionType->isArrayType()) {
21259     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
21260     return QualType();
21261   }
21262   return ReductionType;
21263 }
21264 
21265 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
21266     Scope *S, DeclContext *DC, DeclarationName Name,
21267     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
21268     AccessSpecifier AS, Decl *PrevDeclInScope) {
21269   SmallVector<Decl *, 8> Decls;
21270   Decls.reserve(ReductionTypes.size());
21271 
21272   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
21273                       forRedeclarationInCurContext());
21274   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
21275   // A reduction-identifier may not be re-declared in the current scope for the
21276   // same type or for a type that is compatible according to the base language
21277   // rules.
21278   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
21279   OMPDeclareReductionDecl *PrevDRD = nullptr;
21280   bool InCompoundScope = true;
21281   if (S != nullptr) {
21282     // Find previous declaration with the same name not referenced in other
21283     // declarations.
21284     FunctionScopeInfo *ParentFn = getEnclosingFunction();
21285     InCompoundScope =
21286         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
21287     LookupName(Lookup, S);
21288     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
21289                          /*AllowInlineNamespace=*/false);
21290     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
21291     LookupResult::Filter Filter = Lookup.makeFilter();
21292     while (Filter.hasNext()) {
21293       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
21294       if (InCompoundScope) {
21295         auto I = UsedAsPrevious.find(PrevDecl);
21296         if (I == UsedAsPrevious.end())
21297           UsedAsPrevious[PrevDecl] = false;
21298         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
21299           UsedAsPrevious[D] = true;
21300       }
21301       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
21302           PrevDecl->getLocation();
21303     }
21304     Filter.done();
21305     if (InCompoundScope) {
21306       for (const auto &PrevData : UsedAsPrevious) {
21307         if (!PrevData.second) {
21308           PrevDRD = PrevData.first;
21309           break;
21310         }
21311       }
21312     }
21313   } else if (PrevDeclInScope != nullptr) {
21314     auto *PrevDRDInScope = PrevDRD =
21315         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
21316     do {
21317       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
21318           PrevDRDInScope->getLocation();
21319       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
21320     } while (PrevDRDInScope != nullptr);
21321   }
21322   for (const auto &TyData : ReductionTypes) {
21323     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
21324     bool Invalid = false;
21325     if (I != PreviousRedeclTypes.end()) {
21326       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
21327           << TyData.first;
21328       Diag(I->second, diag::note_previous_definition);
21329       Invalid = true;
21330     }
21331     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
21332     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
21333                                                 Name, TyData.first, PrevDRD);
21334     DC->addDecl(DRD);
21335     DRD->setAccess(AS);
21336     Decls.push_back(DRD);
21337     if (Invalid)
21338       DRD->setInvalidDecl();
21339     else
21340       PrevDRD = DRD;
21341   }
21342 
21343   return DeclGroupPtrTy::make(
21344       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
21345 }
21346 
21347 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
21348   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21349 
21350   // Enter new function scope.
21351   PushFunctionScope();
21352   setFunctionHasBranchProtectedScope();
21353   getCurFunction()->setHasOMPDeclareReductionCombiner();
21354 
21355   if (S != nullptr)
21356     PushDeclContext(S, DRD);
21357   else
21358     CurContext = DRD;
21359 
21360   PushExpressionEvaluationContext(
21361       ExpressionEvaluationContext::PotentiallyEvaluated);
21362 
21363   QualType ReductionType = DRD->getType();
21364   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
21365   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
21366   // uses semantics of argument handles by value, but it should be passed by
21367   // reference. C lang does not support references, so pass all parameters as
21368   // pointers.
21369   // Create 'T omp_in;' variable.
21370   VarDecl *OmpInParm =
21371       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
21372   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
21373   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
21374   // uses semantics of argument handles by value, but it should be passed by
21375   // reference. C lang does not support references, so pass all parameters as
21376   // pointers.
21377   // Create 'T omp_out;' variable.
21378   VarDecl *OmpOutParm =
21379       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
21380   if (S != nullptr) {
21381     PushOnScopeChains(OmpInParm, S);
21382     PushOnScopeChains(OmpOutParm, S);
21383   } else {
21384     DRD->addDecl(OmpInParm);
21385     DRD->addDecl(OmpOutParm);
21386   }
21387   Expr *InE =
21388       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
21389   Expr *OutE =
21390       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
21391   DRD->setCombinerData(InE, OutE);
21392 }
21393 
21394 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
21395   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21396   DiscardCleanupsInEvaluationContext();
21397   PopExpressionEvaluationContext();
21398 
21399   PopDeclContext();
21400   PopFunctionScopeInfo();
21401 
21402   if (Combiner != nullptr)
21403     DRD->setCombiner(Combiner);
21404   else
21405     DRD->setInvalidDecl();
21406 }
21407 
21408 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
21409   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21410 
21411   // Enter new function scope.
21412   PushFunctionScope();
21413   setFunctionHasBranchProtectedScope();
21414 
21415   if (S != nullptr)
21416     PushDeclContext(S, DRD);
21417   else
21418     CurContext = DRD;
21419 
21420   PushExpressionEvaluationContext(
21421       ExpressionEvaluationContext::PotentiallyEvaluated);
21422 
21423   QualType ReductionType = DRD->getType();
21424   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
21425   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
21426   // uses semantics of argument handles by value, but it should be passed by
21427   // reference. C lang does not support references, so pass all parameters as
21428   // pointers.
21429   // Create 'T omp_priv;' variable.
21430   VarDecl *OmpPrivParm =
21431       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
21432   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
21433   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
21434   // uses semantics of argument handles by value, but it should be passed by
21435   // reference. C lang does not support references, so pass all parameters as
21436   // pointers.
21437   // Create 'T omp_orig;' variable.
21438   VarDecl *OmpOrigParm =
21439       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
21440   if (S != nullptr) {
21441     PushOnScopeChains(OmpPrivParm, S);
21442     PushOnScopeChains(OmpOrigParm, S);
21443   } else {
21444     DRD->addDecl(OmpPrivParm);
21445     DRD->addDecl(OmpOrigParm);
21446   }
21447   Expr *OrigE =
21448       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
21449   Expr *PrivE =
21450       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
21451   DRD->setInitializerData(OrigE, PrivE);
21452   return OmpPrivParm;
21453 }
21454 
21455 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
21456                                                      VarDecl *OmpPrivParm) {
21457   auto *DRD = cast<OMPDeclareReductionDecl>(D);
21458   DiscardCleanupsInEvaluationContext();
21459   PopExpressionEvaluationContext();
21460 
21461   PopDeclContext();
21462   PopFunctionScopeInfo();
21463 
21464   if (Initializer != nullptr) {
21465     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
21466   } else if (OmpPrivParm->hasInit()) {
21467     DRD->setInitializer(OmpPrivParm->getInit(),
21468                         OmpPrivParm->isDirectInit()
21469                             ? OMPDeclareReductionDecl::DirectInit
21470                             : OMPDeclareReductionDecl::CopyInit);
21471   } else {
21472     DRD->setInvalidDecl();
21473   }
21474 }
21475 
21476 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
21477     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
21478   for (Decl *D : DeclReductions.get()) {
21479     if (IsValid) {
21480       if (S)
21481         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
21482                           /*AddToContext=*/false);
21483     } else {
21484       D->setInvalidDecl();
21485     }
21486   }
21487   return DeclReductions;
21488 }
21489 
21490 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
21491   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
21492   QualType T = TInfo->getType();
21493   if (D.isInvalidType())
21494     return true;
21495 
21496   if (getLangOpts().CPlusPlus) {
21497     // Check that there are no default arguments (C++ only).
21498     CheckExtraCXXDefaultArguments(D);
21499   }
21500 
21501   return CreateParsedType(T, TInfo);
21502 }
21503 
21504 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
21505                                             TypeResult ParsedType) {
21506   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
21507 
21508   QualType MapperType = GetTypeFromParser(ParsedType.get());
21509   assert(!MapperType.isNull() && "Expect valid mapper type");
21510 
21511   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
21512   //  The type must be of struct, union or class type in C and C++
21513   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
21514     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
21515     return QualType();
21516   }
21517   return MapperType;
21518 }
21519 
21520 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
21521     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
21522     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
21523     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
21524   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
21525                       forRedeclarationInCurContext());
21526   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
21527   //  A mapper-identifier may not be redeclared in the current scope for the
21528   //  same type or for a type that is compatible according to the base language
21529   //  rules.
21530   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
21531   OMPDeclareMapperDecl *PrevDMD = nullptr;
21532   bool InCompoundScope = true;
21533   if (S != nullptr) {
21534     // Find previous declaration with the same name not referenced in other
21535     // declarations.
21536     FunctionScopeInfo *ParentFn = getEnclosingFunction();
21537     InCompoundScope =
21538         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
21539     LookupName(Lookup, S);
21540     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
21541                          /*AllowInlineNamespace=*/false);
21542     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
21543     LookupResult::Filter Filter = Lookup.makeFilter();
21544     while (Filter.hasNext()) {
21545       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
21546       if (InCompoundScope) {
21547         auto I = UsedAsPrevious.find(PrevDecl);
21548         if (I == UsedAsPrevious.end())
21549           UsedAsPrevious[PrevDecl] = false;
21550         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
21551           UsedAsPrevious[D] = true;
21552       }
21553       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
21554           PrevDecl->getLocation();
21555     }
21556     Filter.done();
21557     if (InCompoundScope) {
21558       for (const auto &PrevData : UsedAsPrevious) {
21559         if (!PrevData.second) {
21560           PrevDMD = PrevData.first;
21561           break;
21562         }
21563       }
21564     }
21565   } else if (PrevDeclInScope) {
21566     auto *PrevDMDInScope = PrevDMD =
21567         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
21568     do {
21569       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
21570           PrevDMDInScope->getLocation();
21571       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
21572     } while (PrevDMDInScope != nullptr);
21573   }
21574   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
21575   bool Invalid = false;
21576   if (I != PreviousRedeclTypes.end()) {
21577     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
21578         << MapperType << Name;
21579     Diag(I->second, diag::note_previous_definition);
21580     Invalid = true;
21581   }
21582   // Build expressions for implicit maps of data members with 'default'
21583   // mappers.
21584   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
21585                                                   Clauses.end());
21586   if (LangOpts.OpenMP >= 50)
21587     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
21588   auto *DMD =
21589       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
21590                                    ClausesWithImplicit, PrevDMD);
21591   if (S)
21592     PushOnScopeChains(DMD, S);
21593   else
21594     DC->addDecl(DMD);
21595   DMD->setAccess(AS);
21596   if (Invalid)
21597     DMD->setInvalidDecl();
21598 
21599   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
21600   VD->setDeclContext(DMD);
21601   VD->setLexicalDeclContext(DMD);
21602   DMD->addDecl(VD);
21603   DMD->setMapperVarRef(MapperVarRef);
21604 
21605   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
21606 }
21607 
21608 ExprResult
21609 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
21610                                                SourceLocation StartLoc,
21611                                                DeclarationName VN) {
21612   TypeSourceInfo *TInfo =
21613       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
21614   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
21615                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
21616                              MapperType, TInfo, SC_None);
21617   if (S)
21618     PushOnScopeChains(VD, S, /*AddToContext=*/false);
21619   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
21620   DSAStack->addDeclareMapperVarRef(E);
21621   return E;
21622 }
21623 
21624 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
21625   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
21626   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
21627   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
21628     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
21629       return true;
21630     if (VD->isUsableInConstantExpressions(Context))
21631       return true;
21632     return false;
21633   }
21634   return true;
21635 }
21636 
21637 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
21638   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
21639   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
21640 }
21641 
21642 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
21643                                            SourceLocation StartLoc,
21644                                            SourceLocation LParenLoc,
21645                                            SourceLocation EndLoc) {
21646   Expr *ValExpr = NumTeams;
21647   Stmt *HelperValStmt = nullptr;
21648 
21649   // OpenMP [teams Constrcut, Restrictions]
21650   // The num_teams expression must evaluate to a positive integer value.
21651   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
21652                                  /*StrictlyPositive=*/true))
21653     return nullptr;
21654 
21655   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
21656   OpenMPDirectiveKind CaptureRegion =
21657       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
21658   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
21659     ValExpr = MakeFullExpr(ValExpr).get();
21660     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21661     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21662     HelperValStmt = buildPreInits(Context, Captures);
21663   }
21664 
21665   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
21666                                          StartLoc, LParenLoc, EndLoc);
21667 }
21668 
21669 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
21670                                               SourceLocation StartLoc,
21671                                               SourceLocation LParenLoc,
21672                                               SourceLocation EndLoc) {
21673   Expr *ValExpr = ThreadLimit;
21674   Stmt *HelperValStmt = nullptr;
21675 
21676   // OpenMP [teams Constrcut, Restrictions]
21677   // The thread_limit expression must evaluate to a positive integer value.
21678   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
21679                                  /*StrictlyPositive=*/true))
21680     return nullptr;
21681 
21682   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
21683   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
21684       DKind, OMPC_thread_limit, LangOpts.OpenMP);
21685   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
21686     ValExpr = MakeFullExpr(ValExpr).get();
21687     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21688     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21689     HelperValStmt = buildPreInits(Context, Captures);
21690   }
21691 
21692   return new (Context) OMPThreadLimitClause(
21693       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
21694 }
21695 
21696 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
21697                                            SourceLocation StartLoc,
21698                                            SourceLocation LParenLoc,
21699                                            SourceLocation EndLoc) {
21700   Expr *ValExpr = Priority;
21701   Stmt *HelperValStmt = nullptr;
21702   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
21703 
21704   // OpenMP [2.9.1, task Constrcut]
21705   // The priority-value is a non-negative numerical scalar expression.
21706   if (!isNonNegativeIntegerValue(
21707           ValExpr, *this, OMPC_priority,
21708           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
21709           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
21710     return nullptr;
21711 
21712   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
21713                                          StartLoc, LParenLoc, EndLoc);
21714 }
21715 
21716 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
21717                                             SourceLocation StartLoc,
21718                                             SourceLocation LParenLoc,
21719                                             SourceLocation EndLoc) {
21720   Expr *ValExpr = Grainsize;
21721   Stmt *HelperValStmt = nullptr;
21722   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
21723 
21724   // OpenMP [2.9.2, taskloop Constrcut]
21725   // The parameter of the grainsize clause must be a positive integer
21726   // expression.
21727   if (!isNonNegativeIntegerValue(
21728           ValExpr, *this, OMPC_grainsize,
21729           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
21730           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
21731     return nullptr;
21732 
21733   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
21734                                           StartLoc, LParenLoc, EndLoc);
21735 }
21736 
21737 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
21738                                            SourceLocation StartLoc,
21739                                            SourceLocation LParenLoc,
21740                                            SourceLocation EndLoc) {
21741   Expr *ValExpr = NumTasks;
21742   Stmt *HelperValStmt = nullptr;
21743   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
21744 
21745   // OpenMP [2.9.2, taskloop Constrcut]
21746   // The parameter of the num_tasks clause must be a positive integer
21747   // expression.
21748   if (!isNonNegativeIntegerValue(
21749           ValExpr, *this, OMPC_num_tasks,
21750           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
21751           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
21752     return nullptr;
21753 
21754   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
21755                                          StartLoc, LParenLoc, EndLoc);
21756 }
21757 
21758 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
21759                                        SourceLocation LParenLoc,
21760                                        SourceLocation EndLoc) {
21761   // OpenMP [2.13.2, critical construct, Description]
21762   // ... where hint-expression is an integer constant expression that evaluates
21763   // to a valid lock hint.
21764   ExprResult HintExpr =
21765       VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint, false);
21766   if (HintExpr.isInvalid())
21767     return nullptr;
21768   return new (Context)
21769       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
21770 }
21771 
21772 /// Tries to find omp_event_handle_t type.
21773 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
21774                                 DSAStackTy *Stack) {
21775   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
21776   if (!OMPEventHandleT.isNull())
21777     return true;
21778   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
21779   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
21780   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21781     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
21782     return false;
21783   }
21784   Stack->setOMPEventHandleT(PT.get());
21785   return true;
21786 }
21787 
21788 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
21789                                          SourceLocation LParenLoc,
21790                                          SourceLocation EndLoc) {
21791   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
21792       !Evt->isInstantiationDependent() &&
21793       !Evt->containsUnexpandedParameterPack()) {
21794     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
21795       return nullptr;
21796     // OpenMP 5.0, 2.10.1 task Construct.
21797     // event-handle is a variable of the omp_event_handle_t type.
21798     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
21799     if (!Ref) {
21800       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
21801           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
21802       return nullptr;
21803     }
21804     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
21805     if (!VD) {
21806       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
21807           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
21808       return nullptr;
21809     }
21810     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
21811                                         VD->getType()) ||
21812         VD->getType().isConstant(Context)) {
21813       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
21814           << "omp_event_handle_t" << 1 << VD->getType()
21815           << Evt->getSourceRange();
21816       return nullptr;
21817     }
21818     // OpenMP 5.0, 2.10.1 task Construct
21819     // [detach clause]... The event-handle will be considered as if it was
21820     // specified on a firstprivate clause.
21821     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
21822     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
21823         DVar.RefExpr) {
21824       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
21825           << getOpenMPClauseName(DVar.CKind)
21826           << getOpenMPClauseName(OMPC_firstprivate);
21827       reportOriginalDsa(*this, DSAStack, VD, DVar);
21828       return nullptr;
21829     }
21830   }
21831 
21832   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
21833 }
21834 
21835 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
21836     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
21837     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
21838     SourceLocation EndLoc) {
21839   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
21840     std::string Values;
21841     Values += "'";
21842     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
21843     Values += "'";
21844     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21845         << Values << getOpenMPClauseName(OMPC_dist_schedule);
21846     return nullptr;
21847   }
21848   Expr *ValExpr = ChunkSize;
21849   Stmt *HelperValStmt = nullptr;
21850   if (ChunkSize) {
21851     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
21852         !ChunkSize->isInstantiationDependent() &&
21853         !ChunkSize->containsUnexpandedParameterPack()) {
21854       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
21855       ExprResult Val =
21856           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
21857       if (Val.isInvalid())
21858         return nullptr;
21859 
21860       ValExpr = Val.get();
21861 
21862       // OpenMP [2.7.1, Restrictions]
21863       //  chunk_size must be a loop invariant integer expression with a positive
21864       //  value.
21865       if (Optional<llvm::APSInt> Result =
21866               ValExpr->getIntegerConstantExpr(Context)) {
21867         if (Result->isSigned() && !Result->isStrictlyPositive()) {
21868           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
21869               << "dist_schedule" << ChunkSize->getSourceRange();
21870           return nullptr;
21871         }
21872       } else if (getOpenMPCaptureRegionForClause(
21873                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
21874                      LangOpts.OpenMP) != OMPD_unknown &&
21875                  !CurContext->isDependentContext()) {
21876         ValExpr = MakeFullExpr(ValExpr).get();
21877         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21878         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21879         HelperValStmt = buildPreInits(Context, Captures);
21880       }
21881     }
21882   }
21883 
21884   return new (Context)
21885       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
21886                             Kind, ValExpr, HelperValStmt);
21887 }
21888 
21889 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
21890     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
21891     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
21892     SourceLocation KindLoc, SourceLocation EndLoc) {
21893   if (getLangOpts().OpenMP < 50) {
21894     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
21895         Kind != OMPC_DEFAULTMAP_scalar) {
21896       std::string Value;
21897       SourceLocation Loc;
21898       Value += "'";
21899       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
21900         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
21901                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
21902         Loc = MLoc;
21903       } else {
21904         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
21905                                                OMPC_DEFAULTMAP_scalar);
21906         Loc = KindLoc;
21907       }
21908       Value += "'";
21909       Diag(Loc, diag::err_omp_unexpected_clause_value)
21910           << Value << getOpenMPClauseName(OMPC_defaultmap);
21911       return nullptr;
21912     }
21913   } else {
21914     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
21915     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
21916                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
21917     if (!isDefaultmapKind || !isDefaultmapModifier) {
21918       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
21919       if (LangOpts.OpenMP == 50) {
21920         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
21921                                   "'firstprivate', 'none', 'default'";
21922         if (!isDefaultmapKind && isDefaultmapModifier) {
21923           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21924               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21925         } else if (isDefaultmapKind && !isDefaultmapModifier) {
21926           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21927               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21928         } else {
21929           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21930               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21931           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21932               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21933         }
21934       } else {
21935         StringRef ModifierValue =
21936             "'alloc', 'from', 'to', 'tofrom', "
21937             "'firstprivate', 'none', 'default', 'present'";
21938         if (!isDefaultmapKind && isDefaultmapModifier) {
21939           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21940               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21941         } else if (isDefaultmapKind && !isDefaultmapModifier) {
21942           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21943               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21944         } else {
21945           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21946               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21947           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21948               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21949         }
21950       }
21951       return nullptr;
21952     }
21953 
21954     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
21955     //  At most one defaultmap clause for each category can appear on the
21956     //  directive.
21957     if (DSAStack->checkDefaultmapCategory(Kind)) {
21958       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
21959       return nullptr;
21960     }
21961   }
21962   if (Kind == OMPC_DEFAULTMAP_unknown) {
21963     // Variable category is not specified - mark all categories.
21964     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
21965     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
21966     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
21967   } else {
21968     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
21969   }
21970 
21971   return new (Context)
21972       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
21973 }
21974 
21975 bool Sema::ActOnStartOpenMPDeclareTargetContext(
21976     DeclareTargetContextInfo &DTCI) {
21977   DeclContext *CurLexicalContext = getCurLexicalContext();
21978   if (!CurLexicalContext->isFileContext() &&
21979       !CurLexicalContext->isExternCContext() &&
21980       !CurLexicalContext->isExternCXXContext() &&
21981       !isa<CXXRecordDecl>(CurLexicalContext) &&
21982       !isa<ClassTemplateDecl>(CurLexicalContext) &&
21983       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
21984       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
21985     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
21986     return false;
21987   }
21988   DeclareTargetNesting.push_back(DTCI);
21989   return true;
21990 }
21991 
21992 const Sema::DeclareTargetContextInfo
21993 Sema::ActOnOpenMPEndDeclareTargetDirective() {
21994   assert(!DeclareTargetNesting.empty() &&
21995          "check isInOpenMPDeclareTargetContext() first!");
21996   return DeclareTargetNesting.pop_back_val();
21997 }
21998 
21999 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
22000     DeclareTargetContextInfo &DTCI) {
22001   for (auto &It : DTCI.ExplicitlyMapped)
22002     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI);
22003 }
22004 
22005 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
22006                                                CXXScopeSpec &ScopeSpec,
22007                                                const DeclarationNameInfo &Id) {
22008   LookupResult Lookup(*this, Id, LookupOrdinaryName);
22009   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
22010 
22011   if (Lookup.isAmbiguous())
22012     return nullptr;
22013   Lookup.suppressDiagnostics();
22014 
22015   if (!Lookup.isSingleResult()) {
22016     VarOrFuncDeclFilterCCC CCC(*this);
22017     if (TypoCorrection Corrected =
22018             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
22019                         CTK_ErrorRecovery)) {
22020       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
22021                                   << Id.getName());
22022       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
22023       return nullptr;
22024     }
22025 
22026     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
22027     return nullptr;
22028   }
22029 
22030   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
22031   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
22032       !isa<FunctionTemplateDecl>(ND)) {
22033     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
22034     return nullptr;
22035   }
22036   return ND;
22037 }
22038 
22039 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
22040                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
22041                                         DeclareTargetContextInfo &DTCI) {
22042   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
22043           isa<FunctionTemplateDecl>(ND)) &&
22044          "Expected variable, function or function template.");
22045 
22046   // Diagnose marking after use as it may lead to incorrect diagnosis and
22047   // codegen.
22048   if (LangOpts.OpenMP >= 50 &&
22049       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
22050     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
22051 
22052   // Explicit declare target lists have precedence.
22053   const unsigned Level = -1;
22054 
22055   auto *VD = cast<ValueDecl>(ND);
22056   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
22057       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
22058   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT &&
22059       ActiveAttr.getValue()->getLevel() == Level) {
22060     Diag(Loc, diag::err_omp_device_type_mismatch)
22061         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
22062         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
22063                ActiveAttr.getValue()->getDevType());
22064     return;
22065   }
22066   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
22067       ActiveAttr.getValue()->getLevel() == Level) {
22068     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
22069     return;
22070   }
22071 
22072   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
22073     return;
22074 
22075   Expr *IndirectE = nullptr;
22076   bool IsIndirect = false;
22077   if (DTCI.Indirect.hasValue()) {
22078     IndirectE = DTCI.Indirect.getValue();
22079     if (!IndirectE)
22080       IsIndirect = true;
22081   }
22082   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
22083       Context, MT, DTCI.DT, IndirectE, IsIndirect, Level,
22084       SourceRange(Loc, Loc));
22085   ND->addAttr(A);
22086   if (ASTMutationListener *ML = Context.getASTMutationListener())
22087     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
22088   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
22089 }
22090 
22091 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
22092                                      Sema &SemaRef, Decl *D) {
22093   if (!D || !isa<VarDecl>(D))
22094     return;
22095   auto *VD = cast<VarDecl>(D);
22096   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
22097       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
22098   if (SemaRef.LangOpts.OpenMP >= 50 &&
22099       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
22100        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
22101       VD->hasGlobalStorage()) {
22102     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
22103       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
22104       // If a lambda declaration and definition appears between a
22105       // declare target directive and the matching end declare target
22106       // directive, all variables that are captured by the lambda
22107       // expression must also appear in a to clause.
22108       SemaRef.Diag(VD->getLocation(),
22109                    diag::err_omp_lambda_capture_in_declare_target_not_to);
22110       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
22111           << VD << 0 << SR;
22112       return;
22113     }
22114   }
22115   if (MapTy.hasValue())
22116     return;
22117   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
22118   SemaRef.Diag(SL, diag::note_used_here) << SR;
22119 }
22120 
22121 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
22122                                    Sema &SemaRef, DSAStackTy *Stack,
22123                                    ValueDecl *VD) {
22124   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
22125          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
22126                            /*FullCheck=*/false);
22127 }
22128 
22129 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
22130                                             SourceLocation IdLoc) {
22131   if (!D || D->isInvalidDecl())
22132     return;
22133   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
22134   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
22135   if (auto *VD = dyn_cast<VarDecl>(D)) {
22136     // Only global variables can be marked as declare target.
22137     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
22138         !VD->isStaticDataMember())
22139       return;
22140     // 2.10.6: threadprivate variable cannot appear in a declare target
22141     // directive.
22142     if (DSAStack->isThreadPrivate(VD)) {
22143       Diag(SL, diag::err_omp_threadprivate_in_target);
22144       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
22145       return;
22146     }
22147   }
22148   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
22149     D = FTD->getTemplatedDecl();
22150   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
22151     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
22152         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
22153     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
22154       Diag(IdLoc, diag::err_omp_function_in_link_clause);
22155       Diag(FD->getLocation(), diag::note_defined_here) << FD;
22156       return;
22157     }
22158   }
22159   if (auto *VD = dyn_cast<ValueDecl>(D)) {
22160     // Problem if any with var declared with incomplete type will be reported
22161     // as normal, so no need to check it here.
22162     if ((E || !VD->getType()->isIncompleteType()) &&
22163         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
22164       return;
22165     if (!E && isInOpenMPDeclareTargetContext()) {
22166       // Checking declaration inside declare target region.
22167       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
22168           isa<FunctionTemplateDecl>(D)) {
22169         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
22170             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
22171         unsigned Level = DeclareTargetNesting.size();
22172         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
22173           return;
22174         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
22175         Expr *IndirectE = nullptr;
22176         bool IsIndirect = false;
22177         if (DTCI.Indirect.hasValue()) {
22178           IndirectE = DTCI.Indirect.getValue();
22179           if (!IndirectE)
22180             IsIndirect = true;
22181         }
22182         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
22183             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE,
22184             IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc));
22185         D->addAttr(A);
22186         if (ASTMutationListener *ML = Context.getASTMutationListener())
22187           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
22188       }
22189       return;
22190     }
22191   }
22192   if (!E)
22193     return;
22194   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
22195 }
22196 
22197 OMPClause *Sema::ActOnOpenMPToClause(
22198     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
22199     ArrayRef<SourceLocation> MotionModifiersLoc,
22200     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
22201     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
22202     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
22203   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
22204                                           OMPC_MOTION_MODIFIER_unknown};
22205   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
22206 
22207   // Process motion-modifiers, flag errors for duplicate modifiers.
22208   unsigned Count = 0;
22209   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
22210     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
22211         llvm::is_contained(Modifiers, MotionModifiers[I])) {
22212       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
22213       continue;
22214     }
22215     assert(Count < NumberOfOMPMotionModifiers &&
22216            "Modifiers exceed the allowed number of motion modifiers");
22217     Modifiers[Count] = MotionModifiers[I];
22218     ModifiersLoc[Count] = MotionModifiersLoc[I];
22219     ++Count;
22220   }
22221 
22222   MappableVarListInfo MVLI(VarList);
22223   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
22224                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
22225   if (MVLI.ProcessedVarList.empty())
22226     return nullptr;
22227 
22228   return OMPToClause::Create(
22229       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
22230       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
22231       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
22232 }
22233 
22234 OMPClause *Sema::ActOnOpenMPFromClause(
22235     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
22236     ArrayRef<SourceLocation> MotionModifiersLoc,
22237     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
22238     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
22239     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
22240   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
22241                                           OMPC_MOTION_MODIFIER_unknown};
22242   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
22243 
22244   // Process motion-modifiers, flag errors for duplicate modifiers.
22245   unsigned Count = 0;
22246   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
22247     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
22248         llvm::is_contained(Modifiers, MotionModifiers[I])) {
22249       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
22250       continue;
22251     }
22252     assert(Count < NumberOfOMPMotionModifiers &&
22253            "Modifiers exceed the allowed number of motion modifiers");
22254     Modifiers[Count] = MotionModifiers[I];
22255     ModifiersLoc[Count] = MotionModifiersLoc[I];
22256     ++Count;
22257   }
22258 
22259   MappableVarListInfo MVLI(VarList);
22260   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
22261                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
22262   if (MVLI.ProcessedVarList.empty())
22263     return nullptr;
22264 
22265   return OMPFromClause::Create(
22266       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
22267       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
22268       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
22269 }
22270 
22271 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
22272                                                const OMPVarListLocTy &Locs) {
22273   MappableVarListInfo MVLI(VarList);
22274   SmallVector<Expr *, 8> PrivateCopies;
22275   SmallVector<Expr *, 8> Inits;
22276 
22277   for (Expr *RefExpr : VarList) {
22278     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
22279     SourceLocation ELoc;
22280     SourceRange ERange;
22281     Expr *SimpleRefExpr = RefExpr;
22282     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22283     if (Res.second) {
22284       // It will be analyzed later.
22285       MVLI.ProcessedVarList.push_back(RefExpr);
22286       PrivateCopies.push_back(nullptr);
22287       Inits.push_back(nullptr);
22288     }
22289     ValueDecl *D = Res.first;
22290     if (!D)
22291       continue;
22292 
22293     QualType Type = D->getType();
22294     Type = Type.getNonReferenceType().getUnqualifiedType();
22295 
22296     auto *VD = dyn_cast<VarDecl>(D);
22297 
22298     // Item should be a pointer or reference to pointer.
22299     if (!Type->isPointerType()) {
22300       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
22301           << 0 << RefExpr->getSourceRange();
22302       continue;
22303     }
22304 
22305     // Build the private variable and the expression that refers to it.
22306     auto VDPrivate =
22307         buildVarDecl(*this, ELoc, Type, D->getName(),
22308                      D->hasAttrs() ? &D->getAttrs() : nullptr,
22309                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
22310     if (VDPrivate->isInvalidDecl())
22311       continue;
22312 
22313     CurContext->addDecl(VDPrivate);
22314     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
22315         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
22316 
22317     // Add temporary variable to initialize the private copy of the pointer.
22318     VarDecl *VDInit =
22319         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
22320     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
22321         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
22322     AddInitializerToDecl(VDPrivate,
22323                          DefaultLvalueConversion(VDInitRefExpr).get(),
22324                          /*DirectInit=*/false);
22325 
22326     // If required, build a capture to implement the privatization initialized
22327     // with the current list item value.
22328     DeclRefExpr *Ref = nullptr;
22329     if (!VD)
22330       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
22331     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
22332     PrivateCopies.push_back(VDPrivateRefExpr);
22333     Inits.push_back(VDInitRefExpr);
22334 
22335     // We need to add a data sharing attribute for this variable to make sure it
22336     // is correctly captured. A variable that shows up in a use_device_ptr has
22337     // similar properties of a first private variable.
22338     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
22339 
22340     // Create a mappable component for the list item. List items in this clause
22341     // only need a component.
22342     MVLI.VarBaseDeclarations.push_back(D);
22343     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
22344     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
22345                                            /*IsNonContiguous=*/false);
22346   }
22347 
22348   if (MVLI.ProcessedVarList.empty())
22349     return nullptr;
22350 
22351   return OMPUseDevicePtrClause::Create(
22352       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
22353       MVLI.VarBaseDeclarations, MVLI.VarComponents);
22354 }
22355 
22356 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
22357                                                 const OMPVarListLocTy &Locs) {
22358   MappableVarListInfo MVLI(VarList);
22359 
22360   for (Expr *RefExpr : VarList) {
22361     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
22362     SourceLocation ELoc;
22363     SourceRange ERange;
22364     Expr *SimpleRefExpr = RefExpr;
22365     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22366                               /*AllowArraySection=*/true);
22367     if (Res.second) {
22368       // It will be analyzed later.
22369       MVLI.ProcessedVarList.push_back(RefExpr);
22370     }
22371     ValueDecl *D = Res.first;
22372     if (!D)
22373       continue;
22374     auto *VD = dyn_cast<VarDecl>(D);
22375 
22376     // If required, build a capture to implement the privatization initialized
22377     // with the current list item value.
22378     DeclRefExpr *Ref = nullptr;
22379     if (!VD)
22380       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
22381     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
22382 
22383     // We need to add a data sharing attribute for this variable to make sure it
22384     // is correctly captured. A variable that shows up in a use_device_addr has
22385     // similar properties of a first private variable.
22386     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
22387 
22388     // Create a mappable component for the list item. List items in this clause
22389     // only need a component.
22390     MVLI.VarBaseDeclarations.push_back(D);
22391     MVLI.VarComponents.emplace_back();
22392     Expr *Component = SimpleRefExpr;
22393     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
22394                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
22395       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
22396     MVLI.VarComponents.back().emplace_back(Component, D,
22397                                            /*IsNonContiguous=*/false);
22398   }
22399 
22400   if (MVLI.ProcessedVarList.empty())
22401     return nullptr;
22402 
22403   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
22404                                         MVLI.VarBaseDeclarations,
22405                                         MVLI.VarComponents);
22406 }
22407 
22408 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
22409                                               const OMPVarListLocTy &Locs) {
22410   MappableVarListInfo MVLI(VarList);
22411   for (Expr *RefExpr : VarList) {
22412     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
22413     SourceLocation ELoc;
22414     SourceRange ERange;
22415     Expr *SimpleRefExpr = RefExpr;
22416     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22417     if (Res.second) {
22418       // It will be analyzed later.
22419       MVLI.ProcessedVarList.push_back(RefExpr);
22420     }
22421     ValueDecl *D = Res.first;
22422     if (!D)
22423       continue;
22424 
22425     QualType Type = D->getType();
22426     // item should be a pointer or array or reference to pointer or array
22427     if (!Type.getNonReferenceType()->isPointerType() &&
22428         !Type.getNonReferenceType()->isArrayType()) {
22429       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
22430           << 0 << RefExpr->getSourceRange();
22431       continue;
22432     }
22433 
22434     // Check if the declaration in the clause does not show up in any data
22435     // sharing attribute.
22436     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
22437     if (isOpenMPPrivate(DVar.CKind)) {
22438       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
22439           << getOpenMPClauseName(DVar.CKind)
22440           << getOpenMPClauseName(OMPC_is_device_ptr)
22441           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
22442       reportOriginalDsa(*this, DSAStack, D, DVar);
22443       continue;
22444     }
22445 
22446     const Expr *ConflictExpr;
22447     if (DSAStack->checkMappableExprComponentListsForDecl(
22448             D, /*CurrentRegionOnly=*/true,
22449             [&ConflictExpr](
22450                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
22451                 OpenMPClauseKind) -> bool {
22452               ConflictExpr = R.front().getAssociatedExpression();
22453               return true;
22454             })) {
22455       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
22456       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
22457           << ConflictExpr->getSourceRange();
22458       continue;
22459     }
22460 
22461     // Store the components in the stack so that they can be used to check
22462     // against other clauses later on.
22463     OMPClauseMappableExprCommon::MappableComponent MC(
22464         SimpleRefExpr, D, /*IsNonContiguous=*/false);
22465     DSAStack->addMappableExpressionComponents(
22466         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
22467 
22468     // Record the expression we've just processed.
22469     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
22470 
22471     // Create a mappable component for the list item. List items in this clause
22472     // only need a component. We use a null declaration to signal fields in
22473     // 'this'.
22474     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
22475             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
22476            "Unexpected device pointer expression!");
22477     MVLI.VarBaseDeclarations.push_back(
22478         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
22479     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
22480     MVLI.VarComponents.back().push_back(MC);
22481   }
22482 
22483   if (MVLI.ProcessedVarList.empty())
22484     return nullptr;
22485 
22486   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
22487                                       MVLI.VarBaseDeclarations,
22488                                       MVLI.VarComponents);
22489 }
22490 
22491 OMPClause *Sema::ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
22492                                                 const OMPVarListLocTy &Locs) {
22493   MappableVarListInfo MVLI(VarList);
22494   for (Expr *RefExpr : VarList) {
22495     assert(RefExpr && "NULL expr in OpenMP has_device_addr clause.");
22496     SourceLocation ELoc;
22497     SourceRange ERange;
22498     Expr *SimpleRefExpr = RefExpr;
22499     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22500                               /*AllowArraySection=*/true);
22501     if (Res.second) {
22502       // It will be analyzed later.
22503       MVLI.ProcessedVarList.push_back(RefExpr);
22504     }
22505     ValueDecl *D = Res.first;
22506     if (!D)
22507       continue;
22508 
22509     // Check if the declaration in the clause does not show up in any data
22510     // sharing attribute.
22511     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
22512     if (isOpenMPPrivate(DVar.CKind)) {
22513       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
22514           << getOpenMPClauseName(DVar.CKind)
22515           << getOpenMPClauseName(OMPC_has_device_addr)
22516           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
22517       reportOriginalDsa(*this, DSAStack, D, DVar);
22518       continue;
22519     }
22520 
22521     const Expr *ConflictExpr;
22522     if (DSAStack->checkMappableExprComponentListsForDecl(
22523             D, /*CurrentRegionOnly=*/true,
22524             [&ConflictExpr](
22525                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
22526                 OpenMPClauseKind) -> bool {
22527               ConflictExpr = R.front().getAssociatedExpression();
22528               return true;
22529             })) {
22530       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
22531       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
22532           << ConflictExpr->getSourceRange();
22533       continue;
22534     }
22535 
22536     // Store the components in the stack so that they can be used to check
22537     // against other clauses later on.
22538     OMPClauseMappableExprCommon::MappableComponent MC(
22539         SimpleRefExpr, D, /*IsNonContiguous=*/false);
22540     DSAStack->addMappableExpressionComponents(
22541         D, MC, /*WhereFoundClauseKind=*/OMPC_has_device_addr);
22542 
22543     // Record the expression we've just processed.
22544     auto *VD = dyn_cast<VarDecl>(D);
22545     if (!VD && !CurContext->isDependentContext()) {
22546       DeclRefExpr *Ref =
22547           buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
22548       assert(Ref && "has_device_addr capture failed");
22549       MVLI.ProcessedVarList.push_back(Ref);
22550     } else
22551       MVLI.ProcessedVarList.push_back(RefExpr->IgnoreParens());
22552 
22553     // Create a mappable component for the list item. List items in this clause
22554     // only need a component. We use a null declaration to signal fields in
22555     // 'this'.
22556     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
22557             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
22558            "Unexpected device pointer expression!");
22559     MVLI.VarBaseDeclarations.push_back(
22560         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
22561     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
22562     MVLI.VarComponents.back().push_back(MC);
22563   }
22564 
22565   if (MVLI.ProcessedVarList.empty())
22566     return nullptr;
22567 
22568   return OMPHasDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
22569                                         MVLI.VarBaseDeclarations,
22570                                         MVLI.VarComponents);
22571 }
22572 
22573 OMPClause *Sema::ActOnOpenMPAllocateClause(
22574     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
22575     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
22576   if (Allocator) {
22577     // OpenMP [2.11.4 allocate Clause, Description]
22578     // allocator is an expression of omp_allocator_handle_t type.
22579     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
22580       return nullptr;
22581 
22582     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
22583     if (AllocatorRes.isInvalid())
22584       return nullptr;
22585     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
22586                                              DSAStack->getOMPAllocatorHandleT(),
22587                                              Sema::AA_Initializing,
22588                                              /*AllowExplicit=*/true);
22589     if (AllocatorRes.isInvalid())
22590       return nullptr;
22591     Allocator = AllocatorRes.get();
22592   } else {
22593     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
22594     // allocate clauses that appear on a target construct or on constructs in a
22595     // target region must specify an allocator expression unless a requires
22596     // directive with the dynamic_allocators clause is present in the same
22597     // compilation unit.
22598     if (LangOpts.OpenMPIsDevice &&
22599         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
22600       targetDiag(StartLoc, diag::err_expected_allocator_expression);
22601   }
22602   // Analyze and build list of variables.
22603   SmallVector<Expr *, 8> Vars;
22604   for (Expr *RefExpr : VarList) {
22605     assert(RefExpr && "NULL expr in OpenMP private clause.");
22606     SourceLocation ELoc;
22607     SourceRange ERange;
22608     Expr *SimpleRefExpr = RefExpr;
22609     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22610     if (Res.second) {
22611       // It will be analyzed later.
22612       Vars.push_back(RefExpr);
22613     }
22614     ValueDecl *D = Res.first;
22615     if (!D)
22616       continue;
22617 
22618     auto *VD = dyn_cast<VarDecl>(D);
22619     DeclRefExpr *Ref = nullptr;
22620     if (!VD && !CurContext->isDependentContext())
22621       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
22622     Vars.push_back((VD || CurContext->isDependentContext())
22623                        ? RefExpr->IgnoreParens()
22624                        : Ref);
22625   }
22626 
22627   if (Vars.empty())
22628     return nullptr;
22629 
22630   if (Allocator)
22631     DSAStack->addInnerAllocatorExpr(Allocator);
22632   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
22633                                    ColonLoc, EndLoc, Vars);
22634 }
22635 
22636 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
22637                                               SourceLocation StartLoc,
22638                                               SourceLocation LParenLoc,
22639                                               SourceLocation EndLoc) {
22640   SmallVector<Expr *, 8> Vars;
22641   for (Expr *RefExpr : VarList) {
22642     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
22643     SourceLocation ELoc;
22644     SourceRange ERange;
22645     Expr *SimpleRefExpr = RefExpr;
22646     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
22647     if (Res.second)
22648       // It will be analyzed later.
22649       Vars.push_back(RefExpr);
22650     ValueDecl *D = Res.first;
22651     if (!D)
22652       continue;
22653 
22654     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
22655     // A list-item cannot appear in more than one nontemporal clause.
22656     if (const Expr *PrevRef =
22657             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
22658       Diag(ELoc, diag::err_omp_used_in_clause_twice)
22659           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
22660       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
22661           << getOpenMPClauseName(OMPC_nontemporal);
22662       continue;
22663     }
22664 
22665     Vars.push_back(RefExpr);
22666   }
22667 
22668   if (Vars.empty())
22669     return nullptr;
22670 
22671   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
22672                                       Vars);
22673 }
22674 
22675 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
22676                                             SourceLocation StartLoc,
22677                                             SourceLocation LParenLoc,
22678                                             SourceLocation EndLoc) {
22679   SmallVector<Expr *, 8> Vars;
22680   for (Expr *RefExpr : VarList) {
22681     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
22682     SourceLocation ELoc;
22683     SourceRange ERange;
22684     Expr *SimpleRefExpr = RefExpr;
22685     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22686                               /*AllowArraySection=*/true);
22687     if (Res.second)
22688       // It will be analyzed later.
22689       Vars.push_back(RefExpr);
22690     ValueDecl *D = Res.first;
22691     if (!D)
22692       continue;
22693 
22694     const DSAStackTy::DSAVarData DVar =
22695         DSAStack->getTopDSA(D, /*FromParent=*/true);
22696     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
22697     // A list item that appears in the inclusive or exclusive clause must appear
22698     // in a reduction clause with the inscan modifier on the enclosing
22699     // worksharing-loop, worksharing-loop SIMD, or simd construct.
22700     if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
22701       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
22702           << RefExpr->getSourceRange();
22703 
22704     if (DSAStack->getParentDirective() != OMPD_unknown)
22705       DSAStack->markDeclAsUsedInScanDirective(D);
22706     Vars.push_back(RefExpr);
22707   }
22708 
22709   if (Vars.empty())
22710     return nullptr;
22711 
22712   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
22713 }
22714 
22715 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
22716                                             SourceLocation StartLoc,
22717                                             SourceLocation LParenLoc,
22718                                             SourceLocation EndLoc) {
22719   SmallVector<Expr *, 8> Vars;
22720   for (Expr *RefExpr : VarList) {
22721     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
22722     SourceLocation ELoc;
22723     SourceRange ERange;
22724     Expr *SimpleRefExpr = RefExpr;
22725     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
22726                               /*AllowArraySection=*/true);
22727     if (Res.second)
22728       // It will be analyzed later.
22729       Vars.push_back(RefExpr);
22730     ValueDecl *D = Res.first;
22731     if (!D)
22732       continue;
22733 
22734     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
22735     DSAStackTy::DSAVarData DVar;
22736     if (ParentDirective != OMPD_unknown)
22737       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
22738     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
22739     // A list item that appears in the inclusive or exclusive clause must appear
22740     // in a reduction clause with the inscan modifier on the enclosing
22741     // worksharing-loop, worksharing-loop SIMD, or simd construct.
22742     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
22743         DVar.Modifier != OMPC_REDUCTION_inscan) {
22744       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
22745           << RefExpr->getSourceRange();
22746     } else {
22747       DSAStack->markDeclAsUsedInScanDirective(D);
22748     }
22749     Vars.push_back(RefExpr);
22750   }
22751 
22752   if (Vars.empty())
22753     return nullptr;
22754 
22755   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
22756 }
22757 
22758 /// Tries to find omp_alloctrait_t type.
22759 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
22760   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
22761   if (!OMPAlloctraitT.isNull())
22762     return true;
22763   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
22764   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
22765   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
22766     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
22767     return false;
22768   }
22769   Stack->setOMPAlloctraitT(PT.get());
22770   return true;
22771 }
22772 
22773 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
22774     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
22775     ArrayRef<UsesAllocatorsData> Data) {
22776   // OpenMP [2.12.5, target Construct]
22777   // allocator is an identifier of omp_allocator_handle_t type.
22778   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
22779     return nullptr;
22780   // OpenMP [2.12.5, target Construct]
22781   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
22782   if (llvm::any_of(
22783           Data,
22784           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
22785       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
22786     return nullptr;
22787   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
22788   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
22789     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
22790     StringRef Allocator =
22791         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
22792     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
22793     PredefinedAllocators.insert(LookupSingleName(
22794         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
22795   }
22796 
22797   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
22798   for (const UsesAllocatorsData &D : Data) {
22799     Expr *AllocatorExpr = nullptr;
22800     // Check allocator expression.
22801     if (D.Allocator->isTypeDependent()) {
22802       AllocatorExpr = D.Allocator;
22803     } else {
22804       // Traits were specified - need to assign new allocator to the specified
22805       // allocator, so it must be an lvalue.
22806       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
22807       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
22808       bool IsPredefinedAllocator = false;
22809       if (DRE)
22810         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
22811       if (!DRE ||
22812           !(Context.hasSameUnqualifiedType(
22813                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
22814             Context.typesAreCompatible(AllocatorExpr->getType(),
22815                                        DSAStack->getOMPAllocatorHandleT(),
22816                                        /*CompareUnqualified=*/true)) ||
22817           (!IsPredefinedAllocator &&
22818            (AllocatorExpr->getType().isConstant(Context) ||
22819             !AllocatorExpr->isLValue()))) {
22820         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
22821             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
22822             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
22823         continue;
22824       }
22825       // OpenMP [2.12.5, target Construct]
22826       // Predefined allocators appearing in a uses_allocators clause cannot have
22827       // traits specified.
22828       if (IsPredefinedAllocator && D.AllocatorTraits) {
22829         Diag(D.AllocatorTraits->getExprLoc(),
22830              diag::err_omp_predefined_allocator_with_traits)
22831             << D.AllocatorTraits->getSourceRange();
22832         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
22833             << cast<NamedDecl>(DRE->getDecl())->getName()
22834             << D.Allocator->getSourceRange();
22835         continue;
22836       }
22837       // OpenMP [2.12.5, target Construct]
22838       // Non-predefined allocators appearing in a uses_allocators clause must
22839       // have traits specified.
22840       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
22841         Diag(D.Allocator->getExprLoc(),
22842              diag::err_omp_nonpredefined_allocator_without_traits);
22843         continue;
22844       }
22845       // No allocator traits - just convert it to rvalue.
22846       if (!D.AllocatorTraits)
22847         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
22848       DSAStack->addUsesAllocatorsDecl(
22849           DRE->getDecl(),
22850           IsPredefinedAllocator
22851               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
22852               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
22853     }
22854     Expr *AllocatorTraitsExpr = nullptr;
22855     if (D.AllocatorTraits) {
22856       if (D.AllocatorTraits->isTypeDependent()) {
22857         AllocatorTraitsExpr = D.AllocatorTraits;
22858       } else {
22859         // OpenMP [2.12.5, target Construct]
22860         // Arrays that contain allocator traits that appear in a uses_allocators
22861         // clause must be constant arrays, have constant values and be defined
22862         // in the same scope as the construct in which the clause appears.
22863         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
22864         // Check that traits expr is a constant array.
22865         QualType TraitTy;
22866         if (const ArrayType *Ty =
22867                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
22868           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
22869             TraitTy = ConstArrayTy->getElementType();
22870         if (TraitTy.isNull() ||
22871             !(Context.hasSameUnqualifiedType(TraitTy,
22872                                              DSAStack->getOMPAlloctraitT()) ||
22873               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
22874                                          /*CompareUnqualified=*/true))) {
22875           Diag(D.AllocatorTraits->getExprLoc(),
22876                diag::err_omp_expected_array_alloctraits)
22877               << AllocatorTraitsExpr->getType();
22878           continue;
22879         }
22880         // Do not map by default allocator traits if it is a standalone
22881         // variable.
22882         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
22883           DSAStack->addUsesAllocatorsDecl(
22884               DRE->getDecl(),
22885               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
22886       }
22887     }
22888     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
22889     NewD.Allocator = AllocatorExpr;
22890     NewD.AllocatorTraits = AllocatorTraitsExpr;
22891     NewD.LParenLoc = D.LParenLoc;
22892     NewD.RParenLoc = D.RParenLoc;
22893   }
22894   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
22895                                          NewData);
22896 }
22897 
22898 OMPClause *Sema::ActOnOpenMPAffinityClause(
22899     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
22900     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
22901   SmallVector<Expr *, 8> Vars;
22902   for (Expr *RefExpr : Locators) {
22903     assert(RefExpr && "NULL expr in OpenMP shared clause.");
22904     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
22905       // It will be analyzed later.
22906       Vars.push_back(RefExpr);
22907       continue;
22908     }
22909 
22910     SourceLocation ELoc = RefExpr->getExprLoc();
22911     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
22912 
22913     if (!SimpleExpr->isLValue()) {
22914       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
22915           << 1 << 0 << RefExpr->getSourceRange();
22916       continue;
22917     }
22918 
22919     ExprResult Res;
22920     {
22921       Sema::TentativeAnalysisScope Trap(*this);
22922       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
22923     }
22924     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
22925         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
22926       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
22927           << 1 << 0 << RefExpr->getSourceRange();
22928       continue;
22929     }
22930     Vars.push_back(SimpleExpr);
22931   }
22932 
22933   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
22934                                    EndLoc, Modifier, Vars);
22935 }
22936 
22937 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
22938                                        SourceLocation KindLoc,
22939                                        SourceLocation StartLoc,
22940                                        SourceLocation LParenLoc,
22941                                        SourceLocation EndLoc) {
22942   if (Kind == OMPC_BIND_unknown) {
22943     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
22944         << getListOfPossibleValues(OMPC_bind, /*First=*/0,
22945                                    /*Last=*/unsigned(OMPC_BIND_unknown))
22946         << getOpenMPClauseName(OMPC_bind);
22947     return nullptr;
22948   }
22949 
22950   return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
22951                                EndLoc);
22952 }
22953