1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements semantic analysis for OpenMP directives and
10 /// clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/OpenMPClause.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/DiagnosticSema.h"
27 #include "clang/Basic/OpenMPKinds.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/PointerEmbeddedInt.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Frontend/OpenMP/OMPAssume.h"
40 #include "llvm/Frontend/OpenMP/OMPConstants.h"
41 #include <set>
42 
43 using namespace clang;
44 using namespace llvm::omp;
45 
46 //===----------------------------------------------------------------------===//
47 // Stack of data-sharing attributes for variables
48 //===----------------------------------------------------------------------===//
49 
50 static const Expr *checkMapClauseExpressionBase(
51     Sema &SemaRef, Expr *E,
52     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
53     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
54 
55 namespace {
56 /// Default data sharing attributes, which can be applied to directive.
57 enum DefaultDataSharingAttributes {
58   DSA_unspecified = 0,       /// Data sharing attribute not specified.
59   DSA_none = 1 << 0,         /// Default data sharing attribute 'none'.
60   DSA_shared = 1 << 1,       /// Default data sharing attribute 'shared'.
61   DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
62 };
63 
64 /// Stack for tracking declarations used in OpenMP directives and
65 /// clauses and their data-sharing attributes.
66 class DSAStackTy {
67 public:
68   struct DSAVarData {
69     OpenMPDirectiveKind DKind = OMPD_unknown;
70     OpenMPClauseKind CKind = OMPC_unknown;
71     unsigned Modifier = 0;
72     const Expr *RefExpr = nullptr;
73     DeclRefExpr *PrivateCopy = nullptr;
74     SourceLocation ImplicitDSALoc;
75     bool AppliedToPointee = false;
76     DSAVarData() = default;
77     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
78                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
79                SourceLocation ImplicitDSALoc, unsigned Modifier,
80                bool AppliedToPointee)
81         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
82           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
83           AppliedToPointee(AppliedToPointee) {}
84   };
85   using OperatorOffsetTy =
86       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
87   using DoacrossDependMapTy =
88       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
89   /// Kind of the declaration used in the uses_allocators clauses.
90   enum class UsesAllocatorsDeclKind {
91     /// Predefined allocator
92     PredefinedAllocator,
93     /// User-defined allocator
94     UserDefinedAllocator,
95     /// The declaration that represent allocator trait
96     AllocatorTrait,
97   };
98 
99 private:
100   struct DSAInfo {
101     OpenMPClauseKind Attributes = OMPC_unknown;
102     unsigned Modifier = 0;
103     /// Pointer to a reference expression and a flag which shows that the
104     /// variable is marked as lastprivate(true) or not (false).
105     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
106     DeclRefExpr *PrivateCopy = nullptr;
107     /// true if the attribute is applied to the pointee, not the variable
108     /// itself.
109     bool AppliedToPointee = false;
110   };
111   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
112   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
113   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
114   using LoopControlVariablesMapTy =
115       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
116   /// Struct that associates a component with the clause kind where they are
117   /// found.
118   struct MappedExprComponentTy {
119     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
120     OpenMPClauseKind Kind = OMPC_unknown;
121   };
122   using MappedExprComponentsTy =
123       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
124   using CriticalsWithHintsTy =
125       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
126   struct ReductionData {
127     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
128     SourceRange ReductionRange;
129     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
130     ReductionData() = default;
131     void set(BinaryOperatorKind BO, SourceRange RR) {
132       ReductionRange = RR;
133       ReductionOp = BO;
134     }
135     void set(const Expr *RefExpr, SourceRange RR) {
136       ReductionRange = RR;
137       ReductionOp = RefExpr;
138     }
139   };
140   using DeclReductionMapTy =
141       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
142   struct DefaultmapInfo {
143     OpenMPDefaultmapClauseModifier ImplicitBehavior =
144         OMPC_DEFAULTMAP_MODIFIER_unknown;
145     SourceLocation SLoc;
146     DefaultmapInfo() = default;
147     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
148         : ImplicitBehavior(M), SLoc(Loc) {}
149   };
150 
151   struct SharingMapTy {
152     DeclSAMapTy SharingMap;
153     DeclReductionMapTy ReductionMap;
154     UsedRefMapTy AlignedMap;
155     UsedRefMapTy NontemporalMap;
156     MappedExprComponentsTy MappedExprComponents;
157     LoopControlVariablesMapTy LCVMap;
158     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
159     SourceLocation DefaultAttrLoc;
160     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
161     OpenMPDirectiveKind Directive = OMPD_unknown;
162     DeclarationNameInfo DirectiveName;
163     Scope *CurScope = nullptr;
164     DeclContext *Context = nullptr;
165     SourceLocation ConstructLoc;
166     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
167     /// get the data (loop counters etc.) about enclosing loop-based construct.
168     /// This data is required during codegen.
169     DoacrossDependMapTy DoacrossDepends;
170     /// First argument (Expr *) contains optional argument of the
171     /// 'ordered' clause, the second one is true if the regions has 'ordered'
172     /// clause, false otherwise.
173     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
174     unsigned AssociatedLoops = 1;
175     bool HasMutipleLoops = false;
176     const Decl *PossiblyLoopCounter = nullptr;
177     bool NowaitRegion = false;
178     bool CancelRegion = false;
179     bool LoopStart = false;
180     bool BodyComplete = false;
181     SourceLocation PrevScanLocation;
182     SourceLocation PrevOrderedLocation;
183     SourceLocation InnerTeamsRegionLoc;
184     /// Reference to the taskgroup task_reduction reference expression.
185     Expr *TaskgroupReductionRef = nullptr;
186     llvm::DenseSet<QualType> MappedClassesQualTypes;
187     SmallVector<Expr *, 4> InnerUsedAllocators;
188     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
189     /// List of globals marked as declare target link in this target region
190     /// (isOpenMPTargetExecutionDirective(Directive) == true).
191     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
192     /// List of decls used in inclusive/exclusive clauses of the scan directive.
193     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
194     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
195         UsesAllocatorsDecls;
196     Expr *DeclareMapperVar = nullptr;
197     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
198                  Scope *CurScope, SourceLocation Loc)
199         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
200           ConstructLoc(Loc) {}
201     SharingMapTy() = default;
202   };
203 
204   using StackTy = SmallVector<SharingMapTy, 4>;
205 
206   /// Stack of used declaration and their data-sharing attributes.
207   DeclSAMapTy Threadprivates;
208   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
209   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
210   /// true, if check for DSA must be from parent directive, false, if
211   /// from current directive.
212   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
213   Sema &SemaRef;
214   bool ForceCapturing = false;
215   /// true if all the variables in the target executable directives must be
216   /// captured by reference.
217   bool ForceCaptureByReferenceInTargetExecutable = false;
218   CriticalsWithHintsTy Criticals;
219   unsigned IgnoredStackElements = 0;
220 
221   /// Iterators over the stack iterate in order from innermost to outermost
222   /// directive.
223   using const_iterator = StackTy::const_reverse_iterator;
224   const_iterator begin() const {
225     return Stack.empty() ? const_iterator()
226                          : Stack.back().first.rbegin() + IgnoredStackElements;
227   }
228   const_iterator end() const {
229     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
230   }
231   using iterator = StackTy::reverse_iterator;
232   iterator begin() {
233     return Stack.empty() ? iterator()
234                          : Stack.back().first.rbegin() + IgnoredStackElements;
235   }
236   iterator end() {
237     return Stack.empty() ? iterator() : Stack.back().first.rend();
238   }
239 
240   // Convenience operations to get at the elements of the stack.
241 
242   bool isStackEmpty() const {
243     return Stack.empty() ||
244            Stack.back().second != CurrentNonCapturingFunctionScope ||
245            Stack.back().first.size() <= IgnoredStackElements;
246   }
247   size_t getStackSize() const {
248     return isStackEmpty() ? 0
249                           : Stack.back().first.size() - IgnoredStackElements;
250   }
251 
252   SharingMapTy *getTopOfStackOrNull() {
253     size_t Size = getStackSize();
254     if (Size == 0)
255       return nullptr;
256     return &Stack.back().first[Size - 1];
257   }
258   const SharingMapTy *getTopOfStackOrNull() const {
259     return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
260   }
261   SharingMapTy &getTopOfStack() {
262     assert(!isStackEmpty() && "no current directive");
263     return *getTopOfStackOrNull();
264   }
265   const SharingMapTy &getTopOfStack() const {
266     return const_cast<DSAStackTy &>(*this).getTopOfStack();
267   }
268 
269   SharingMapTy *getSecondOnStackOrNull() {
270     size_t Size = getStackSize();
271     if (Size <= 1)
272       return nullptr;
273     return &Stack.back().first[Size - 2];
274   }
275   const SharingMapTy *getSecondOnStackOrNull() const {
276     return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
277   }
278 
279   /// Get the stack element at a certain level (previously returned by
280   /// \c getNestingLevel).
281   ///
282   /// Note that nesting levels count from outermost to innermost, and this is
283   /// the reverse of our iteration order where new inner levels are pushed at
284   /// the front of the stack.
285   SharingMapTy &getStackElemAtLevel(unsigned Level) {
286     assert(Level < getStackSize() && "no such stack element");
287     return Stack.back().first[Level];
288   }
289   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
290     return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
291   }
292 
293   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
294 
295   /// Checks if the variable is a local for OpenMP region.
296   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
297 
298   /// Vector of previously declared requires directives
299   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
300   /// omp_allocator_handle_t type.
301   QualType OMPAllocatorHandleT;
302   /// omp_depend_t type.
303   QualType OMPDependT;
304   /// omp_event_handle_t type.
305   QualType OMPEventHandleT;
306   /// omp_alloctrait_t type.
307   QualType OMPAlloctraitT;
308   /// Expression for the predefined allocators.
309   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
310       nullptr};
311   /// Vector of previously encountered target directives
312   SmallVector<SourceLocation, 2> TargetLocations;
313   SourceLocation AtomicLocation;
314   /// Vector of declare variant construct traits.
315   SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
316 
317 public:
318   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
319 
320   /// Sets omp_allocator_handle_t type.
321   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
322   /// Gets omp_allocator_handle_t type.
323   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
324   /// Sets omp_alloctrait_t type.
325   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
326   /// Gets omp_alloctrait_t type.
327   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
328   /// Sets the given default allocator.
329   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
330                     Expr *Allocator) {
331     OMPPredefinedAllocators[AllocatorKind] = Allocator;
332   }
333   /// Returns the specified default allocator.
334   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
335     return OMPPredefinedAllocators[AllocatorKind];
336   }
337   /// Sets omp_depend_t type.
338   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
339   /// Gets omp_depend_t type.
340   QualType getOMPDependT() const { return OMPDependT; }
341 
342   /// Sets omp_event_handle_t type.
343   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
344   /// Gets omp_event_handle_t type.
345   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
346 
347   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
348   OpenMPClauseKind getClauseParsingMode() const {
349     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
350     return ClauseKindMode;
351   }
352   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
353 
354   bool isBodyComplete() const {
355     const SharingMapTy *Top = getTopOfStackOrNull();
356     return Top && Top->BodyComplete;
357   }
358   void setBodyComplete() { getTopOfStack().BodyComplete = true; }
359 
360   bool isForceVarCapturing() const { return ForceCapturing; }
361   void setForceVarCapturing(bool V) { ForceCapturing = V; }
362 
363   void setForceCaptureByReferenceInTargetExecutable(bool V) {
364     ForceCaptureByReferenceInTargetExecutable = V;
365   }
366   bool isForceCaptureByReferenceInTargetExecutable() const {
367     return ForceCaptureByReferenceInTargetExecutable;
368   }
369 
370   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
371             Scope *CurScope, SourceLocation Loc) {
372     assert(!IgnoredStackElements &&
373            "cannot change stack while ignoring elements");
374     if (Stack.empty() ||
375         Stack.back().second != CurrentNonCapturingFunctionScope)
376       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
377     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
378     Stack.back().first.back().DefaultAttrLoc = Loc;
379   }
380 
381   void pop() {
382     assert(!IgnoredStackElements &&
383            "cannot change stack while ignoring elements");
384     assert(!Stack.back().first.empty() &&
385            "Data-sharing attributes stack is empty!");
386     Stack.back().first.pop_back();
387   }
388 
389   /// RAII object to temporarily leave the scope of a directive when we want to
390   /// logically operate in its parent.
391   class ParentDirectiveScope {
392     DSAStackTy &Self;
393     bool Active;
394 
395   public:
396     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
397         : Self(Self), Active(false) {
398       if (Activate)
399         enable();
400     }
401     ~ParentDirectiveScope() { disable(); }
402     void disable() {
403       if (Active) {
404         --Self.IgnoredStackElements;
405         Active = false;
406       }
407     }
408     void enable() {
409       if (!Active) {
410         ++Self.IgnoredStackElements;
411         Active = true;
412       }
413     }
414   };
415 
416   /// Marks that we're started loop parsing.
417   void loopInit() {
418     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
419            "Expected loop-based directive.");
420     getTopOfStack().LoopStart = true;
421   }
422   /// Start capturing of the variables in the loop context.
423   void loopStart() {
424     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
425            "Expected loop-based directive.");
426     getTopOfStack().LoopStart = false;
427   }
428   /// true, if variables are captured, false otherwise.
429   bool isLoopStarted() const {
430     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
431            "Expected loop-based directive.");
432     return !getTopOfStack().LoopStart;
433   }
434   /// Marks (or clears) declaration as possibly loop counter.
435   void resetPossibleLoopCounter(const Decl *D = nullptr) {
436     getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
437   }
438   /// Gets the possible loop counter decl.
439   const Decl *getPossiblyLoopCunter() const {
440     return getTopOfStack().PossiblyLoopCounter;
441   }
442   /// Start new OpenMP region stack in new non-capturing function.
443   void pushFunction() {
444     assert(!IgnoredStackElements &&
445            "cannot change stack while ignoring elements");
446     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
447     assert(!isa<CapturingScopeInfo>(CurFnScope));
448     CurrentNonCapturingFunctionScope = CurFnScope;
449   }
450   /// Pop region stack for non-capturing function.
451   void popFunction(const FunctionScopeInfo *OldFSI) {
452     assert(!IgnoredStackElements &&
453            "cannot change stack while ignoring elements");
454     if (!Stack.empty() && Stack.back().second == OldFSI) {
455       assert(Stack.back().first.empty());
456       Stack.pop_back();
457     }
458     CurrentNonCapturingFunctionScope = nullptr;
459     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
460       if (!isa<CapturingScopeInfo>(FSI)) {
461         CurrentNonCapturingFunctionScope = FSI;
462         break;
463       }
464     }
465   }
466 
467   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
468     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
469   }
470   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
471   getCriticalWithHint(const DeclarationNameInfo &Name) const {
472     auto I = Criticals.find(Name.getAsString());
473     if (I != Criticals.end())
474       return I->second;
475     return std::make_pair(nullptr, llvm::APSInt());
476   }
477   /// If 'aligned' declaration for given variable \a D was not seen yet,
478   /// add it and return NULL; otherwise return previous occurrence's expression
479   /// for diagnostics.
480   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
481   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
482   /// add it and return NULL; otherwise return previous occurrence's expression
483   /// for diagnostics.
484   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
485 
486   /// Register specified variable as loop control variable.
487   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
488   /// Check if the specified variable is a loop control variable for
489   /// current region.
490   /// \return The index of the loop control variable in the list of associated
491   /// for-loops (from outer to inner).
492   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
493   /// Check if the specified variable is a loop control variable for
494   /// parent region.
495   /// \return The index of the loop control variable in the list of associated
496   /// for-loops (from outer to inner).
497   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
498   /// Check if the specified variable is a loop control variable for
499   /// current region.
500   /// \return The index of the loop control variable in the list of associated
501   /// for-loops (from outer to inner).
502   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
503                                          unsigned Level) const;
504   /// Get the loop control variable for the I-th loop (or nullptr) in
505   /// parent directive.
506   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
507 
508   /// Marks the specified decl \p D as used in scan directive.
509   void markDeclAsUsedInScanDirective(ValueDecl *D) {
510     if (SharingMapTy *Stack = getSecondOnStackOrNull())
511       Stack->UsedInScanDirective.insert(D);
512   }
513 
514   /// Checks if the specified declaration was used in the inner scan directive.
515   bool isUsedInScanDirective(ValueDecl *D) const {
516     if (const SharingMapTy *Stack = getTopOfStackOrNull())
517       return Stack->UsedInScanDirective.contains(D);
518     return false;
519   }
520 
521   /// Adds explicit data sharing attribute to the specified declaration.
522   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
523               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
524               bool AppliedToPointee = false);
525 
526   /// Adds additional information for the reduction items with the reduction id
527   /// represented as an operator.
528   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
529                                  BinaryOperatorKind BOK);
530   /// Adds additional information for the reduction items with the reduction id
531   /// represented as reduction identifier.
532   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
533                                  const Expr *ReductionRef);
534   /// Returns the location and reduction operation from the innermost parent
535   /// region for the given \p D.
536   const DSAVarData
537   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
538                                    BinaryOperatorKind &BOK,
539                                    Expr *&TaskgroupDescriptor) const;
540   /// Returns the location and reduction operation from the innermost parent
541   /// region for the given \p D.
542   const DSAVarData
543   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
544                                    const Expr *&ReductionRef,
545                                    Expr *&TaskgroupDescriptor) const;
546   /// Return reduction reference expression for the current taskgroup or
547   /// parallel/worksharing directives with task reductions.
548   Expr *getTaskgroupReductionRef() const {
549     assert((getTopOfStack().Directive == OMPD_taskgroup ||
550             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
551               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
552              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
553            "taskgroup reference expression requested for non taskgroup or "
554            "parallel/worksharing directive.");
555     return getTopOfStack().TaskgroupReductionRef;
556   }
557   /// Checks if the given \p VD declaration is actually a taskgroup reduction
558   /// descriptor variable at the \p Level of OpenMP regions.
559   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
560     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
561            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
562                    ->getDecl() == VD;
563   }
564 
565   /// Returns data sharing attributes from top of the stack for the
566   /// specified declaration.
567   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
568   /// Returns data-sharing attributes for the specified declaration.
569   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
570   /// Returns data-sharing attributes for the specified declaration.
571   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
572   /// Checks if the specified variables has data-sharing attributes which
573   /// match specified \a CPred predicate in any directive which matches \a DPred
574   /// predicate.
575   const DSAVarData
576   hasDSA(ValueDecl *D,
577          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
578          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
579          bool FromParent) const;
580   /// Checks if the specified variables has data-sharing attributes which
581   /// match specified \a CPred predicate in any innermost directive which
582   /// matches \a DPred predicate.
583   const DSAVarData
584   hasInnermostDSA(ValueDecl *D,
585                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
586                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
587                   bool FromParent) const;
588   /// Checks if the specified variables has explicit data-sharing
589   /// attributes which match specified \a CPred predicate at the specified
590   /// OpenMP region.
591   bool
592   hasExplicitDSA(const ValueDecl *D,
593                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
594                  unsigned Level, bool NotLastprivate = false) const;
595 
596   /// Returns true if the directive at level \Level matches in the
597   /// specified \a DPred predicate.
598   bool hasExplicitDirective(
599       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
600       unsigned Level) const;
601 
602   /// Finds a directive which matches specified \a DPred predicate.
603   bool hasDirective(
604       const llvm::function_ref<bool(
605           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
606           DPred,
607       bool FromParent) const;
608 
609   /// Returns currently analyzed directive.
610   OpenMPDirectiveKind getCurrentDirective() const {
611     const SharingMapTy *Top = getTopOfStackOrNull();
612     return Top ? Top->Directive : OMPD_unknown;
613   }
614   /// Returns directive kind at specified level.
615   OpenMPDirectiveKind getDirective(unsigned Level) const {
616     assert(!isStackEmpty() && "No directive at specified level.");
617     return getStackElemAtLevel(Level).Directive;
618   }
619   /// Returns the capture region at the specified level.
620   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
621                                        unsigned OpenMPCaptureLevel) const {
622     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
623     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
624     return CaptureRegions[OpenMPCaptureLevel];
625   }
626   /// Returns parent directive.
627   OpenMPDirectiveKind getParentDirective() const {
628     const SharingMapTy *Parent = getSecondOnStackOrNull();
629     return Parent ? Parent->Directive : OMPD_unknown;
630   }
631 
632   /// Add requires decl to internal vector
633   void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
634 
635   /// Checks if the defined 'requires' directive has specified type of clause.
636   template <typename ClauseType> bool hasRequiresDeclWithClause() const {
637     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
638       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
639         return isa<ClauseType>(C);
640       });
641     });
642   }
643 
644   /// Checks for a duplicate clause amongst previously declared requires
645   /// directives
646   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
647     bool IsDuplicate = false;
648     for (OMPClause *CNew : ClauseList) {
649       for (const OMPRequiresDecl *D : RequiresDecls) {
650         for (const OMPClause *CPrev : D->clauselists()) {
651           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
652             SemaRef.Diag(CNew->getBeginLoc(),
653                          diag::err_omp_requires_clause_redeclaration)
654                 << getOpenMPClauseName(CNew->getClauseKind());
655             SemaRef.Diag(CPrev->getBeginLoc(),
656                          diag::note_omp_requires_previous_clause)
657                 << getOpenMPClauseName(CPrev->getClauseKind());
658             IsDuplicate = true;
659           }
660         }
661       }
662     }
663     return IsDuplicate;
664   }
665 
666   /// Add location of previously encountered target to internal vector
667   void addTargetDirLocation(SourceLocation LocStart) {
668     TargetLocations.push_back(LocStart);
669   }
670 
671   /// Add location for the first encountered atomicc directive.
672   void addAtomicDirectiveLoc(SourceLocation Loc) {
673     if (AtomicLocation.isInvalid())
674       AtomicLocation = Loc;
675   }
676 
677   /// Returns the location of the first encountered atomic directive in the
678   /// module.
679   SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
680 
681   // Return previously encountered target region locations.
682   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
683     return TargetLocations;
684   }
685 
686   /// Set default data sharing attribute to none.
687   void setDefaultDSANone(SourceLocation Loc) {
688     getTopOfStack().DefaultAttr = DSA_none;
689     getTopOfStack().DefaultAttrLoc = Loc;
690   }
691   /// Set default data sharing attribute to shared.
692   void setDefaultDSAShared(SourceLocation Loc) {
693     getTopOfStack().DefaultAttr = DSA_shared;
694     getTopOfStack().DefaultAttrLoc = Loc;
695   }
696   /// Set default data sharing attribute to firstprivate.
697   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
698     getTopOfStack().DefaultAttr = DSA_firstprivate;
699     getTopOfStack().DefaultAttrLoc = Loc;
700   }
701   /// Set default data mapping attribute to Modifier:Kind
702   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
703                          OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
704     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
705     DMI.ImplicitBehavior = M;
706     DMI.SLoc = Loc;
707   }
708   /// Check whether the implicit-behavior has been set in defaultmap
709   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
710     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
711       return getTopOfStack()
712                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
713                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
714              getTopOfStack()
715                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
716                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
717              getTopOfStack()
718                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
719                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
720     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
721            OMPC_DEFAULTMAP_MODIFIER_unknown;
722   }
723 
724   ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
725     return ConstructTraits;
726   }
727   void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
728                             bool ScopeEntry) {
729     if (ScopeEntry)
730       ConstructTraits.append(Traits.begin(), Traits.end());
731     else
732       for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
733         llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
734         assert(Top == Trait && "Something left a trait on the stack!");
735         (void)Trait;
736         (void)Top;
737       }
738   }
739 
740   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
741     return getStackSize() <= Level ? DSA_unspecified
742                                    : getStackElemAtLevel(Level).DefaultAttr;
743   }
744   DefaultDataSharingAttributes getDefaultDSA() const {
745     return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
746   }
747   SourceLocation getDefaultDSALocation() const {
748     return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
749   }
750   OpenMPDefaultmapClauseModifier
751   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
752     return isStackEmpty()
753                ? OMPC_DEFAULTMAP_MODIFIER_unknown
754                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
755   }
756   OpenMPDefaultmapClauseModifier
757   getDefaultmapModifierAtLevel(unsigned Level,
758                                OpenMPDefaultmapClauseKind Kind) const {
759     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
760   }
761   bool isDefaultmapCapturedByRef(unsigned Level,
762                                  OpenMPDefaultmapClauseKind Kind) const {
763     OpenMPDefaultmapClauseModifier M =
764         getDefaultmapModifierAtLevel(Level, Kind);
765     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
766       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
767              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
768              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
769              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
770     }
771     return true;
772   }
773   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
774                                      OpenMPDefaultmapClauseKind Kind) {
775     switch (Kind) {
776     case OMPC_DEFAULTMAP_scalar:
777     case OMPC_DEFAULTMAP_pointer:
778       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
779              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
780              (M == OMPC_DEFAULTMAP_MODIFIER_default);
781     case OMPC_DEFAULTMAP_aggregate:
782       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
783     default:
784       break;
785     }
786     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
787   }
788   bool mustBeFirstprivateAtLevel(unsigned Level,
789                                  OpenMPDefaultmapClauseKind Kind) const {
790     OpenMPDefaultmapClauseModifier M =
791         getDefaultmapModifierAtLevel(Level, Kind);
792     return mustBeFirstprivateBase(M, Kind);
793   }
794   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
795     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
796     return mustBeFirstprivateBase(M, Kind);
797   }
798 
799   /// Checks if the specified variable is a threadprivate.
800   bool isThreadPrivate(VarDecl *D) {
801     const DSAVarData DVar = getTopDSA(D, false);
802     return isOpenMPThreadPrivate(DVar.CKind);
803   }
804 
805   /// Marks current region as ordered (it has an 'ordered' clause).
806   void setOrderedRegion(bool IsOrdered, const Expr *Param,
807                         OMPOrderedClause *Clause) {
808     if (IsOrdered)
809       getTopOfStack().OrderedRegion.emplace(Param, Clause);
810     else
811       getTopOfStack().OrderedRegion.reset();
812   }
813   /// Returns true, if region is ordered (has associated 'ordered' clause),
814   /// false - otherwise.
815   bool isOrderedRegion() const {
816     if (const SharingMapTy *Top = getTopOfStackOrNull())
817       return Top->OrderedRegion.hasValue();
818     return false;
819   }
820   /// Returns optional parameter for the ordered region.
821   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
822     if (const SharingMapTy *Top = getTopOfStackOrNull())
823       if (Top->OrderedRegion.hasValue())
824         return Top->OrderedRegion.getValue();
825     return std::make_pair(nullptr, nullptr);
826   }
827   /// Returns true, if parent region is ordered (has associated
828   /// 'ordered' clause), false - otherwise.
829   bool isParentOrderedRegion() const {
830     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
831       return Parent->OrderedRegion.hasValue();
832     return false;
833   }
834   /// Returns optional parameter for the ordered region.
835   std::pair<const Expr *, OMPOrderedClause *>
836   getParentOrderedRegionParam() const {
837     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
838       if (Parent->OrderedRegion.hasValue())
839         return Parent->OrderedRegion.getValue();
840     return std::make_pair(nullptr, nullptr);
841   }
842   /// Marks current region as nowait (it has a 'nowait' clause).
843   void setNowaitRegion(bool IsNowait = true) {
844     getTopOfStack().NowaitRegion = IsNowait;
845   }
846   /// Returns true, if parent region is nowait (has associated
847   /// 'nowait' clause), false - otherwise.
848   bool isParentNowaitRegion() const {
849     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
850       return Parent->NowaitRegion;
851     return false;
852   }
853   /// Marks parent region as cancel region.
854   void setParentCancelRegion(bool Cancel = true) {
855     if (SharingMapTy *Parent = getSecondOnStackOrNull())
856       Parent->CancelRegion |= Cancel;
857   }
858   /// Return true if current region has inner cancel construct.
859   bool isCancelRegion() const {
860     const SharingMapTy *Top = getTopOfStackOrNull();
861     return Top ? Top->CancelRegion : false;
862   }
863 
864   /// Mark that parent region already has scan directive.
865   void setParentHasScanDirective(SourceLocation Loc) {
866     if (SharingMapTy *Parent = getSecondOnStackOrNull())
867       Parent->PrevScanLocation = Loc;
868   }
869   /// Return true if current region has inner cancel construct.
870   bool doesParentHasScanDirective() const {
871     const SharingMapTy *Top = getSecondOnStackOrNull();
872     return Top ? Top->PrevScanLocation.isValid() : false;
873   }
874   /// Return true if current region has inner cancel construct.
875   SourceLocation getParentScanDirectiveLoc() const {
876     const SharingMapTy *Top = getSecondOnStackOrNull();
877     return Top ? Top->PrevScanLocation : SourceLocation();
878   }
879   /// Mark that parent region already has ordered directive.
880   void setParentHasOrderedDirective(SourceLocation Loc) {
881     if (SharingMapTy *Parent = getSecondOnStackOrNull())
882       Parent->PrevOrderedLocation = Loc;
883   }
884   /// Return true if current region has inner ordered construct.
885   bool doesParentHasOrderedDirective() const {
886     const SharingMapTy *Top = getSecondOnStackOrNull();
887     return Top ? Top->PrevOrderedLocation.isValid() : false;
888   }
889   /// Returns the location of the previously specified ordered directive.
890   SourceLocation getParentOrderedDirectiveLoc() const {
891     const SharingMapTy *Top = getSecondOnStackOrNull();
892     return Top ? Top->PrevOrderedLocation : SourceLocation();
893   }
894 
895   /// Set collapse value for the region.
896   void setAssociatedLoops(unsigned Val) {
897     getTopOfStack().AssociatedLoops = Val;
898     if (Val > 1)
899       getTopOfStack().HasMutipleLoops = true;
900   }
901   /// Return collapse value for region.
902   unsigned getAssociatedLoops() const {
903     const SharingMapTy *Top = getTopOfStackOrNull();
904     return Top ? Top->AssociatedLoops : 0;
905   }
906   /// Returns true if the construct is associated with multiple loops.
907   bool hasMutipleLoops() const {
908     const SharingMapTy *Top = getTopOfStackOrNull();
909     return Top ? Top->HasMutipleLoops : false;
910   }
911 
912   /// Marks current target region as one with closely nested teams
913   /// region.
914   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
915     if (SharingMapTy *Parent = getSecondOnStackOrNull())
916       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
917   }
918   /// Returns true, if current region has closely nested teams region.
919   bool hasInnerTeamsRegion() const {
920     return getInnerTeamsRegionLoc().isValid();
921   }
922   /// Returns location of the nested teams region (if any).
923   SourceLocation getInnerTeamsRegionLoc() const {
924     const SharingMapTy *Top = getTopOfStackOrNull();
925     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
926   }
927 
928   Scope *getCurScope() const {
929     const SharingMapTy *Top = getTopOfStackOrNull();
930     return Top ? Top->CurScope : nullptr;
931   }
932   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
933   SourceLocation getConstructLoc() const {
934     const SharingMapTy *Top = getTopOfStackOrNull();
935     return Top ? Top->ConstructLoc : SourceLocation();
936   }
937 
938   /// Do the check specified in \a Check to all component lists and return true
939   /// if any issue is found.
940   bool checkMappableExprComponentListsForDecl(
941       const ValueDecl *VD, bool CurrentRegionOnly,
942       const llvm::function_ref<
943           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
944                OpenMPClauseKind)>
945           Check) const {
946     if (isStackEmpty())
947       return false;
948     auto SI = begin();
949     auto SE = end();
950 
951     if (SI == SE)
952       return false;
953 
954     if (CurrentRegionOnly)
955       SE = std::next(SI);
956     else
957       std::advance(SI, 1);
958 
959     for (; SI != SE; ++SI) {
960       auto MI = SI->MappedExprComponents.find(VD);
961       if (MI != SI->MappedExprComponents.end())
962         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
963              MI->second.Components)
964           if (Check(L, MI->second.Kind))
965             return true;
966     }
967     return false;
968   }
969 
970   /// Do the check specified in \a Check to all component lists at a given level
971   /// and return true if any issue is found.
972   bool checkMappableExprComponentListsForDeclAtLevel(
973       const ValueDecl *VD, unsigned Level,
974       const llvm::function_ref<
975           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
976                OpenMPClauseKind)>
977           Check) const {
978     if (getStackSize() <= Level)
979       return false;
980 
981     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
982     auto MI = StackElem.MappedExprComponents.find(VD);
983     if (MI != StackElem.MappedExprComponents.end())
984       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
985            MI->second.Components)
986         if (Check(L, MI->second.Kind))
987           return true;
988     return false;
989   }
990 
991   /// Create a new mappable expression component list associated with a given
992   /// declaration and initialize it with the provided list of components.
993   void addMappableExpressionComponents(
994       const ValueDecl *VD,
995       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
996       OpenMPClauseKind WhereFoundClauseKind) {
997     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
998     // Create new entry and append the new components there.
999     MEC.Components.resize(MEC.Components.size() + 1);
1000     MEC.Components.back().append(Components.begin(), Components.end());
1001     MEC.Kind = WhereFoundClauseKind;
1002   }
1003 
1004   unsigned getNestingLevel() const {
1005     assert(!isStackEmpty());
1006     return getStackSize() - 1;
1007   }
1008   void addDoacrossDependClause(OMPDependClause *C,
1009                                const OperatorOffsetTy &OpsOffs) {
1010     SharingMapTy *Parent = getSecondOnStackOrNull();
1011     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1012     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1013   }
1014   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1015   getDoacrossDependClauses() const {
1016     const SharingMapTy &StackElem = getTopOfStack();
1017     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1018       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1019       return llvm::make_range(Ref.begin(), Ref.end());
1020     }
1021     return llvm::make_range(StackElem.DoacrossDepends.end(),
1022                             StackElem.DoacrossDepends.end());
1023   }
1024 
1025   // Store types of classes which have been explicitly mapped
1026   void addMappedClassesQualTypes(QualType QT) {
1027     SharingMapTy &StackElem = getTopOfStack();
1028     StackElem.MappedClassesQualTypes.insert(QT);
1029   }
1030 
1031   // Return set of mapped classes types
1032   bool isClassPreviouslyMapped(QualType QT) const {
1033     const SharingMapTy &StackElem = getTopOfStack();
1034     return StackElem.MappedClassesQualTypes.contains(QT);
1035   }
1036 
1037   /// Adds global declare target to the parent target region.
1038   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1039     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1040                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1041            "Expected declare target link global.");
1042     for (auto &Elem : *this) {
1043       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1044         Elem.DeclareTargetLinkVarDecls.push_back(E);
1045         return;
1046       }
1047     }
1048   }
1049 
1050   /// Returns the list of globals with declare target link if current directive
1051   /// is target.
1052   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1053     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1054            "Expected target executable directive.");
1055     return getTopOfStack().DeclareTargetLinkVarDecls;
1056   }
1057 
1058   /// Adds list of allocators expressions.
1059   void addInnerAllocatorExpr(Expr *E) {
1060     getTopOfStack().InnerUsedAllocators.push_back(E);
1061   }
1062   /// Return list of used allocators.
1063   ArrayRef<Expr *> getInnerAllocators() const {
1064     return getTopOfStack().InnerUsedAllocators;
1065   }
1066   /// Marks the declaration as implicitly firstprivate nin the task-based
1067   /// regions.
1068   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1069     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1070   }
1071   /// Checks if the decl is implicitly firstprivate in the task-based region.
1072   bool isImplicitTaskFirstprivate(Decl *D) const {
1073     return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1074   }
1075 
1076   /// Marks decl as used in uses_allocators clause as the allocator.
1077   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1078     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1079   }
1080   /// Checks if specified decl is used in uses allocator clause as the
1081   /// allocator.
1082   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1083                                                         const Decl *D) const {
1084     const SharingMapTy &StackElem = getTopOfStack();
1085     auto I = StackElem.UsesAllocatorsDecls.find(D);
1086     if (I == StackElem.UsesAllocatorsDecls.end())
1087       return None;
1088     return I->getSecond();
1089   }
1090   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1091     const SharingMapTy &StackElem = getTopOfStack();
1092     auto I = StackElem.UsesAllocatorsDecls.find(D);
1093     if (I == StackElem.UsesAllocatorsDecls.end())
1094       return None;
1095     return I->getSecond();
1096   }
1097 
1098   void addDeclareMapperVarRef(Expr *Ref) {
1099     SharingMapTy &StackElem = getTopOfStack();
1100     StackElem.DeclareMapperVar = Ref;
1101   }
1102   const Expr *getDeclareMapperVarRef() const {
1103     const SharingMapTy *Top = getTopOfStackOrNull();
1104     return Top ? Top->DeclareMapperVar : nullptr;
1105   }
1106 };
1107 
1108 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1109   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1110 }
1111 
1112 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1113   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1114          DKind == OMPD_unknown;
1115 }
1116 
1117 } // namespace
1118 
1119 static const Expr *getExprAsWritten(const Expr *E) {
1120   if (const auto *FE = dyn_cast<FullExpr>(E))
1121     E = FE->getSubExpr();
1122 
1123   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1124     E = MTE->getSubExpr();
1125 
1126   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1127     E = Binder->getSubExpr();
1128 
1129   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1130     E = ICE->getSubExprAsWritten();
1131   return E->IgnoreParens();
1132 }
1133 
1134 static Expr *getExprAsWritten(Expr *E) {
1135   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1136 }
1137 
1138 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1139   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1140     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1141       D = ME->getMemberDecl();
1142   const auto *VD = dyn_cast<VarDecl>(D);
1143   const auto *FD = dyn_cast<FieldDecl>(D);
1144   if (VD != nullptr) {
1145     VD = VD->getCanonicalDecl();
1146     D = VD;
1147   } else {
1148     assert(FD);
1149     FD = FD->getCanonicalDecl();
1150     D = FD;
1151   }
1152   return D;
1153 }
1154 
1155 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1156   return const_cast<ValueDecl *>(
1157       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1158 }
1159 
1160 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1161                                           ValueDecl *D) const {
1162   D = getCanonicalDecl(D);
1163   auto *VD = dyn_cast<VarDecl>(D);
1164   const auto *FD = dyn_cast<FieldDecl>(D);
1165   DSAVarData DVar;
1166   if (Iter == end()) {
1167     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1168     // in a region but not in construct]
1169     //  File-scope or namespace-scope variables referenced in called routines
1170     //  in the region are shared unless they appear in a threadprivate
1171     //  directive.
1172     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1173       DVar.CKind = OMPC_shared;
1174 
1175     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1176     // in a region but not in construct]
1177     //  Variables with static storage duration that are declared in called
1178     //  routines in the region are shared.
1179     if (VD && VD->hasGlobalStorage())
1180       DVar.CKind = OMPC_shared;
1181 
1182     // Non-static data members are shared by default.
1183     if (FD)
1184       DVar.CKind = OMPC_shared;
1185 
1186     return DVar;
1187   }
1188 
1189   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1190   // in a Construct, C/C++, predetermined, p.1]
1191   // Variables with automatic storage duration that are declared in a scope
1192   // inside the construct are private.
1193   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1194       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1195     DVar.CKind = OMPC_private;
1196     return DVar;
1197   }
1198 
1199   DVar.DKind = Iter->Directive;
1200   // Explicitly specified attributes and local variables with predetermined
1201   // attributes.
1202   if (Iter->SharingMap.count(D)) {
1203     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1204     DVar.RefExpr = Data.RefExpr.getPointer();
1205     DVar.PrivateCopy = Data.PrivateCopy;
1206     DVar.CKind = Data.Attributes;
1207     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1208     DVar.Modifier = Data.Modifier;
1209     DVar.AppliedToPointee = Data.AppliedToPointee;
1210     return DVar;
1211   }
1212 
1213   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1214   // in a Construct, C/C++, implicitly determined, p.1]
1215   //  In a parallel or task construct, the data-sharing attributes of these
1216   //  variables are determined by the default clause, if present.
1217   switch (Iter->DefaultAttr) {
1218   case DSA_shared:
1219     DVar.CKind = OMPC_shared;
1220     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1221     return DVar;
1222   case DSA_none:
1223     return DVar;
1224   case DSA_firstprivate:
1225     if (VD->getStorageDuration() == SD_Static &&
1226         VD->getDeclContext()->isFileContext()) {
1227       DVar.CKind = OMPC_unknown;
1228     } else {
1229       DVar.CKind = OMPC_firstprivate;
1230     }
1231     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1232     return DVar;
1233   case DSA_unspecified:
1234     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1235     // in a Construct, implicitly determined, p.2]
1236     //  In a parallel construct, if no default clause is present, these
1237     //  variables are shared.
1238     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1239     if ((isOpenMPParallelDirective(DVar.DKind) &&
1240          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1241         isOpenMPTeamsDirective(DVar.DKind)) {
1242       DVar.CKind = OMPC_shared;
1243       return DVar;
1244     }
1245 
1246     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1247     // in a Construct, implicitly determined, p.4]
1248     //  In a task construct, if no default clause is present, a variable that in
1249     //  the enclosing context is determined to be shared by all implicit tasks
1250     //  bound to the current team is shared.
1251     if (isOpenMPTaskingDirective(DVar.DKind)) {
1252       DSAVarData DVarTemp;
1253       const_iterator I = Iter, E = end();
1254       do {
1255         ++I;
1256         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1257         // Referenced in a Construct, implicitly determined, p.6]
1258         //  In a task construct, if no default clause is present, a variable
1259         //  whose data-sharing attribute is not determined by the rules above is
1260         //  firstprivate.
1261         DVarTemp = getDSA(I, D);
1262         if (DVarTemp.CKind != OMPC_shared) {
1263           DVar.RefExpr = nullptr;
1264           DVar.CKind = OMPC_firstprivate;
1265           return DVar;
1266         }
1267       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1268       DVar.CKind =
1269           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1270       return DVar;
1271     }
1272   }
1273   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1274   // in a Construct, implicitly determined, p.3]
1275   //  For constructs other than task, if no default clause is present, these
1276   //  variables inherit their data-sharing attributes from the enclosing
1277   //  context.
1278   return getDSA(++Iter, D);
1279 }
1280 
1281 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1282                                          const Expr *NewDE) {
1283   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1284   D = getCanonicalDecl(D);
1285   SharingMapTy &StackElem = getTopOfStack();
1286   auto It = StackElem.AlignedMap.find(D);
1287   if (It == StackElem.AlignedMap.end()) {
1288     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1289     StackElem.AlignedMap[D] = NewDE;
1290     return nullptr;
1291   }
1292   assert(It->second && "Unexpected nullptr expr in the aligned map");
1293   return It->second;
1294 }
1295 
1296 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1297                                              const Expr *NewDE) {
1298   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1299   D = getCanonicalDecl(D);
1300   SharingMapTy &StackElem = getTopOfStack();
1301   auto It = StackElem.NontemporalMap.find(D);
1302   if (It == StackElem.NontemporalMap.end()) {
1303     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1304     StackElem.NontemporalMap[D] = NewDE;
1305     return nullptr;
1306   }
1307   assert(It->second && "Unexpected nullptr expr in the aligned map");
1308   return It->second;
1309 }
1310 
1311 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1312   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1313   D = getCanonicalDecl(D);
1314   SharingMapTy &StackElem = getTopOfStack();
1315   StackElem.LCVMap.try_emplace(
1316       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1317 }
1318 
1319 const DSAStackTy::LCDeclInfo
1320 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1321   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1322   D = getCanonicalDecl(D);
1323   const SharingMapTy &StackElem = getTopOfStack();
1324   auto It = StackElem.LCVMap.find(D);
1325   if (It != StackElem.LCVMap.end())
1326     return It->second;
1327   return {0, nullptr};
1328 }
1329 
1330 const DSAStackTy::LCDeclInfo
1331 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1332   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1333   D = getCanonicalDecl(D);
1334   for (unsigned I = Level + 1; I > 0; --I) {
1335     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1336     auto It = StackElem.LCVMap.find(D);
1337     if (It != StackElem.LCVMap.end())
1338       return It->second;
1339   }
1340   return {0, nullptr};
1341 }
1342 
1343 const DSAStackTy::LCDeclInfo
1344 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1345   const SharingMapTy *Parent = getSecondOnStackOrNull();
1346   assert(Parent && "Data-sharing attributes stack is empty");
1347   D = getCanonicalDecl(D);
1348   auto It = Parent->LCVMap.find(D);
1349   if (It != Parent->LCVMap.end())
1350     return It->second;
1351   return {0, nullptr};
1352 }
1353 
1354 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1355   const SharingMapTy *Parent = getSecondOnStackOrNull();
1356   assert(Parent && "Data-sharing attributes stack is empty");
1357   if (Parent->LCVMap.size() < I)
1358     return nullptr;
1359   for (const auto &Pair : Parent->LCVMap)
1360     if (Pair.second.first == I)
1361       return Pair.first;
1362   return nullptr;
1363 }
1364 
1365 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1366                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1367                         bool AppliedToPointee) {
1368   D = getCanonicalDecl(D);
1369   if (A == OMPC_threadprivate) {
1370     DSAInfo &Data = Threadprivates[D];
1371     Data.Attributes = A;
1372     Data.RefExpr.setPointer(E);
1373     Data.PrivateCopy = nullptr;
1374     Data.Modifier = Modifier;
1375   } else {
1376     DSAInfo &Data = getTopOfStack().SharingMap[D];
1377     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1378            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1379            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1380            (isLoopControlVariable(D).first && A == OMPC_private));
1381     Data.Modifier = Modifier;
1382     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1383       Data.RefExpr.setInt(/*IntVal=*/true);
1384       return;
1385     }
1386     const bool IsLastprivate =
1387         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1388     Data.Attributes = A;
1389     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1390     Data.PrivateCopy = PrivateCopy;
1391     Data.AppliedToPointee = AppliedToPointee;
1392     if (PrivateCopy) {
1393       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1394       Data.Modifier = Modifier;
1395       Data.Attributes = A;
1396       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1397       Data.PrivateCopy = nullptr;
1398       Data.AppliedToPointee = AppliedToPointee;
1399     }
1400   }
1401 }
1402 
1403 /// Build a variable declaration for OpenMP loop iteration variable.
1404 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1405                              StringRef Name, const AttrVec *Attrs = nullptr,
1406                              DeclRefExpr *OrigRef = nullptr) {
1407   DeclContext *DC = SemaRef.CurContext;
1408   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1409   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1410   auto *Decl =
1411       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1412   if (Attrs) {
1413     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1414          I != E; ++I)
1415       Decl->addAttr(*I);
1416   }
1417   Decl->setImplicit();
1418   if (OrigRef) {
1419     Decl->addAttr(
1420         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1421   }
1422   return Decl;
1423 }
1424 
1425 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1426                                      SourceLocation Loc,
1427                                      bool RefersToCapture = false) {
1428   D->setReferenced();
1429   D->markUsed(S.Context);
1430   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1431                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1432                              VK_LValue);
1433 }
1434 
1435 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1436                                            BinaryOperatorKind BOK) {
1437   D = getCanonicalDecl(D);
1438   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1439   assert(
1440       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1441       "Additional reduction info may be specified only for reduction items.");
1442   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1443   assert(ReductionData.ReductionRange.isInvalid() &&
1444          (getTopOfStack().Directive == OMPD_taskgroup ||
1445           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1446             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1447            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1448          "Additional reduction info may be specified only once for reduction "
1449          "items.");
1450   ReductionData.set(BOK, SR);
1451   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1452   if (!TaskgroupReductionRef) {
1453     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1454                                SemaRef.Context.VoidPtrTy, ".task_red.");
1455     TaskgroupReductionRef =
1456         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1457   }
1458 }
1459 
1460 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1461                                            const Expr *ReductionRef) {
1462   D = getCanonicalDecl(D);
1463   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1464   assert(
1465       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1466       "Additional reduction info may be specified only for reduction items.");
1467   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1468   assert(ReductionData.ReductionRange.isInvalid() &&
1469          (getTopOfStack().Directive == OMPD_taskgroup ||
1470           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1471             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1472            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1473          "Additional reduction info may be specified only once for reduction "
1474          "items.");
1475   ReductionData.set(ReductionRef, SR);
1476   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1477   if (!TaskgroupReductionRef) {
1478     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1479                                SemaRef.Context.VoidPtrTy, ".task_red.");
1480     TaskgroupReductionRef =
1481         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1482   }
1483 }
1484 
1485 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1486     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1487     Expr *&TaskgroupDescriptor) const {
1488   D = getCanonicalDecl(D);
1489   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1490   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1491     const DSAInfo &Data = I->SharingMap.lookup(D);
1492     if (Data.Attributes != OMPC_reduction ||
1493         Data.Modifier != OMPC_REDUCTION_task)
1494       continue;
1495     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1496     if (!ReductionData.ReductionOp ||
1497         ReductionData.ReductionOp.is<const Expr *>())
1498       return DSAVarData();
1499     SR = ReductionData.ReductionRange;
1500     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1501     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1502                                        "expression for the descriptor is not "
1503                                        "set.");
1504     TaskgroupDescriptor = I->TaskgroupReductionRef;
1505     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1506                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1507                       /*AppliedToPointee=*/false);
1508   }
1509   return DSAVarData();
1510 }
1511 
1512 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1513     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1514     Expr *&TaskgroupDescriptor) const {
1515   D = getCanonicalDecl(D);
1516   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1517   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1518     const DSAInfo &Data = I->SharingMap.lookup(D);
1519     if (Data.Attributes != OMPC_reduction ||
1520         Data.Modifier != OMPC_REDUCTION_task)
1521       continue;
1522     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1523     if (!ReductionData.ReductionOp ||
1524         !ReductionData.ReductionOp.is<const Expr *>())
1525       return DSAVarData();
1526     SR = ReductionData.ReductionRange;
1527     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1528     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1529                                        "expression for the descriptor is not "
1530                                        "set.");
1531     TaskgroupDescriptor = I->TaskgroupReductionRef;
1532     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1533                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1534                       /*AppliedToPointee=*/false);
1535   }
1536   return DSAVarData();
1537 }
1538 
1539 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1540   D = D->getCanonicalDecl();
1541   for (const_iterator E = end(); I != E; ++I) {
1542     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1543         isOpenMPTargetExecutionDirective(I->Directive)) {
1544       if (I->CurScope) {
1545         Scope *TopScope = I->CurScope->getParent();
1546         Scope *CurScope = getCurScope();
1547         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1548           CurScope = CurScope->getParent();
1549         return CurScope != TopScope;
1550       }
1551       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1552         if (I->Context == DC)
1553           return true;
1554       return false;
1555     }
1556   }
1557   return false;
1558 }
1559 
1560 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1561                                   bool AcceptIfMutable = true,
1562                                   bool *IsClassType = nullptr) {
1563   ASTContext &Context = SemaRef.getASTContext();
1564   Type = Type.getNonReferenceType().getCanonicalType();
1565   bool IsConstant = Type.isConstant(Context);
1566   Type = Context.getBaseElementType(Type);
1567   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1568                                 ? Type->getAsCXXRecordDecl()
1569                                 : nullptr;
1570   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1571     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1572       RD = CTD->getTemplatedDecl();
1573   if (IsClassType)
1574     *IsClassType = RD;
1575   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1576                          RD->hasDefinition() && RD->hasMutableFields());
1577 }
1578 
1579 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1580                                       QualType Type, OpenMPClauseKind CKind,
1581                                       SourceLocation ELoc,
1582                                       bool AcceptIfMutable = true,
1583                                       bool ListItemNotVar = false) {
1584   ASTContext &Context = SemaRef.getASTContext();
1585   bool IsClassType;
1586   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1587     unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1588                     : IsClassType  ? diag::err_omp_const_not_mutable_variable
1589                                    : diag::err_omp_const_variable;
1590     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1591     if (!ListItemNotVar && D) {
1592       const VarDecl *VD = dyn_cast<VarDecl>(D);
1593       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1594                                VarDecl::DeclarationOnly;
1595       SemaRef.Diag(D->getLocation(),
1596                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1597           << D;
1598     }
1599     return true;
1600   }
1601   return false;
1602 }
1603 
1604 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1605                                                    bool FromParent) {
1606   D = getCanonicalDecl(D);
1607   DSAVarData DVar;
1608 
1609   auto *VD = dyn_cast<VarDecl>(D);
1610   auto TI = Threadprivates.find(D);
1611   if (TI != Threadprivates.end()) {
1612     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1613     DVar.CKind = OMPC_threadprivate;
1614     DVar.Modifier = TI->getSecond().Modifier;
1615     return DVar;
1616   }
1617   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1618     DVar.RefExpr = buildDeclRefExpr(
1619         SemaRef, VD, D->getType().getNonReferenceType(),
1620         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1621     DVar.CKind = OMPC_threadprivate;
1622     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1623     return DVar;
1624   }
1625   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1626   // in a Construct, C/C++, predetermined, p.1]
1627   //  Variables appearing in threadprivate directives are threadprivate.
1628   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1629        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1630          SemaRef.getLangOpts().OpenMPUseTLS &&
1631          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1632       (VD && VD->getStorageClass() == SC_Register &&
1633        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1634     DVar.RefExpr = buildDeclRefExpr(
1635         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1636     DVar.CKind = OMPC_threadprivate;
1637     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1638     return DVar;
1639   }
1640   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1641       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1642       !isLoopControlVariable(D).first) {
1643     const_iterator IterTarget =
1644         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1645           return isOpenMPTargetExecutionDirective(Data.Directive);
1646         });
1647     if (IterTarget != end()) {
1648       const_iterator ParentIterTarget = IterTarget + 1;
1649       for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1650         if (isOpenMPLocal(VD, Iter)) {
1651           DVar.RefExpr =
1652               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1653                                D->getLocation());
1654           DVar.CKind = OMPC_threadprivate;
1655           return DVar;
1656         }
1657       }
1658       if (!isClauseParsingMode() || IterTarget != begin()) {
1659         auto DSAIter = IterTarget->SharingMap.find(D);
1660         if (DSAIter != IterTarget->SharingMap.end() &&
1661             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1662           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1663           DVar.CKind = OMPC_threadprivate;
1664           return DVar;
1665         }
1666         const_iterator End = end();
1667         if (!SemaRef.isOpenMPCapturedByRef(D,
1668                                            std::distance(ParentIterTarget, End),
1669                                            /*OpenMPCaptureLevel=*/0)) {
1670           DVar.RefExpr =
1671               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1672                                IterTarget->ConstructLoc);
1673           DVar.CKind = OMPC_threadprivate;
1674           return DVar;
1675         }
1676       }
1677     }
1678   }
1679 
1680   if (isStackEmpty())
1681     // Not in OpenMP execution region and top scope was already checked.
1682     return DVar;
1683 
1684   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1685   // in a Construct, C/C++, predetermined, p.4]
1686   //  Static data members are shared.
1687   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1688   // in a Construct, C/C++, predetermined, p.7]
1689   //  Variables with static storage duration that are declared in a scope
1690   //  inside the construct are shared.
1691   if (VD && VD->isStaticDataMember()) {
1692     // Check for explicitly specified attributes.
1693     const_iterator I = begin();
1694     const_iterator EndI = end();
1695     if (FromParent && I != EndI)
1696       ++I;
1697     if (I != EndI) {
1698       auto It = I->SharingMap.find(D);
1699       if (It != I->SharingMap.end()) {
1700         const DSAInfo &Data = It->getSecond();
1701         DVar.RefExpr = Data.RefExpr.getPointer();
1702         DVar.PrivateCopy = Data.PrivateCopy;
1703         DVar.CKind = Data.Attributes;
1704         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1705         DVar.DKind = I->Directive;
1706         DVar.Modifier = Data.Modifier;
1707         DVar.AppliedToPointee = Data.AppliedToPointee;
1708         return DVar;
1709       }
1710     }
1711 
1712     DVar.CKind = OMPC_shared;
1713     return DVar;
1714   }
1715 
1716   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1717   // The predetermined shared attribute for const-qualified types having no
1718   // mutable members was removed after OpenMP 3.1.
1719   if (SemaRef.LangOpts.OpenMP <= 31) {
1720     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1721     // in a Construct, C/C++, predetermined, p.6]
1722     //  Variables with const qualified type having no mutable member are
1723     //  shared.
1724     if (isConstNotMutableType(SemaRef, D->getType())) {
1725       // Variables with const-qualified type having no mutable member may be
1726       // listed in a firstprivate clause, even if they are static data members.
1727       DSAVarData DVarTemp = hasInnermostDSA(
1728           D,
1729           [](OpenMPClauseKind C, bool) {
1730             return C == OMPC_firstprivate || C == OMPC_shared;
1731           },
1732           MatchesAlways, FromParent);
1733       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1734         return DVarTemp;
1735 
1736       DVar.CKind = OMPC_shared;
1737       return DVar;
1738     }
1739   }
1740 
1741   // Explicitly specified attributes and local variables with predetermined
1742   // attributes.
1743   const_iterator I = begin();
1744   const_iterator EndI = end();
1745   if (FromParent && I != EndI)
1746     ++I;
1747   if (I == EndI)
1748     return DVar;
1749   auto It = I->SharingMap.find(D);
1750   if (It != I->SharingMap.end()) {
1751     const DSAInfo &Data = It->getSecond();
1752     DVar.RefExpr = Data.RefExpr.getPointer();
1753     DVar.PrivateCopy = Data.PrivateCopy;
1754     DVar.CKind = Data.Attributes;
1755     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1756     DVar.DKind = I->Directive;
1757     DVar.Modifier = Data.Modifier;
1758     DVar.AppliedToPointee = Data.AppliedToPointee;
1759   }
1760 
1761   return DVar;
1762 }
1763 
1764 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1765                                                         bool FromParent) const {
1766   if (isStackEmpty()) {
1767     const_iterator I;
1768     return getDSA(I, D);
1769   }
1770   D = getCanonicalDecl(D);
1771   const_iterator StartI = begin();
1772   const_iterator EndI = end();
1773   if (FromParent && StartI != EndI)
1774     ++StartI;
1775   return getDSA(StartI, D);
1776 }
1777 
1778 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1779                                                         unsigned Level) const {
1780   if (getStackSize() <= Level)
1781     return DSAVarData();
1782   D = getCanonicalDecl(D);
1783   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1784   return getDSA(StartI, D);
1785 }
1786 
1787 const DSAStackTy::DSAVarData
1788 DSAStackTy::hasDSA(ValueDecl *D,
1789                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1790                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1791                    bool FromParent) const {
1792   if (isStackEmpty())
1793     return {};
1794   D = getCanonicalDecl(D);
1795   const_iterator I = begin();
1796   const_iterator EndI = end();
1797   if (FromParent && I != EndI)
1798     ++I;
1799   for (; I != EndI; ++I) {
1800     if (!DPred(I->Directive) &&
1801         !isImplicitOrExplicitTaskingRegion(I->Directive))
1802       continue;
1803     const_iterator NewI = I;
1804     DSAVarData DVar = getDSA(NewI, D);
1805     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1806       return DVar;
1807   }
1808   return {};
1809 }
1810 
1811 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1812     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1813     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1814     bool FromParent) const {
1815   if (isStackEmpty())
1816     return {};
1817   D = getCanonicalDecl(D);
1818   const_iterator StartI = begin();
1819   const_iterator EndI = end();
1820   if (FromParent && StartI != EndI)
1821     ++StartI;
1822   if (StartI == EndI || !DPred(StartI->Directive))
1823     return {};
1824   const_iterator NewI = StartI;
1825   DSAVarData DVar = getDSA(NewI, D);
1826   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1827              ? DVar
1828              : DSAVarData();
1829 }
1830 
1831 bool DSAStackTy::hasExplicitDSA(
1832     const ValueDecl *D,
1833     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1834     unsigned Level, bool NotLastprivate) const {
1835   if (getStackSize() <= Level)
1836     return false;
1837   D = getCanonicalDecl(D);
1838   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1839   auto I = StackElem.SharingMap.find(D);
1840   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1841       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1842       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1843     return true;
1844   // Check predetermined rules for the loop control variables.
1845   auto LI = StackElem.LCVMap.find(D);
1846   if (LI != StackElem.LCVMap.end())
1847     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1848   return false;
1849 }
1850 
1851 bool DSAStackTy::hasExplicitDirective(
1852     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1853     unsigned Level) const {
1854   if (getStackSize() <= Level)
1855     return false;
1856   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1857   return DPred(StackElem.Directive);
1858 }
1859 
1860 bool DSAStackTy::hasDirective(
1861     const llvm::function_ref<bool(OpenMPDirectiveKind,
1862                                   const DeclarationNameInfo &, SourceLocation)>
1863         DPred,
1864     bool FromParent) const {
1865   // We look only in the enclosing region.
1866   size_t Skip = FromParent ? 2 : 1;
1867   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1868        I != E; ++I) {
1869     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1870       return true;
1871   }
1872   return false;
1873 }
1874 
1875 void Sema::InitDataSharingAttributesStack() {
1876   VarDataSharingAttributesStack = new DSAStackTy(*this);
1877 }
1878 
1879 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1880 
1881 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
1882 
1883 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1884   DSAStack->popFunction(OldFSI);
1885 }
1886 
1887 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1888   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1889          "Expected OpenMP device compilation.");
1890   return !S.isInOpenMPTargetExecutionDirective();
1891 }
1892 
1893 namespace {
1894 /// Status of the function emission on the host/device.
1895 enum class FunctionEmissionStatus {
1896   Emitted,
1897   Discarded,
1898   Unknown,
1899 };
1900 } // anonymous namespace
1901 
1902 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1903                                                          unsigned DiagID,
1904                                                          FunctionDecl *FD) {
1905   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1906          "Expected OpenMP device compilation.");
1907 
1908   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1909   if (FD) {
1910     FunctionEmissionStatus FES = getEmissionStatus(FD);
1911     switch (FES) {
1912     case FunctionEmissionStatus::Emitted:
1913       Kind = SemaDiagnosticBuilder::K_Immediate;
1914       break;
1915     case FunctionEmissionStatus::Unknown:
1916       // TODO: We should always delay diagnostics here in case a target
1917       //       region is in a function we do not emit. However, as the
1918       //       current diagnostics are associated with the function containing
1919       //       the target region and we do not emit that one, we would miss out
1920       //       on diagnostics for the target region itself. We need to anchor
1921       //       the diagnostics with the new generated function *or* ensure we
1922       //       emit diagnostics associated with the surrounding function.
1923       Kind = isOpenMPDeviceDelayedContext(*this)
1924                  ? SemaDiagnosticBuilder::K_Deferred
1925                  : SemaDiagnosticBuilder::K_Immediate;
1926       break;
1927     case FunctionEmissionStatus::TemplateDiscarded:
1928     case FunctionEmissionStatus::OMPDiscarded:
1929       Kind = SemaDiagnosticBuilder::K_Nop;
1930       break;
1931     case FunctionEmissionStatus::CUDADiscarded:
1932       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1933       break;
1934     }
1935   }
1936 
1937   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1938 }
1939 
1940 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1941                                                        unsigned DiagID,
1942                                                        FunctionDecl *FD) {
1943   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1944          "Expected OpenMP host compilation.");
1945 
1946   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1947   if (FD) {
1948     FunctionEmissionStatus FES = getEmissionStatus(FD);
1949     switch (FES) {
1950     case FunctionEmissionStatus::Emitted:
1951       Kind = SemaDiagnosticBuilder::K_Immediate;
1952       break;
1953     case FunctionEmissionStatus::Unknown:
1954       Kind = SemaDiagnosticBuilder::K_Deferred;
1955       break;
1956     case FunctionEmissionStatus::TemplateDiscarded:
1957     case FunctionEmissionStatus::OMPDiscarded:
1958     case FunctionEmissionStatus::CUDADiscarded:
1959       Kind = SemaDiagnosticBuilder::K_Nop;
1960       break;
1961     }
1962   }
1963 
1964   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1965 }
1966 
1967 static OpenMPDefaultmapClauseKind
1968 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1969   if (LO.OpenMP <= 45) {
1970     if (VD->getType().getNonReferenceType()->isScalarType())
1971       return OMPC_DEFAULTMAP_scalar;
1972     return OMPC_DEFAULTMAP_aggregate;
1973   }
1974   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1975     return OMPC_DEFAULTMAP_pointer;
1976   if (VD->getType().getNonReferenceType()->isScalarType())
1977     return OMPC_DEFAULTMAP_scalar;
1978   return OMPC_DEFAULTMAP_aggregate;
1979 }
1980 
1981 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1982                                  unsigned OpenMPCaptureLevel) const {
1983   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1984 
1985   ASTContext &Ctx = getASTContext();
1986   bool IsByRef = true;
1987 
1988   // Find the directive that is associated with the provided scope.
1989   D = cast<ValueDecl>(D->getCanonicalDecl());
1990   QualType Ty = D->getType();
1991 
1992   bool IsVariableUsedInMapClause = false;
1993   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1994     // This table summarizes how a given variable should be passed to the device
1995     // given its type and the clauses where it appears. This table is based on
1996     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1997     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1998     //
1999     // =========================================================================
2000     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
2001     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
2002     // =========================================================================
2003     // | scl  |               |     |       |       -       |          | bycopy|
2004     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2005     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2006     // | scl  |       x       |     |       |       -       |          | byref |
2007     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2008     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2009     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2010     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2011     //
2012     // | agg  |      n.a.     |     |       |       -       |          | byref |
2013     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2014     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2015     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2016     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2017     //
2018     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2019     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2020     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2021     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2022     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2023     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2024     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2025     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2026     // =========================================================================
2027     // Legend:
2028     //  scl - scalar
2029     //  ptr - pointer
2030     //  agg - aggregate
2031     //  x - applies
2032     //  - - invalid in this combination
2033     //  [] - mapped with an array section
2034     //  byref - should be mapped by reference
2035     //  byval - should be mapped by value
2036     //  null - initialize a local variable to null on the device
2037     //
2038     // Observations:
2039     //  - All scalar declarations that show up in a map clause have to be passed
2040     //    by reference, because they may have been mapped in the enclosing data
2041     //    environment.
2042     //  - If the scalar value does not fit the size of uintptr, it has to be
2043     //    passed by reference, regardless the result in the table above.
2044     //  - For pointers mapped by value that have either an implicit map or an
2045     //    array section, the runtime library may pass the NULL value to the
2046     //    device instead of the value passed to it by the compiler.
2047 
2048     if (Ty->isReferenceType())
2049       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2050 
2051     // Locate map clauses and see if the variable being captured is referred to
2052     // in any of those clauses. Here we only care about variables, not fields,
2053     // because fields are part of aggregates.
2054     bool IsVariableAssociatedWithSection = false;
2055 
2056     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2057         D, Level,
2058         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2059          D](OMPClauseMappableExprCommon::MappableExprComponentListRef
2060                 MapExprComponents,
2061             OpenMPClauseKind WhereFoundClauseKind) {
2062           // Only the map clause information influences how a variable is
2063           // captured. E.g. is_device_ptr does not require changing the default
2064           // behavior.
2065           if (WhereFoundClauseKind != OMPC_map)
2066             return false;
2067 
2068           auto EI = MapExprComponents.rbegin();
2069           auto EE = MapExprComponents.rend();
2070 
2071           assert(EI != EE && "Invalid map expression!");
2072 
2073           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2074             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2075 
2076           ++EI;
2077           if (EI == EE)
2078             return false;
2079 
2080           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2081               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2082               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2083               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2084             IsVariableAssociatedWithSection = true;
2085             // There is nothing more we need to know about this variable.
2086             return true;
2087           }
2088 
2089           // Keep looking for more map info.
2090           return false;
2091         });
2092 
2093     if (IsVariableUsedInMapClause) {
2094       // If variable is identified in a map clause it is always captured by
2095       // reference except if it is a pointer that is dereferenced somehow.
2096       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2097     } else {
2098       // By default, all the data that has a scalar type is mapped by copy
2099       // (except for reduction variables).
2100       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2101       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2102                  !Ty->isAnyPointerType()) ||
2103                 !Ty->isScalarType() ||
2104                 DSAStack->isDefaultmapCapturedByRef(
2105                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2106                 DSAStack->hasExplicitDSA(
2107                     D,
2108                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2109                       return K == OMPC_reduction && !AppliedToPointee;
2110                     },
2111                     Level);
2112     }
2113   }
2114 
2115   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2116     IsByRef =
2117         ((IsVariableUsedInMapClause &&
2118           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2119               OMPD_target) ||
2120          !(DSAStack->hasExplicitDSA(
2121                D,
2122                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2123                  return K == OMPC_firstprivate ||
2124                         (K == OMPC_reduction && AppliedToPointee);
2125                },
2126                Level, /*NotLastprivate=*/true) ||
2127            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2128         // If the variable is artificial and must be captured by value - try to
2129         // capture by value.
2130         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2131           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2132         // If the variable is implicitly firstprivate and scalar - capture by
2133         // copy
2134         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2135           !DSAStack->hasExplicitDSA(
2136               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2137               Level) &&
2138           !DSAStack->isLoopControlVariable(D, Level).first);
2139   }
2140 
2141   // When passing data by copy, we need to make sure it fits the uintptr size
2142   // and alignment, because the runtime library only deals with uintptr types.
2143   // If it does not fit the uintptr size, we need to pass the data by reference
2144   // instead.
2145   if (!IsByRef &&
2146       (Ctx.getTypeSizeInChars(Ty) >
2147            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2148        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2149     IsByRef = true;
2150   }
2151 
2152   return IsByRef;
2153 }
2154 
2155 unsigned Sema::getOpenMPNestingLevel() const {
2156   assert(getLangOpts().OpenMP);
2157   return DSAStack->getNestingLevel();
2158 }
2159 
2160 bool Sema::isInOpenMPTargetExecutionDirective() const {
2161   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2162           !DSAStack->isClauseParsingMode()) ||
2163          DSAStack->hasDirective(
2164              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2165                 SourceLocation) -> bool {
2166                return isOpenMPTargetExecutionDirective(K);
2167              },
2168              false);
2169 }
2170 
2171 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2172                                     unsigned StopAt) {
2173   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2174   D = getCanonicalDecl(D);
2175 
2176   auto *VD = dyn_cast<VarDecl>(D);
2177   // Do not capture constexpr variables.
2178   if (VD && VD->isConstexpr())
2179     return nullptr;
2180 
2181   // If we want to determine whether the variable should be captured from the
2182   // perspective of the current capturing scope, and we've already left all the
2183   // capturing scopes of the top directive on the stack, check from the
2184   // perspective of its parent directive (if any) instead.
2185   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2186       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2187 
2188   // If we are attempting to capture a global variable in a directive with
2189   // 'target' we return true so that this global is also mapped to the device.
2190   //
2191   if (VD && !VD->hasLocalStorage() &&
2192       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2193     if (isInOpenMPTargetExecutionDirective()) {
2194       DSAStackTy::DSAVarData DVarTop =
2195           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2196       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2197         return VD;
2198       // If the declaration is enclosed in a 'declare target' directive,
2199       // then it should not be captured.
2200       //
2201       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2202         return nullptr;
2203       CapturedRegionScopeInfo *CSI = nullptr;
2204       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2205                llvm::reverse(FunctionScopes),
2206                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2207         if (!isa<CapturingScopeInfo>(FSI))
2208           return nullptr;
2209         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2210           if (RSI->CapRegionKind == CR_OpenMP) {
2211             CSI = RSI;
2212             break;
2213           }
2214       }
2215       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2216       SmallVector<OpenMPDirectiveKind, 4> Regions;
2217       getOpenMPCaptureRegions(Regions,
2218                               DSAStack->getDirective(CSI->OpenMPLevel));
2219       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2220         return VD;
2221     }
2222     if (isInOpenMPDeclareTargetContext()) {
2223       // Try to mark variable as declare target if it is used in capturing
2224       // regions.
2225       if (LangOpts.OpenMP <= 45 &&
2226           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2227         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2228       return nullptr;
2229     }
2230   }
2231 
2232   if (CheckScopeInfo) {
2233     bool OpenMPFound = false;
2234     for (unsigned I = StopAt + 1; I > 0; --I) {
2235       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2236       if (!isa<CapturingScopeInfo>(FSI))
2237         return nullptr;
2238       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2239         if (RSI->CapRegionKind == CR_OpenMP) {
2240           OpenMPFound = true;
2241           break;
2242         }
2243     }
2244     if (!OpenMPFound)
2245       return nullptr;
2246   }
2247 
2248   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2249       (!DSAStack->isClauseParsingMode() ||
2250        DSAStack->getParentDirective() != OMPD_unknown)) {
2251     auto &&Info = DSAStack->isLoopControlVariable(D);
2252     if (Info.first ||
2253         (VD && VD->hasLocalStorage() &&
2254          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2255         (VD && DSAStack->isForceVarCapturing()))
2256       return VD ? VD : Info.second;
2257     DSAStackTy::DSAVarData DVarTop =
2258         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2259     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2260         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2261       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2262     // Threadprivate variables must not be captured.
2263     if (isOpenMPThreadPrivate(DVarTop.CKind))
2264       return nullptr;
2265     // The variable is not private or it is the variable in the directive with
2266     // default(none) clause and not used in any clause.
2267     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2268         D,
2269         [](OpenMPClauseKind C, bool AppliedToPointee) {
2270           return isOpenMPPrivate(C) && !AppliedToPointee;
2271         },
2272         [](OpenMPDirectiveKind) { return true; },
2273         DSAStack->isClauseParsingMode());
2274     // Global shared must not be captured.
2275     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2276         ((DSAStack->getDefaultDSA() != DSA_none &&
2277           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2278          DVarTop.CKind == OMPC_shared))
2279       return nullptr;
2280     if (DVarPrivate.CKind != OMPC_unknown ||
2281         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2282                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2283       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2284   }
2285   return nullptr;
2286 }
2287 
2288 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2289                                         unsigned Level) const {
2290   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2291 }
2292 
2293 void Sema::startOpenMPLoop() {
2294   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2295   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2296     DSAStack->loopInit();
2297 }
2298 
2299 void Sema::startOpenMPCXXRangeFor() {
2300   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2301   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2302     DSAStack->resetPossibleLoopCounter();
2303     DSAStack->loopStart();
2304   }
2305 }
2306 
2307 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2308                                            unsigned CapLevel) const {
2309   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2310   if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
2311     bool IsTriviallyCopyable =
2312         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2313         !D->getType()
2314              .getNonReferenceType()
2315              .getCanonicalType()
2316              ->getAsCXXRecordDecl();
2317     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2318     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2319     getOpenMPCaptureRegions(CaptureRegions, DKind);
2320     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2321         (IsTriviallyCopyable ||
2322          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2323       if (DSAStack->hasExplicitDSA(
2324               D,
2325               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2326               Level, /*NotLastprivate=*/true))
2327         return OMPC_firstprivate;
2328       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2329       if (DVar.CKind != OMPC_shared &&
2330           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2331         DSAStack->addImplicitTaskFirstprivate(Level, D);
2332         return OMPC_firstprivate;
2333       }
2334     }
2335   }
2336   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2337     if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2338       DSAStack->resetPossibleLoopCounter(D);
2339       DSAStack->loopStart();
2340       return OMPC_private;
2341     }
2342     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2343          DSAStack->isLoopControlVariable(D).first) &&
2344         !DSAStack->hasExplicitDSA(
2345             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2346             Level) &&
2347         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2348       return OMPC_private;
2349   }
2350   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2351     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2352         DSAStack->isForceVarCapturing() &&
2353         !DSAStack->hasExplicitDSA(
2354             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2355             Level))
2356       return OMPC_private;
2357   }
2358   // User-defined allocators are private since they must be defined in the
2359   // context of target region.
2360   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2361       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2362           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2363           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2364     return OMPC_private;
2365   return (DSAStack->hasExplicitDSA(
2366               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2367               Level) ||
2368           (DSAStack->isClauseParsingMode() &&
2369            DSAStack->getClauseParsingMode() == OMPC_private) ||
2370           // Consider taskgroup reduction descriptor variable a private
2371           // to avoid possible capture in the region.
2372           (DSAStack->hasExplicitDirective(
2373                [](OpenMPDirectiveKind K) {
2374                  return K == OMPD_taskgroup ||
2375                         ((isOpenMPParallelDirective(K) ||
2376                           isOpenMPWorksharingDirective(K)) &&
2377                          !isOpenMPSimdDirective(K));
2378                },
2379                Level) &&
2380            DSAStack->isTaskgroupReductionRef(D, Level)))
2381              ? OMPC_private
2382              : OMPC_unknown;
2383 }
2384 
2385 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2386                                 unsigned Level) {
2387   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2388   D = getCanonicalDecl(D);
2389   OpenMPClauseKind OMPC = OMPC_unknown;
2390   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2391     const unsigned NewLevel = I - 1;
2392     if (DSAStack->hasExplicitDSA(
2393             D,
2394             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2395               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2396                 OMPC = K;
2397                 return true;
2398               }
2399               return false;
2400             },
2401             NewLevel))
2402       break;
2403     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2404             D, NewLevel,
2405             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2406                OpenMPClauseKind) { return true; })) {
2407       OMPC = OMPC_map;
2408       break;
2409     }
2410     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2411                                        NewLevel)) {
2412       OMPC = OMPC_map;
2413       if (DSAStack->mustBeFirstprivateAtLevel(
2414               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2415         OMPC = OMPC_firstprivate;
2416       break;
2417     }
2418   }
2419   if (OMPC != OMPC_unknown)
2420     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2421 }
2422 
2423 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2424                                       unsigned CaptureLevel) const {
2425   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2426   // Return true if the current level is no longer enclosed in a target region.
2427 
2428   SmallVector<OpenMPDirectiveKind, 4> Regions;
2429   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2430   const auto *VD = dyn_cast<VarDecl>(D);
2431   return VD && !VD->hasLocalStorage() &&
2432          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2433                                         Level) &&
2434          Regions[CaptureLevel] != OMPD_task;
2435 }
2436 
2437 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2438                                       unsigned CaptureLevel) const {
2439   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2440   // Return true if the current level is no longer enclosed in a target region.
2441 
2442   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2443     if (!VD->hasLocalStorage()) {
2444       if (isInOpenMPTargetExecutionDirective())
2445         return true;
2446       DSAStackTy::DSAVarData TopDVar =
2447           DSAStack->getTopDSA(D, /*FromParent=*/false);
2448       unsigned NumLevels =
2449           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2450       if (Level == 0)
2451         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2452       do {
2453         --Level;
2454         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2455         if (DVar.CKind != OMPC_shared)
2456           return true;
2457       } while (Level > 0);
2458     }
2459   }
2460   return true;
2461 }
2462 
2463 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2464 
2465 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2466                                           OMPTraitInfo &TI) {
2467   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2468 }
2469 
2470 void Sema::ActOnOpenMPEndDeclareVariant() {
2471   assert(isInOpenMPDeclareVariantScope() &&
2472          "Not in OpenMP declare variant scope!");
2473 
2474   OMPDeclareVariantScopes.pop_back();
2475 }
2476 
2477 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2478                                          const FunctionDecl *Callee,
2479                                          SourceLocation Loc) {
2480   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2481   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2482       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2483   // Ignore host functions during device analyzis.
2484   if (LangOpts.OpenMPIsDevice &&
2485       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2486     return;
2487   // Ignore nohost functions during host analyzis.
2488   if (!LangOpts.OpenMPIsDevice && DevTy &&
2489       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2490     return;
2491   const FunctionDecl *FD = Callee->getMostRecentDecl();
2492   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2493   if (LangOpts.OpenMPIsDevice && DevTy &&
2494       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2495     // Diagnose host function called during device codegen.
2496     StringRef HostDevTy =
2497         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2498     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2499     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2500          diag::note_omp_marked_device_type_here)
2501         << HostDevTy;
2502     return;
2503   }
2504   if (!LangOpts.OpenMPIsDevice && DevTy &&
2505       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2506     // Diagnose nohost function called during host codegen.
2507     StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2508         OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2509     Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2510     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2511          diag::note_omp_marked_device_type_here)
2512         << NoHostDevTy;
2513   }
2514 }
2515 
2516 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2517                                const DeclarationNameInfo &DirName,
2518                                Scope *CurScope, SourceLocation Loc) {
2519   DSAStack->push(DKind, DirName, CurScope, Loc);
2520   PushExpressionEvaluationContext(
2521       ExpressionEvaluationContext::PotentiallyEvaluated);
2522 }
2523 
2524 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2525   DSAStack->setClauseParsingMode(K);
2526 }
2527 
2528 void Sema::EndOpenMPClause() {
2529   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2530   CleanupVarDeclMarking();
2531 }
2532 
2533 static std::pair<ValueDecl *, bool>
2534 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2535                SourceRange &ERange, bool AllowArraySection = false);
2536 
2537 /// Check consistency of the reduction clauses.
2538 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2539                                   ArrayRef<OMPClause *> Clauses) {
2540   bool InscanFound = false;
2541   SourceLocation InscanLoc;
2542   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2543   // A reduction clause without the inscan reduction-modifier may not appear on
2544   // a construct on which a reduction clause with the inscan reduction-modifier
2545   // appears.
2546   for (OMPClause *C : Clauses) {
2547     if (C->getClauseKind() != OMPC_reduction)
2548       continue;
2549     auto *RC = cast<OMPReductionClause>(C);
2550     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2551       InscanFound = true;
2552       InscanLoc = RC->getModifierLoc();
2553       continue;
2554     }
2555     if (RC->getModifier() == OMPC_REDUCTION_task) {
2556       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2557       // A reduction clause with the task reduction-modifier may only appear on
2558       // a parallel construct, a worksharing construct or a combined or
2559       // composite construct for which any of the aforementioned constructs is a
2560       // constituent construct and simd or loop are not constituent constructs.
2561       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2562       if (!(isOpenMPParallelDirective(CurDir) ||
2563             isOpenMPWorksharingDirective(CurDir)) ||
2564           isOpenMPSimdDirective(CurDir))
2565         S.Diag(RC->getModifierLoc(),
2566                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2567       continue;
2568     }
2569   }
2570   if (InscanFound) {
2571     for (OMPClause *C : Clauses) {
2572       if (C->getClauseKind() != OMPC_reduction)
2573         continue;
2574       auto *RC = cast<OMPReductionClause>(C);
2575       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2576         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2577                    ? RC->getBeginLoc()
2578                    : RC->getModifierLoc(),
2579                diag::err_omp_inscan_reduction_expected);
2580         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2581         continue;
2582       }
2583       for (Expr *Ref : RC->varlists()) {
2584         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2585         SourceLocation ELoc;
2586         SourceRange ERange;
2587         Expr *SimpleRefExpr = Ref;
2588         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2589                                   /*AllowArraySection=*/true);
2590         ValueDecl *D = Res.first;
2591         if (!D)
2592           continue;
2593         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2594           S.Diag(Ref->getExprLoc(),
2595                  diag::err_omp_reduction_not_inclusive_exclusive)
2596               << Ref->getSourceRange();
2597         }
2598       }
2599     }
2600   }
2601 }
2602 
2603 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2604                                  ArrayRef<OMPClause *> Clauses);
2605 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2606                                  bool WithInit);
2607 
2608 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2609                               const ValueDecl *D,
2610                               const DSAStackTy::DSAVarData &DVar,
2611                               bool IsLoopIterVar = false);
2612 
2613 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2614   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2615   //  A variable of class type (or array thereof) that appears in a lastprivate
2616   //  clause requires an accessible, unambiguous default constructor for the
2617   //  class type, unless the list item is also specified in a firstprivate
2618   //  clause.
2619   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2620     for (OMPClause *C : D->clauses()) {
2621       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2622         SmallVector<Expr *, 8> PrivateCopies;
2623         for (Expr *DE : Clause->varlists()) {
2624           if (DE->isValueDependent() || DE->isTypeDependent()) {
2625             PrivateCopies.push_back(nullptr);
2626             continue;
2627           }
2628           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2629           auto *VD = cast<VarDecl>(DRE->getDecl());
2630           QualType Type = VD->getType().getNonReferenceType();
2631           const DSAStackTy::DSAVarData DVar =
2632               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2633           if (DVar.CKind == OMPC_lastprivate) {
2634             // Generate helper private variable and initialize it with the
2635             // default value. The address of the original variable is replaced
2636             // by the address of the new private variable in CodeGen. This new
2637             // variable is not added to IdResolver, so the code in the OpenMP
2638             // region uses original variable for proper diagnostics.
2639             VarDecl *VDPrivate = buildVarDecl(
2640                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2641                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2642             ActOnUninitializedDecl(VDPrivate);
2643             if (VDPrivate->isInvalidDecl()) {
2644               PrivateCopies.push_back(nullptr);
2645               continue;
2646             }
2647             PrivateCopies.push_back(buildDeclRefExpr(
2648                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2649           } else {
2650             // The variable is also a firstprivate, so initialization sequence
2651             // for private copy is generated already.
2652             PrivateCopies.push_back(nullptr);
2653           }
2654         }
2655         Clause->setPrivateCopies(PrivateCopies);
2656         continue;
2657       }
2658       // Finalize nontemporal clause by handling private copies, if any.
2659       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2660         SmallVector<Expr *, 8> PrivateRefs;
2661         for (Expr *RefExpr : Clause->varlists()) {
2662           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2663           SourceLocation ELoc;
2664           SourceRange ERange;
2665           Expr *SimpleRefExpr = RefExpr;
2666           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2667           if (Res.second)
2668             // It will be analyzed later.
2669             PrivateRefs.push_back(RefExpr);
2670           ValueDecl *D = Res.first;
2671           if (!D)
2672             continue;
2673 
2674           const DSAStackTy::DSAVarData DVar =
2675               DSAStack->getTopDSA(D, /*FromParent=*/false);
2676           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2677                                                  : SimpleRefExpr);
2678         }
2679         Clause->setPrivateRefs(PrivateRefs);
2680         continue;
2681       }
2682       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2683         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2684           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2685           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2686           if (!DRE)
2687             continue;
2688           ValueDecl *VD = DRE->getDecl();
2689           if (!VD || !isa<VarDecl>(VD))
2690             continue;
2691           DSAStackTy::DSAVarData DVar =
2692               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2693           // OpenMP [2.12.5, target Construct]
2694           // Memory allocators that appear in a uses_allocators clause cannot
2695           // appear in other data-sharing attribute clauses or data-mapping
2696           // attribute clauses in the same construct.
2697           Expr *MapExpr = nullptr;
2698           if (DVar.RefExpr ||
2699               DSAStack->checkMappableExprComponentListsForDecl(
2700                   VD, /*CurrentRegionOnly=*/true,
2701                   [VD, &MapExpr](
2702                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2703                           MapExprComponents,
2704                       OpenMPClauseKind C) {
2705                     auto MI = MapExprComponents.rbegin();
2706                     auto ME = MapExprComponents.rend();
2707                     if (MI != ME &&
2708                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2709                             VD->getCanonicalDecl()) {
2710                       MapExpr = MI->getAssociatedExpression();
2711                       return true;
2712                     }
2713                     return false;
2714                   })) {
2715             Diag(D.Allocator->getExprLoc(),
2716                  diag::err_omp_allocator_used_in_clauses)
2717                 << D.Allocator->getSourceRange();
2718             if (DVar.RefExpr)
2719               reportOriginalDsa(*this, DSAStack, VD, DVar);
2720             else
2721               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2722                   << MapExpr->getSourceRange();
2723           }
2724         }
2725         continue;
2726       }
2727     }
2728     // Check allocate clauses.
2729     if (!CurContext->isDependentContext())
2730       checkAllocateClauses(*this, DSAStack, D->clauses());
2731     checkReductionClauses(*this, DSAStack, D->clauses());
2732   }
2733 
2734   DSAStack->pop();
2735   DiscardCleanupsInEvaluationContext();
2736   PopExpressionEvaluationContext();
2737 }
2738 
2739 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2740                                      Expr *NumIterations, Sema &SemaRef,
2741                                      Scope *S, DSAStackTy *Stack);
2742 
2743 namespace {
2744 
2745 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2746 private:
2747   Sema &SemaRef;
2748 
2749 public:
2750   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2751   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2752     NamedDecl *ND = Candidate.getCorrectionDecl();
2753     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2754       return VD->hasGlobalStorage() &&
2755              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2756                                    SemaRef.getCurScope());
2757     }
2758     return false;
2759   }
2760 
2761   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2762     return std::make_unique<VarDeclFilterCCC>(*this);
2763   }
2764 };
2765 
2766 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2767 private:
2768   Sema &SemaRef;
2769 
2770 public:
2771   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2772   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2773     NamedDecl *ND = Candidate.getCorrectionDecl();
2774     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2775                isa<FunctionDecl>(ND))) {
2776       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2777                                    SemaRef.getCurScope());
2778     }
2779     return false;
2780   }
2781 
2782   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2783     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2784   }
2785 };
2786 
2787 } // namespace
2788 
2789 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2790                                          CXXScopeSpec &ScopeSpec,
2791                                          const DeclarationNameInfo &Id,
2792                                          OpenMPDirectiveKind Kind) {
2793   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2794   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2795 
2796   if (Lookup.isAmbiguous())
2797     return ExprError();
2798 
2799   VarDecl *VD;
2800   if (!Lookup.isSingleResult()) {
2801     VarDeclFilterCCC CCC(*this);
2802     if (TypoCorrection Corrected =
2803             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2804                         CTK_ErrorRecovery)) {
2805       diagnoseTypo(Corrected,
2806                    PDiag(Lookup.empty()
2807                              ? diag::err_undeclared_var_use_suggest
2808                              : diag::err_omp_expected_var_arg_suggest)
2809                        << Id.getName());
2810       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2811     } else {
2812       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2813                                        : diag::err_omp_expected_var_arg)
2814           << Id.getName();
2815       return ExprError();
2816     }
2817   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2818     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2819     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2820     return ExprError();
2821   }
2822   Lookup.suppressDiagnostics();
2823 
2824   // OpenMP [2.9.2, Syntax, C/C++]
2825   //   Variables must be file-scope, namespace-scope, or static block-scope.
2826   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2827     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2828         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2829     bool IsDecl =
2830         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2831     Diag(VD->getLocation(),
2832          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2833         << VD;
2834     return ExprError();
2835   }
2836 
2837   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2838   NamedDecl *ND = CanonicalVD;
2839   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2840   //   A threadprivate directive for file-scope variables must appear outside
2841   //   any definition or declaration.
2842   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2843       !getCurLexicalContext()->isTranslationUnit()) {
2844     Diag(Id.getLoc(), diag::err_omp_var_scope)
2845         << getOpenMPDirectiveName(Kind) << VD;
2846     bool IsDecl =
2847         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2848     Diag(VD->getLocation(),
2849          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2850         << VD;
2851     return ExprError();
2852   }
2853   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2854   //   A threadprivate directive for static class member variables must appear
2855   //   in the class definition, in the same scope in which the member
2856   //   variables are declared.
2857   if (CanonicalVD->isStaticDataMember() &&
2858       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2859     Diag(Id.getLoc(), diag::err_omp_var_scope)
2860         << getOpenMPDirectiveName(Kind) << VD;
2861     bool IsDecl =
2862         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2863     Diag(VD->getLocation(),
2864          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2865         << VD;
2866     return ExprError();
2867   }
2868   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2869   //   A threadprivate directive for namespace-scope variables must appear
2870   //   outside any definition or declaration other than the namespace
2871   //   definition itself.
2872   if (CanonicalVD->getDeclContext()->isNamespace() &&
2873       (!getCurLexicalContext()->isFileContext() ||
2874        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2875     Diag(Id.getLoc(), diag::err_omp_var_scope)
2876         << getOpenMPDirectiveName(Kind) << VD;
2877     bool IsDecl =
2878         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2879     Diag(VD->getLocation(),
2880          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2881         << VD;
2882     return ExprError();
2883   }
2884   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2885   //   A threadprivate directive for static block-scope variables must appear
2886   //   in the scope of the variable and not in a nested scope.
2887   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2888       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2889     Diag(Id.getLoc(), diag::err_omp_var_scope)
2890         << getOpenMPDirectiveName(Kind) << VD;
2891     bool IsDecl =
2892         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2893     Diag(VD->getLocation(),
2894          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2895         << VD;
2896     return ExprError();
2897   }
2898 
2899   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2900   //   A threadprivate directive must lexically precede all references to any
2901   //   of the variables in its list.
2902   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2903       !DSAStack->isThreadPrivate(VD)) {
2904     Diag(Id.getLoc(), diag::err_omp_var_used)
2905         << getOpenMPDirectiveName(Kind) << VD;
2906     return ExprError();
2907   }
2908 
2909   QualType ExprType = VD->getType().getNonReferenceType();
2910   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2911                              SourceLocation(), VD,
2912                              /*RefersToEnclosingVariableOrCapture=*/false,
2913                              Id.getLoc(), ExprType, VK_LValue);
2914 }
2915 
2916 Sema::DeclGroupPtrTy
2917 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2918                                         ArrayRef<Expr *> VarList) {
2919   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2920     CurContext->addDecl(D);
2921     return DeclGroupPtrTy::make(DeclGroupRef(D));
2922   }
2923   return nullptr;
2924 }
2925 
2926 namespace {
2927 class LocalVarRefChecker final
2928     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2929   Sema &SemaRef;
2930 
2931 public:
2932   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2933     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2934       if (VD->hasLocalStorage()) {
2935         SemaRef.Diag(E->getBeginLoc(),
2936                      diag::err_omp_local_var_in_threadprivate_init)
2937             << E->getSourceRange();
2938         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2939             << VD << VD->getSourceRange();
2940         return true;
2941       }
2942     }
2943     return false;
2944   }
2945   bool VisitStmt(const Stmt *S) {
2946     for (const Stmt *Child : S->children()) {
2947       if (Child && Visit(Child))
2948         return true;
2949     }
2950     return false;
2951   }
2952   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2953 };
2954 } // namespace
2955 
2956 OMPThreadPrivateDecl *
2957 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2958   SmallVector<Expr *, 8> Vars;
2959   for (Expr *RefExpr : VarList) {
2960     auto *DE = cast<DeclRefExpr>(RefExpr);
2961     auto *VD = cast<VarDecl>(DE->getDecl());
2962     SourceLocation ILoc = DE->getExprLoc();
2963 
2964     // Mark variable as used.
2965     VD->setReferenced();
2966     VD->markUsed(Context);
2967 
2968     QualType QType = VD->getType();
2969     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2970       // It will be analyzed later.
2971       Vars.push_back(DE);
2972       continue;
2973     }
2974 
2975     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2976     //   A threadprivate variable must not have an incomplete type.
2977     if (RequireCompleteType(ILoc, VD->getType(),
2978                             diag::err_omp_threadprivate_incomplete_type)) {
2979       continue;
2980     }
2981 
2982     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2983     //   A threadprivate variable must not have a reference type.
2984     if (VD->getType()->isReferenceType()) {
2985       Diag(ILoc, diag::err_omp_ref_type_arg)
2986           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2987       bool IsDecl =
2988           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2989       Diag(VD->getLocation(),
2990            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2991           << VD;
2992       continue;
2993     }
2994 
2995     // Check if this is a TLS variable. If TLS is not being supported, produce
2996     // the corresponding diagnostic.
2997     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2998          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2999            getLangOpts().OpenMPUseTLS &&
3000            getASTContext().getTargetInfo().isTLSSupported())) ||
3001         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3002          !VD->isLocalVarDecl())) {
3003       Diag(ILoc, diag::err_omp_var_thread_local)
3004           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3005       bool IsDecl =
3006           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3007       Diag(VD->getLocation(),
3008            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3009           << VD;
3010       continue;
3011     }
3012 
3013     // Check if initial value of threadprivate variable reference variable with
3014     // local storage (it is not supported by runtime).
3015     if (const Expr *Init = VD->getAnyInitializer()) {
3016       LocalVarRefChecker Checker(*this);
3017       if (Checker.Visit(Init))
3018         continue;
3019     }
3020 
3021     Vars.push_back(RefExpr);
3022     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3023     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3024         Context, SourceRange(Loc, Loc)));
3025     if (ASTMutationListener *ML = Context.getASTMutationListener())
3026       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3027   }
3028   OMPThreadPrivateDecl *D = nullptr;
3029   if (!Vars.empty()) {
3030     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3031                                      Vars);
3032     D->setAccess(AS_public);
3033   }
3034   return D;
3035 }
3036 
3037 static OMPAllocateDeclAttr::AllocatorTypeTy
3038 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3039   if (!Allocator)
3040     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3041   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3042       Allocator->isInstantiationDependent() ||
3043       Allocator->containsUnexpandedParameterPack())
3044     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3045   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3046   const Expr *AE = Allocator->IgnoreParenImpCasts();
3047   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3048     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3049     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3050     llvm::FoldingSetNodeID AEId, DAEId;
3051     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3052     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3053     if (AEId == DAEId) {
3054       AllocatorKindRes = AllocatorKind;
3055       break;
3056     }
3057   }
3058   return AllocatorKindRes;
3059 }
3060 
3061 static bool checkPreviousOMPAllocateAttribute(
3062     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3063     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3064   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3065     return false;
3066   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3067   Expr *PrevAllocator = A->getAllocator();
3068   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3069       getAllocatorKind(S, Stack, PrevAllocator);
3070   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3071   if (AllocatorsMatch &&
3072       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3073       Allocator && PrevAllocator) {
3074     const Expr *AE = Allocator->IgnoreParenImpCasts();
3075     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3076     llvm::FoldingSetNodeID AEId, PAEId;
3077     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3078     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3079     AllocatorsMatch = AEId == PAEId;
3080   }
3081   if (!AllocatorsMatch) {
3082     SmallString<256> AllocatorBuffer;
3083     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3084     if (Allocator)
3085       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3086     SmallString<256> PrevAllocatorBuffer;
3087     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3088     if (PrevAllocator)
3089       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3090                                  S.getPrintingPolicy());
3091 
3092     SourceLocation AllocatorLoc =
3093         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3094     SourceRange AllocatorRange =
3095         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3096     SourceLocation PrevAllocatorLoc =
3097         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3098     SourceRange PrevAllocatorRange =
3099         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3100     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3101         << (Allocator ? 1 : 0) << AllocatorStream.str()
3102         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3103         << AllocatorRange;
3104     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3105         << PrevAllocatorRange;
3106     return true;
3107   }
3108   return false;
3109 }
3110 
3111 static void
3112 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3113                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3114                           Expr *Allocator, Expr *Alignment, SourceRange SR) {
3115   if (VD->hasAttr<OMPAllocateDeclAttr>())
3116     return;
3117   if (Alignment &&
3118       (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3119        Alignment->isInstantiationDependent() ||
3120        Alignment->containsUnexpandedParameterPack()))
3121     // Apply later when we have a usable value.
3122     return;
3123   if (Allocator &&
3124       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3125        Allocator->isInstantiationDependent() ||
3126        Allocator->containsUnexpandedParameterPack()))
3127     return;
3128   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3129                                                 Allocator, Alignment, SR);
3130   VD->addAttr(A);
3131   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3132     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3133 }
3134 
3135 Sema::DeclGroupPtrTy
3136 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
3137                                    ArrayRef<OMPClause *> Clauses,
3138                                    DeclContext *Owner) {
3139   assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3140   Expr *Alignment = nullptr;
3141   Expr *Allocator = nullptr;
3142   if (Clauses.empty()) {
3143     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3144     // allocate directives that appear in a target region must specify an
3145     // allocator clause unless a requires directive with the dynamic_allocators
3146     // clause is present in the same compilation unit.
3147     if (LangOpts.OpenMPIsDevice &&
3148         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3149       targetDiag(Loc, diag::err_expected_allocator_clause);
3150   } else {
3151     for (const OMPClause *C : Clauses)
3152       if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3153         Allocator = AC->getAllocator();
3154       else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3155         Alignment = AC->getAlignment();
3156       else
3157         llvm_unreachable("Unexpected clause on allocate directive");
3158   }
3159   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3160       getAllocatorKind(*this, DSAStack, Allocator);
3161   SmallVector<Expr *, 8> Vars;
3162   for (Expr *RefExpr : VarList) {
3163     auto *DE = cast<DeclRefExpr>(RefExpr);
3164     auto *VD = cast<VarDecl>(DE->getDecl());
3165 
3166     // Check if this is a TLS variable or global register.
3167     if (VD->getTLSKind() != VarDecl::TLS_None ||
3168         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3169         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3170          !VD->isLocalVarDecl()))
3171       continue;
3172 
3173     // If the used several times in the allocate directive, the same allocator
3174     // must be used.
3175     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3176                                           AllocatorKind, Allocator))
3177       continue;
3178 
3179     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3180     // If a list item has a static storage type, the allocator expression in the
3181     // allocator clause must be a constant expression that evaluates to one of
3182     // the predefined memory allocator values.
3183     if (Allocator && VD->hasGlobalStorage()) {
3184       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3185         Diag(Allocator->getExprLoc(),
3186              diag::err_omp_expected_predefined_allocator)
3187             << Allocator->getSourceRange();
3188         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3189                       VarDecl::DeclarationOnly;
3190         Diag(VD->getLocation(),
3191              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3192             << VD;
3193         continue;
3194       }
3195     }
3196 
3197     Vars.push_back(RefExpr);
3198     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
3199                               DE->getSourceRange());
3200   }
3201   if (Vars.empty())
3202     return nullptr;
3203   if (!Owner)
3204     Owner = getCurLexicalContext();
3205   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3206   D->setAccess(AS_public);
3207   Owner->addDecl(D);
3208   return DeclGroupPtrTy::make(DeclGroupRef(D));
3209 }
3210 
3211 Sema::DeclGroupPtrTy
3212 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3213                                    ArrayRef<OMPClause *> ClauseList) {
3214   OMPRequiresDecl *D = nullptr;
3215   if (!CurContext->isFileContext()) {
3216     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3217   } else {
3218     D = CheckOMPRequiresDecl(Loc, ClauseList);
3219     if (D) {
3220       CurContext->addDecl(D);
3221       DSAStack->addRequiresDecl(D);
3222     }
3223   }
3224   return DeclGroupPtrTy::make(DeclGroupRef(D));
3225 }
3226 
3227 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3228                                        OpenMPDirectiveKind DKind,
3229                                        ArrayRef<std::string> Assumptions,
3230                                        bool SkippedClauses) {
3231   if (!SkippedClauses && Assumptions.empty())
3232     Diag(Loc, diag::err_omp_no_clause_for_directive)
3233         << llvm::omp::getAllAssumeClauseOptions()
3234         << llvm::omp::getOpenMPDirectiveName(DKind);
3235 
3236   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3237   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3238     OMPAssumeScoped.push_back(AA);
3239     return;
3240   }
3241 
3242   // Global assumes without assumption clauses are ignored.
3243   if (Assumptions.empty())
3244     return;
3245 
3246   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3247          "Unexpected omp assumption directive!");
3248   OMPAssumeGlobal.push_back(AA);
3249 
3250   // The OMPAssumeGlobal scope above will take care of new declarations but
3251   // we also want to apply the assumption to existing ones, e.g., to
3252   // declarations in included headers. To this end, we traverse all existing
3253   // declaration contexts and annotate function declarations here.
3254   SmallVector<DeclContext *, 8> DeclContexts;
3255   auto *Ctx = CurContext;
3256   while (Ctx->getLexicalParent())
3257     Ctx = Ctx->getLexicalParent();
3258   DeclContexts.push_back(Ctx);
3259   while (!DeclContexts.empty()) {
3260     DeclContext *DC = DeclContexts.pop_back_val();
3261     for (auto *SubDC : DC->decls()) {
3262       if (SubDC->isInvalidDecl())
3263         continue;
3264       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3265         DeclContexts.push_back(CTD->getTemplatedDecl());
3266         for (auto *S : CTD->specializations())
3267           DeclContexts.push_back(S);
3268         continue;
3269       }
3270       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3271         DeclContexts.push_back(DC);
3272       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3273         F->addAttr(AA);
3274         continue;
3275       }
3276     }
3277   }
3278 }
3279 
3280 void Sema::ActOnOpenMPEndAssumesDirective() {
3281   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3282   OMPAssumeScoped.pop_back();
3283 }
3284 
3285 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3286                                             ArrayRef<OMPClause *> ClauseList) {
3287   /// For target specific clauses, the requires directive cannot be
3288   /// specified after the handling of any of the target regions in the
3289   /// current compilation unit.
3290   ArrayRef<SourceLocation> TargetLocations =
3291       DSAStack->getEncounteredTargetLocs();
3292   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3293   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3294     for (const OMPClause *CNew : ClauseList) {
3295       // Check if any of the requires clauses affect target regions.
3296       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3297           isa<OMPUnifiedAddressClause>(CNew) ||
3298           isa<OMPReverseOffloadClause>(CNew) ||
3299           isa<OMPDynamicAllocatorsClause>(CNew)) {
3300         Diag(Loc, diag::err_omp_directive_before_requires)
3301             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3302         for (SourceLocation TargetLoc : TargetLocations) {
3303           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3304               << "target";
3305         }
3306       } else if (!AtomicLoc.isInvalid() &&
3307                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3308         Diag(Loc, diag::err_omp_directive_before_requires)
3309             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3310         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3311             << "atomic";
3312       }
3313     }
3314   }
3315 
3316   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3317     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3318                                    ClauseList);
3319   return nullptr;
3320 }
3321 
3322 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3323                               const ValueDecl *D,
3324                               const DSAStackTy::DSAVarData &DVar,
3325                               bool IsLoopIterVar) {
3326   if (DVar.RefExpr) {
3327     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3328         << getOpenMPClauseName(DVar.CKind);
3329     return;
3330   }
3331   enum {
3332     PDSA_StaticMemberShared,
3333     PDSA_StaticLocalVarShared,
3334     PDSA_LoopIterVarPrivate,
3335     PDSA_LoopIterVarLinear,
3336     PDSA_LoopIterVarLastprivate,
3337     PDSA_ConstVarShared,
3338     PDSA_GlobalVarShared,
3339     PDSA_TaskVarFirstprivate,
3340     PDSA_LocalVarPrivate,
3341     PDSA_Implicit
3342   } Reason = PDSA_Implicit;
3343   bool ReportHint = false;
3344   auto ReportLoc = D->getLocation();
3345   auto *VD = dyn_cast<VarDecl>(D);
3346   if (IsLoopIterVar) {
3347     if (DVar.CKind == OMPC_private)
3348       Reason = PDSA_LoopIterVarPrivate;
3349     else if (DVar.CKind == OMPC_lastprivate)
3350       Reason = PDSA_LoopIterVarLastprivate;
3351     else
3352       Reason = PDSA_LoopIterVarLinear;
3353   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3354              DVar.CKind == OMPC_firstprivate) {
3355     Reason = PDSA_TaskVarFirstprivate;
3356     ReportLoc = DVar.ImplicitDSALoc;
3357   } else if (VD && VD->isStaticLocal())
3358     Reason = PDSA_StaticLocalVarShared;
3359   else if (VD && VD->isStaticDataMember())
3360     Reason = PDSA_StaticMemberShared;
3361   else if (VD && VD->isFileVarDecl())
3362     Reason = PDSA_GlobalVarShared;
3363   else if (D->getType().isConstant(SemaRef.getASTContext()))
3364     Reason = PDSA_ConstVarShared;
3365   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3366     ReportHint = true;
3367     Reason = PDSA_LocalVarPrivate;
3368   }
3369   if (Reason != PDSA_Implicit) {
3370     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3371         << Reason << ReportHint
3372         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3373   } else if (DVar.ImplicitDSALoc.isValid()) {
3374     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3375         << getOpenMPClauseName(DVar.CKind);
3376   }
3377 }
3378 
3379 static OpenMPMapClauseKind
3380 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3381                              bool IsAggregateOrDeclareTarget) {
3382   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3383   switch (M) {
3384   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3385     Kind = OMPC_MAP_alloc;
3386     break;
3387   case OMPC_DEFAULTMAP_MODIFIER_to:
3388     Kind = OMPC_MAP_to;
3389     break;
3390   case OMPC_DEFAULTMAP_MODIFIER_from:
3391     Kind = OMPC_MAP_from;
3392     break;
3393   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3394     Kind = OMPC_MAP_tofrom;
3395     break;
3396   case OMPC_DEFAULTMAP_MODIFIER_present:
3397     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3398     // If implicit-behavior is present, each variable referenced in the
3399     // construct in the category specified by variable-category is treated as if
3400     // it had been listed in a map clause with the map-type of alloc and
3401     // map-type-modifier of present.
3402     Kind = OMPC_MAP_alloc;
3403     break;
3404   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3405   case OMPC_DEFAULTMAP_MODIFIER_last:
3406     llvm_unreachable("Unexpected defaultmap implicit behavior");
3407   case OMPC_DEFAULTMAP_MODIFIER_none:
3408   case OMPC_DEFAULTMAP_MODIFIER_default:
3409   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3410     // IsAggregateOrDeclareTarget could be true if:
3411     // 1. the implicit behavior for aggregate is tofrom
3412     // 2. it's a declare target link
3413     if (IsAggregateOrDeclareTarget) {
3414       Kind = OMPC_MAP_tofrom;
3415       break;
3416     }
3417     llvm_unreachable("Unexpected defaultmap implicit behavior");
3418   }
3419   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3420   return Kind;
3421 }
3422 
3423 namespace {
3424 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3425   DSAStackTy *Stack;
3426   Sema &SemaRef;
3427   bool ErrorFound = false;
3428   bool TryCaptureCXXThisMembers = false;
3429   CapturedStmt *CS = nullptr;
3430   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3431   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3432   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3433   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3434       ImplicitMapModifier[DefaultmapKindNum];
3435   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3436   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3437 
3438   void VisitSubCaptures(OMPExecutableDirective *S) {
3439     // Check implicitly captured variables.
3440     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3441       return;
3442     if (S->getDirectiveKind() == OMPD_atomic ||
3443         S->getDirectiveKind() == OMPD_critical ||
3444         S->getDirectiveKind() == OMPD_section ||
3445         S->getDirectiveKind() == OMPD_master ||
3446         S->getDirectiveKind() == OMPD_masked ||
3447         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3448       Visit(S->getAssociatedStmt());
3449       return;
3450     }
3451     visitSubCaptures(S->getInnermostCapturedStmt());
3452     // Try to capture inner this->member references to generate correct mappings
3453     // and diagnostics.
3454     if (TryCaptureCXXThisMembers ||
3455         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3456          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3457                       [](const CapturedStmt::Capture &C) {
3458                         return C.capturesThis();
3459                       }))) {
3460       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3461       TryCaptureCXXThisMembers = true;
3462       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3463       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3464     }
3465     // In tasks firstprivates are not captured anymore, need to analyze them
3466     // explicitly.
3467     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3468         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3469       for (OMPClause *C : S->clauses())
3470         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3471           for (Expr *Ref : FC->varlists())
3472             Visit(Ref);
3473         }
3474     }
3475   }
3476 
3477 public:
3478   void VisitDeclRefExpr(DeclRefExpr *E) {
3479     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3480         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3481         E->isInstantiationDependent())
3482       return;
3483     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3484       // Check the datasharing rules for the expressions in the clauses.
3485       if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
3486                   !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
3487         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3488           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3489             Visit(CED->getInit());
3490             return;
3491           }
3492       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3493         // Do not analyze internal variables and do not enclose them into
3494         // implicit clauses.
3495         return;
3496       VD = VD->getCanonicalDecl();
3497       // Skip internally declared variables.
3498       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3499           !Stack->isImplicitTaskFirstprivate(VD))
3500         return;
3501       // Skip allocators in uses_allocators clauses.
3502       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3503         return;
3504 
3505       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3506       // Check if the variable has explicit DSA set and stop analysis if it so.
3507       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3508         return;
3509 
3510       // Skip internally declared static variables.
3511       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3512           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3513       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3514           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3515            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3516           !Stack->isImplicitTaskFirstprivate(VD))
3517         return;
3518 
3519       SourceLocation ELoc = E->getExprLoc();
3520       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3521       // The default(none) clause requires that each variable that is referenced
3522       // in the construct, and does not have a predetermined data-sharing
3523       // attribute, must have its data-sharing attribute explicitly determined
3524       // by being listed in a data-sharing attribute clause.
3525       if (DVar.CKind == OMPC_unknown &&
3526           (Stack->getDefaultDSA() == DSA_none ||
3527            Stack->getDefaultDSA() == DSA_firstprivate) &&
3528           isImplicitOrExplicitTaskingRegion(DKind) &&
3529           VarsWithInheritedDSA.count(VD) == 0) {
3530         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3531         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3532           DSAStackTy::DSAVarData DVar =
3533               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3534           InheritedDSA = DVar.CKind == OMPC_unknown;
3535         }
3536         if (InheritedDSA)
3537           VarsWithInheritedDSA[VD] = E;
3538         return;
3539       }
3540 
3541       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3542       // If implicit-behavior is none, each variable referenced in the
3543       // construct that does not have a predetermined data-sharing attribute
3544       // and does not appear in a to or link clause on a declare target
3545       // directive must be listed in a data-mapping attribute clause, a
3546       // data-haring attribute clause (including a data-sharing attribute
3547       // clause on a combined construct where target. is one of the
3548       // constituent constructs), or an is_device_ptr clause.
3549       OpenMPDefaultmapClauseKind ClauseKind =
3550           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3551       if (SemaRef.getLangOpts().OpenMP >= 50) {
3552         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3553                               OMPC_DEFAULTMAP_MODIFIER_none;
3554         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3555             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3556           // Only check for data-mapping attribute and is_device_ptr here
3557           // since we have already make sure that the declaration does not
3558           // have a data-sharing attribute above
3559           if (!Stack->checkMappableExprComponentListsForDecl(
3560                   VD, /*CurrentRegionOnly=*/true,
3561                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3562                            MapExprComponents,
3563                        OpenMPClauseKind) {
3564                     auto MI = MapExprComponents.rbegin();
3565                     auto ME = MapExprComponents.rend();
3566                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3567                   })) {
3568             VarsWithInheritedDSA[VD] = E;
3569             return;
3570           }
3571         }
3572       }
3573       if (SemaRef.getLangOpts().OpenMP > 50) {
3574         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3575                                  OMPC_DEFAULTMAP_MODIFIER_present;
3576         if (IsModifierPresent) {
3577           if (llvm::find(ImplicitMapModifier[ClauseKind],
3578                          OMPC_MAP_MODIFIER_present) ==
3579               std::end(ImplicitMapModifier[ClauseKind])) {
3580             ImplicitMapModifier[ClauseKind].push_back(
3581                 OMPC_MAP_MODIFIER_present);
3582           }
3583         }
3584       }
3585 
3586       if (isOpenMPTargetExecutionDirective(DKind) &&
3587           !Stack->isLoopControlVariable(VD).first) {
3588         if (!Stack->checkMappableExprComponentListsForDecl(
3589                 VD, /*CurrentRegionOnly=*/true,
3590                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3591                            StackComponents,
3592                        OpenMPClauseKind) {
3593                   if (SemaRef.LangOpts.OpenMP >= 50)
3594                     return !StackComponents.empty();
3595                   // Variable is used if it has been marked as an array, array
3596                   // section, array shaping or the variable iself.
3597                   return StackComponents.size() == 1 ||
3598                          std::all_of(
3599                              std::next(StackComponents.rbegin()),
3600                              StackComponents.rend(),
3601                              [](const OMPClauseMappableExprCommon::
3602                                     MappableComponent &MC) {
3603                                return MC.getAssociatedDeclaration() ==
3604                                           nullptr &&
3605                                       (isa<OMPArraySectionExpr>(
3606                                            MC.getAssociatedExpression()) ||
3607                                        isa<OMPArrayShapingExpr>(
3608                                            MC.getAssociatedExpression()) ||
3609                                        isa<ArraySubscriptExpr>(
3610                                            MC.getAssociatedExpression()));
3611                              });
3612                 })) {
3613           bool IsFirstprivate = false;
3614           // By default lambdas are captured as firstprivates.
3615           if (const auto *RD =
3616                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3617             IsFirstprivate = RD->isLambda();
3618           IsFirstprivate =
3619               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3620           if (IsFirstprivate) {
3621             ImplicitFirstprivate.emplace_back(E);
3622           } else {
3623             OpenMPDefaultmapClauseModifier M =
3624                 Stack->getDefaultmapModifier(ClauseKind);
3625             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3626                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3627             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3628           }
3629           return;
3630         }
3631       }
3632 
3633       // OpenMP [2.9.3.6, Restrictions, p.2]
3634       //  A list item that appears in a reduction clause of the innermost
3635       //  enclosing worksharing or parallel construct may not be accessed in an
3636       //  explicit task.
3637       DVar = Stack->hasInnermostDSA(
3638           VD,
3639           [](OpenMPClauseKind C, bool AppliedToPointee) {
3640             return C == OMPC_reduction && !AppliedToPointee;
3641           },
3642           [](OpenMPDirectiveKind K) {
3643             return isOpenMPParallelDirective(K) ||
3644                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3645           },
3646           /*FromParent=*/true);
3647       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3648         ErrorFound = true;
3649         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3650         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3651         return;
3652       }
3653 
3654       // Define implicit data-sharing attributes for task.
3655       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3656       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3657            (Stack->getDefaultDSA() == DSA_firstprivate &&
3658             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3659           !Stack->isLoopControlVariable(VD).first) {
3660         ImplicitFirstprivate.push_back(E);
3661         return;
3662       }
3663 
3664       // Store implicitly used globals with declare target link for parent
3665       // target.
3666       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3667           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3668         Stack->addToParentTargetRegionLinkGlobals(E);
3669         return;
3670       }
3671     }
3672   }
3673   void VisitMemberExpr(MemberExpr *E) {
3674     if (E->isTypeDependent() || E->isValueDependent() ||
3675         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3676       return;
3677     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3678     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3679     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3680       if (!FD)
3681         return;
3682       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3683       // Check if the variable has explicit DSA set and stop analysis if it
3684       // so.
3685       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3686         return;
3687 
3688       if (isOpenMPTargetExecutionDirective(DKind) &&
3689           !Stack->isLoopControlVariable(FD).first &&
3690           !Stack->checkMappableExprComponentListsForDecl(
3691               FD, /*CurrentRegionOnly=*/true,
3692               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3693                      StackComponents,
3694                  OpenMPClauseKind) {
3695                 return isa<CXXThisExpr>(
3696                     cast<MemberExpr>(
3697                         StackComponents.back().getAssociatedExpression())
3698                         ->getBase()
3699                         ->IgnoreParens());
3700               })) {
3701         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3702         //  A bit-field cannot appear in a map clause.
3703         //
3704         if (FD->isBitField())
3705           return;
3706 
3707         // Check to see if the member expression is referencing a class that
3708         // has already been explicitly mapped
3709         if (Stack->isClassPreviouslyMapped(TE->getType()))
3710           return;
3711 
3712         OpenMPDefaultmapClauseModifier Modifier =
3713             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3714         OpenMPDefaultmapClauseKind ClauseKind =
3715             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3716         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3717             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3718         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3719         return;
3720       }
3721 
3722       SourceLocation ELoc = E->getExprLoc();
3723       // OpenMP [2.9.3.6, Restrictions, p.2]
3724       //  A list item that appears in a reduction clause of the innermost
3725       //  enclosing worksharing or parallel construct may not be accessed in
3726       //  an  explicit task.
3727       DVar = Stack->hasInnermostDSA(
3728           FD,
3729           [](OpenMPClauseKind C, bool AppliedToPointee) {
3730             return C == OMPC_reduction && !AppliedToPointee;
3731           },
3732           [](OpenMPDirectiveKind K) {
3733             return isOpenMPParallelDirective(K) ||
3734                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3735           },
3736           /*FromParent=*/true);
3737       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3738         ErrorFound = true;
3739         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3740         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3741         return;
3742       }
3743 
3744       // Define implicit data-sharing attributes for task.
3745       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3746       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3747           !Stack->isLoopControlVariable(FD).first) {
3748         // Check if there is a captured expression for the current field in the
3749         // region. Do not mark it as firstprivate unless there is no captured
3750         // expression.
3751         // TODO: try to make it firstprivate.
3752         if (DVar.CKind != OMPC_unknown)
3753           ImplicitFirstprivate.push_back(E);
3754       }
3755       return;
3756     }
3757     if (isOpenMPTargetExecutionDirective(DKind)) {
3758       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3759       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3760                                         Stack->getCurrentDirective(),
3761                                         /*NoDiagnose=*/true))
3762         return;
3763       const auto *VD = cast<ValueDecl>(
3764           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3765       if (!Stack->checkMappableExprComponentListsForDecl(
3766               VD, /*CurrentRegionOnly=*/true,
3767               [&CurComponents](
3768                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3769                       StackComponents,
3770                   OpenMPClauseKind) {
3771                 auto CCI = CurComponents.rbegin();
3772                 auto CCE = CurComponents.rend();
3773                 for (const auto &SC : llvm::reverse(StackComponents)) {
3774                   // Do both expressions have the same kind?
3775                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3776                       SC.getAssociatedExpression()->getStmtClass())
3777                     if (!((isa<OMPArraySectionExpr>(
3778                                SC.getAssociatedExpression()) ||
3779                            isa<OMPArrayShapingExpr>(
3780                                SC.getAssociatedExpression())) &&
3781                           isa<ArraySubscriptExpr>(
3782                               CCI->getAssociatedExpression())))
3783                       return false;
3784 
3785                   const Decl *CCD = CCI->getAssociatedDeclaration();
3786                   const Decl *SCD = SC.getAssociatedDeclaration();
3787                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3788                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3789                   if (SCD != CCD)
3790                     return false;
3791                   std::advance(CCI, 1);
3792                   if (CCI == CCE)
3793                     break;
3794                 }
3795                 return true;
3796               })) {
3797         Visit(E->getBase());
3798       }
3799     } else if (!TryCaptureCXXThisMembers) {
3800       Visit(E->getBase());
3801     }
3802   }
3803   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3804     for (OMPClause *C : S->clauses()) {
3805       // Skip analysis of arguments of private clauses for task|target
3806       // directives.
3807       if (isa_and_nonnull<OMPPrivateClause>(C))
3808         continue;
3809       // Skip analysis of arguments of implicitly defined firstprivate clause
3810       // for task|target directives.
3811       // Skip analysis of arguments of implicitly defined map clause for target
3812       // directives.
3813       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3814                  C->isImplicit() &&
3815                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3816         for (Stmt *CC : C->children()) {
3817           if (CC)
3818             Visit(CC);
3819         }
3820       }
3821     }
3822     // Check implicitly captured variables.
3823     VisitSubCaptures(S);
3824   }
3825 
3826   void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
3827     // Loop transformation directives do not introduce data sharing
3828     VisitStmt(S);
3829   }
3830 
3831   void VisitCallExpr(CallExpr *S) {
3832     for (Stmt *C : S->arguments()) {
3833       if (C) {
3834         // Check implicitly captured variables in the task-based directives to
3835         // check if they must be firstprivatized.
3836         Visit(C);
3837       }
3838     }
3839     if (Expr *Callee = S->getCallee())
3840       if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts()))
3841         Visit(CE->getBase());
3842   }
3843   void VisitStmt(Stmt *S) {
3844     for (Stmt *C : S->children()) {
3845       if (C) {
3846         // Check implicitly captured variables in the task-based directives to
3847         // check if they must be firstprivatized.
3848         Visit(C);
3849       }
3850     }
3851   }
3852 
3853   void visitSubCaptures(CapturedStmt *S) {
3854     for (const CapturedStmt::Capture &Cap : S->captures()) {
3855       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3856         continue;
3857       VarDecl *VD = Cap.getCapturedVar();
3858       // Do not try to map the variable if it or its sub-component was mapped
3859       // already.
3860       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3861           Stack->checkMappableExprComponentListsForDecl(
3862               VD, /*CurrentRegionOnly=*/true,
3863               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3864                  OpenMPClauseKind) { return true; }))
3865         continue;
3866       DeclRefExpr *DRE = buildDeclRefExpr(
3867           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3868           Cap.getLocation(), /*RefersToCapture=*/true);
3869       Visit(DRE);
3870     }
3871   }
3872   bool isErrorFound() const { return ErrorFound; }
3873   ArrayRef<Expr *> getImplicitFirstprivate() const {
3874     return ImplicitFirstprivate;
3875   }
3876   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3877                                   OpenMPMapClauseKind MK) const {
3878     return ImplicitMap[DK][MK];
3879   }
3880   ArrayRef<OpenMPMapModifierKind>
3881   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3882     return ImplicitMapModifier[Kind];
3883   }
3884   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3885     return VarsWithInheritedDSA;
3886   }
3887 
3888   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3889       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3890     // Process declare target link variables for the target directives.
3891     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3892       for (DeclRefExpr *E : Stack->getLinkGlobals())
3893         Visit(E);
3894     }
3895   }
3896 };
3897 } // namespace
3898 
3899 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
3900                                                OpenMPDirectiveKind DKind,
3901                                                bool ScopeEntry) {
3902   SmallVector<llvm::omp::TraitProperty, 8> Traits;
3903   if (isOpenMPTargetExecutionDirective(DKind))
3904     Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
3905   if (isOpenMPTeamsDirective(DKind))
3906     Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
3907   if (isOpenMPParallelDirective(DKind))
3908     Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
3909   if (isOpenMPWorksharingDirective(DKind))
3910     Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
3911   if (isOpenMPSimdDirective(DKind))
3912     Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
3913   Stack->handleConstructTrait(Traits, ScopeEntry);
3914 }
3915 
3916 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3917   switch (DKind) {
3918   case OMPD_parallel:
3919   case OMPD_parallel_for:
3920   case OMPD_parallel_for_simd:
3921   case OMPD_parallel_sections:
3922   case OMPD_parallel_master:
3923   case OMPD_teams:
3924   case OMPD_teams_distribute:
3925   case OMPD_teams_distribute_simd: {
3926     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3927     QualType KmpInt32PtrTy =
3928         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3929     Sema::CapturedParamNameType Params[] = {
3930         std::make_pair(".global_tid.", KmpInt32PtrTy),
3931         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3932         std::make_pair(StringRef(), QualType()) // __context with shared vars
3933     };
3934     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3935                              Params);
3936     break;
3937   }
3938   case OMPD_target_teams:
3939   case OMPD_target_parallel:
3940   case OMPD_target_parallel_for:
3941   case OMPD_target_parallel_for_simd:
3942   case OMPD_target_teams_distribute:
3943   case OMPD_target_teams_distribute_simd: {
3944     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3945     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3946     QualType KmpInt32PtrTy =
3947         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3948     QualType Args[] = {VoidPtrTy};
3949     FunctionProtoType::ExtProtoInfo EPI;
3950     EPI.Variadic = true;
3951     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3952     Sema::CapturedParamNameType Params[] = {
3953         std::make_pair(".global_tid.", KmpInt32Ty),
3954         std::make_pair(".part_id.", KmpInt32PtrTy),
3955         std::make_pair(".privates.", VoidPtrTy),
3956         std::make_pair(
3957             ".copy_fn.",
3958             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3959         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3960         std::make_pair(StringRef(), QualType()) // __context with shared vars
3961     };
3962     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3963                              Params, /*OpenMPCaptureLevel=*/0);
3964     // Mark this captured region as inlined, because we don't use outlined
3965     // function directly.
3966     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3967         AlwaysInlineAttr::CreateImplicit(
3968             Context, {}, AttributeCommonInfo::AS_Keyword,
3969             AlwaysInlineAttr::Keyword_forceinline));
3970     Sema::CapturedParamNameType ParamsTarget[] = {
3971         std::make_pair(StringRef(), QualType()) // __context with shared vars
3972     };
3973     // Start a captured region for 'target' with no implicit parameters.
3974     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3975                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3976     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3977         std::make_pair(".global_tid.", KmpInt32PtrTy),
3978         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3979         std::make_pair(StringRef(), QualType()) // __context with shared vars
3980     };
3981     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3982     // the same implicit parameters.
3983     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3984                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3985     break;
3986   }
3987   case OMPD_target:
3988   case OMPD_target_simd: {
3989     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3990     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3991     QualType KmpInt32PtrTy =
3992         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3993     QualType Args[] = {VoidPtrTy};
3994     FunctionProtoType::ExtProtoInfo EPI;
3995     EPI.Variadic = true;
3996     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3997     Sema::CapturedParamNameType Params[] = {
3998         std::make_pair(".global_tid.", KmpInt32Ty),
3999         std::make_pair(".part_id.", KmpInt32PtrTy),
4000         std::make_pair(".privates.", VoidPtrTy),
4001         std::make_pair(
4002             ".copy_fn.",
4003             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4004         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4005         std::make_pair(StringRef(), QualType()) // __context with shared vars
4006     };
4007     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4008                              Params, /*OpenMPCaptureLevel=*/0);
4009     // Mark this captured region as inlined, because we don't use outlined
4010     // function directly.
4011     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4012         AlwaysInlineAttr::CreateImplicit(
4013             Context, {}, AttributeCommonInfo::AS_Keyword,
4014             AlwaysInlineAttr::Keyword_forceinline));
4015     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4016                              std::make_pair(StringRef(), QualType()),
4017                              /*OpenMPCaptureLevel=*/1);
4018     break;
4019   }
4020   case OMPD_atomic:
4021   case OMPD_critical:
4022   case OMPD_section:
4023   case OMPD_master:
4024   case OMPD_masked:
4025   case OMPD_tile:
4026   case OMPD_unroll:
4027     break;
4028   case OMPD_loop:
4029     // TODO: 'loop' may require additional parameters depending on the binding.
4030     // Treat similar to OMPD_simd/OMPD_for for now.
4031   case OMPD_simd:
4032   case OMPD_for:
4033   case OMPD_for_simd:
4034   case OMPD_sections:
4035   case OMPD_single:
4036   case OMPD_taskgroup:
4037   case OMPD_distribute:
4038   case OMPD_distribute_simd:
4039   case OMPD_ordered:
4040   case OMPD_target_data:
4041   case OMPD_dispatch: {
4042     Sema::CapturedParamNameType Params[] = {
4043         std::make_pair(StringRef(), QualType()) // __context with shared vars
4044     };
4045     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4046                              Params);
4047     break;
4048   }
4049   case OMPD_task: {
4050     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4051     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4052     QualType KmpInt32PtrTy =
4053         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4054     QualType Args[] = {VoidPtrTy};
4055     FunctionProtoType::ExtProtoInfo EPI;
4056     EPI.Variadic = true;
4057     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4058     Sema::CapturedParamNameType Params[] = {
4059         std::make_pair(".global_tid.", KmpInt32Ty),
4060         std::make_pair(".part_id.", KmpInt32PtrTy),
4061         std::make_pair(".privates.", VoidPtrTy),
4062         std::make_pair(
4063             ".copy_fn.",
4064             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4065         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4066         std::make_pair(StringRef(), QualType()) // __context with shared vars
4067     };
4068     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4069                              Params);
4070     // Mark this captured region as inlined, because we don't use outlined
4071     // function directly.
4072     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4073         AlwaysInlineAttr::CreateImplicit(
4074             Context, {}, AttributeCommonInfo::AS_Keyword,
4075             AlwaysInlineAttr::Keyword_forceinline));
4076     break;
4077   }
4078   case OMPD_taskloop:
4079   case OMPD_taskloop_simd:
4080   case OMPD_master_taskloop:
4081   case OMPD_master_taskloop_simd: {
4082     QualType KmpInt32Ty =
4083         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4084             .withConst();
4085     QualType KmpUInt64Ty =
4086         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4087             .withConst();
4088     QualType KmpInt64Ty =
4089         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4090             .withConst();
4091     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4092     QualType KmpInt32PtrTy =
4093         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4094     QualType Args[] = {VoidPtrTy};
4095     FunctionProtoType::ExtProtoInfo EPI;
4096     EPI.Variadic = true;
4097     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4098     Sema::CapturedParamNameType Params[] = {
4099         std::make_pair(".global_tid.", KmpInt32Ty),
4100         std::make_pair(".part_id.", KmpInt32PtrTy),
4101         std::make_pair(".privates.", VoidPtrTy),
4102         std::make_pair(
4103             ".copy_fn.",
4104             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4105         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4106         std::make_pair(".lb.", KmpUInt64Ty),
4107         std::make_pair(".ub.", KmpUInt64Ty),
4108         std::make_pair(".st.", KmpInt64Ty),
4109         std::make_pair(".liter.", KmpInt32Ty),
4110         std::make_pair(".reductions.", VoidPtrTy),
4111         std::make_pair(StringRef(), QualType()) // __context with shared vars
4112     };
4113     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4114                              Params);
4115     // Mark this captured region as inlined, because we don't use outlined
4116     // function directly.
4117     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4118         AlwaysInlineAttr::CreateImplicit(
4119             Context, {}, AttributeCommonInfo::AS_Keyword,
4120             AlwaysInlineAttr::Keyword_forceinline));
4121     break;
4122   }
4123   case OMPD_parallel_master_taskloop:
4124   case OMPD_parallel_master_taskloop_simd: {
4125     QualType KmpInt32Ty =
4126         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4127             .withConst();
4128     QualType KmpUInt64Ty =
4129         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4130             .withConst();
4131     QualType KmpInt64Ty =
4132         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4133             .withConst();
4134     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4135     QualType KmpInt32PtrTy =
4136         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4137     Sema::CapturedParamNameType ParamsParallel[] = {
4138         std::make_pair(".global_tid.", KmpInt32PtrTy),
4139         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4140         std::make_pair(StringRef(), QualType()) // __context with shared vars
4141     };
4142     // Start a captured region for 'parallel'.
4143     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4144                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4145     QualType Args[] = {VoidPtrTy};
4146     FunctionProtoType::ExtProtoInfo EPI;
4147     EPI.Variadic = true;
4148     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4149     Sema::CapturedParamNameType Params[] = {
4150         std::make_pair(".global_tid.", KmpInt32Ty),
4151         std::make_pair(".part_id.", KmpInt32PtrTy),
4152         std::make_pair(".privates.", VoidPtrTy),
4153         std::make_pair(
4154             ".copy_fn.",
4155             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4156         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4157         std::make_pair(".lb.", KmpUInt64Ty),
4158         std::make_pair(".ub.", KmpUInt64Ty),
4159         std::make_pair(".st.", KmpInt64Ty),
4160         std::make_pair(".liter.", KmpInt32Ty),
4161         std::make_pair(".reductions.", VoidPtrTy),
4162         std::make_pair(StringRef(), QualType()) // __context with shared vars
4163     };
4164     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4165                              Params, /*OpenMPCaptureLevel=*/1);
4166     // Mark this captured region as inlined, because we don't use outlined
4167     // function directly.
4168     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4169         AlwaysInlineAttr::CreateImplicit(
4170             Context, {}, AttributeCommonInfo::AS_Keyword,
4171             AlwaysInlineAttr::Keyword_forceinline));
4172     break;
4173   }
4174   case OMPD_distribute_parallel_for_simd:
4175   case OMPD_distribute_parallel_for: {
4176     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4177     QualType KmpInt32PtrTy =
4178         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4179     Sema::CapturedParamNameType Params[] = {
4180         std::make_pair(".global_tid.", KmpInt32PtrTy),
4181         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4182         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4183         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4184         std::make_pair(StringRef(), QualType()) // __context with shared vars
4185     };
4186     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4187                              Params);
4188     break;
4189   }
4190   case OMPD_target_teams_distribute_parallel_for:
4191   case OMPD_target_teams_distribute_parallel_for_simd: {
4192     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4193     QualType KmpInt32PtrTy =
4194         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4195     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4196 
4197     QualType Args[] = {VoidPtrTy};
4198     FunctionProtoType::ExtProtoInfo EPI;
4199     EPI.Variadic = true;
4200     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4201     Sema::CapturedParamNameType Params[] = {
4202         std::make_pair(".global_tid.", KmpInt32Ty),
4203         std::make_pair(".part_id.", KmpInt32PtrTy),
4204         std::make_pair(".privates.", VoidPtrTy),
4205         std::make_pair(
4206             ".copy_fn.",
4207             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4208         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4209         std::make_pair(StringRef(), QualType()) // __context with shared vars
4210     };
4211     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4212                              Params, /*OpenMPCaptureLevel=*/0);
4213     // Mark this captured region as inlined, because we don't use outlined
4214     // function directly.
4215     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4216         AlwaysInlineAttr::CreateImplicit(
4217             Context, {}, AttributeCommonInfo::AS_Keyword,
4218             AlwaysInlineAttr::Keyword_forceinline));
4219     Sema::CapturedParamNameType ParamsTarget[] = {
4220         std::make_pair(StringRef(), QualType()) // __context with shared vars
4221     };
4222     // Start a captured region for 'target' with no implicit parameters.
4223     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4224                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4225 
4226     Sema::CapturedParamNameType ParamsTeams[] = {
4227         std::make_pair(".global_tid.", KmpInt32PtrTy),
4228         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4229         std::make_pair(StringRef(), QualType()) // __context with shared vars
4230     };
4231     // Start a captured region for 'target' with no implicit parameters.
4232     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4233                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4234 
4235     Sema::CapturedParamNameType ParamsParallel[] = {
4236         std::make_pair(".global_tid.", KmpInt32PtrTy),
4237         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4238         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4239         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4240         std::make_pair(StringRef(), QualType()) // __context with shared vars
4241     };
4242     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4243     // the same implicit parameters.
4244     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4245                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4246     break;
4247   }
4248 
4249   case OMPD_teams_distribute_parallel_for:
4250   case OMPD_teams_distribute_parallel_for_simd: {
4251     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4252     QualType KmpInt32PtrTy =
4253         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4254 
4255     Sema::CapturedParamNameType ParamsTeams[] = {
4256         std::make_pair(".global_tid.", KmpInt32PtrTy),
4257         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4258         std::make_pair(StringRef(), QualType()) // __context with shared vars
4259     };
4260     // Start a captured region for 'target' with no implicit parameters.
4261     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4262                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4263 
4264     Sema::CapturedParamNameType ParamsParallel[] = {
4265         std::make_pair(".global_tid.", KmpInt32PtrTy),
4266         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4267         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4268         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4269         std::make_pair(StringRef(), QualType()) // __context with shared vars
4270     };
4271     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4272     // the same implicit parameters.
4273     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4274                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4275     break;
4276   }
4277   case OMPD_target_update:
4278   case OMPD_target_enter_data:
4279   case OMPD_target_exit_data: {
4280     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4281     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4282     QualType KmpInt32PtrTy =
4283         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4284     QualType Args[] = {VoidPtrTy};
4285     FunctionProtoType::ExtProtoInfo EPI;
4286     EPI.Variadic = true;
4287     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4288     Sema::CapturedParamNameType Params[] = {
4289         std::make_pair(".global_tid.", KmpInt32Ty),
4290         std::make_pair(".part_id.", KmpInt32PtrTy),
4291         std::make_pair(".privates.", VoidPtrTy),
4292         std::make_pair(
4293             ".copy_fn.",
4294             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4295         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4296         std::make_pair(StringRef(), QualType()) // __context with shared vars
4297     };
4298     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4299                              Params);
4300     // Mark this captured region as inlined, because we don't use outlined
4301     // function directly.
4302     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4303         AlwaysInlineAttr::CreateImplicit(
4304             Context, {}, AttributeCommonInfo::AS_Keyword,
4305             AlwaysInlineAttr::Keyword_forceinline));
4306     break;
4307   }
4308   case OMPD_threadprivate:
4309   case OMPD_allocate:
4310   case OMPD_taskyield:
4311   case OMPD_barrier:
4312   case OMPD_taskwait:
4313   case OMPD_cancellation_point:
4314   case OMPD_cancel:
4315   case OMPD_flush:
4316   case OMPD_depobj:
4317   case OMPD_scan:
4318   case OMPD_declare_reduction:
4319   case OMPD_declare_mapper:
4320   case OMPD_declare_simd:
4321   case OMPD_declare_target:
4322   case OMPD_end_declare_target:
4323   case OMPD_requires:
4324   case OMPD_declare_variant:
4325   case OMPD_begin_declare_variant:
4326   case OMPD_end_declare_variant:
4327   case OMPD_metadirective:
4328     llvm_unreachable("OpenMP Directive is not allowed");
4329   case OMPD_unknown:
4330   default:
4331     llvm_unreachable("Unknown OpenMP directive");
4332   }
4333   DSAStack->setContext(CurContext);
4334   handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
4335 }
4336 
4337 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4338   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4339 }
4340 
4341 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4342   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4343   getOpenMPCaptureRegions(CaptureRegions, DKind);
4344   return CaptureRegions.size();
4345 }
4346 
4347 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4348                                              Expr *CaptureExpr, bool WithInit,
4349                                              bool AsExpression) {
4350   assert(CaptureExpr);
4351   ASTContext &C = S.getASTContext();
4352   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4353   QualType Ty = Init->getType();
4354   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4355     if (S.getLangOpts().CPlusPlus) {
4356       Ty = C.getLValueReferenceType(Ty);
4357     } else {
4358       Ty = C.getPointerType(Ty);
4359       ExprResult Res =
4360           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4361       if (!Res.isUsable())
4362         return nullptr;
4363       Init = Res.get();
4364     }
4365     WithInit = true;
4366   }
4367   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4368                                           CaptureExpr->getBeginLoc());
4369   if (!WithInit)
4370     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4371   S.CurContext->addHiddenDecl(CED);
4372   Sema::TentativeAnalysisScope Trap(S);
4373   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4374   return CED;
4375 }
4376 
4377 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4378                                  bool WithInit) {
4379   OMPCapturedExprDecl *CD;
4380   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4381     CD = cast<OMPCapturedExprDecl>(VD);
4382   else
4383     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4384                           /*AsExpression=*/false);
4385   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4386                           CaptureExpr->getExprLoc());
4387 }
4388 
4389 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4390   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4391   if (!Ref) {
4392     OMPCapturedExprDecl *CD = buildCaptureDecl(
4393         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4394         /*WithInit=*/true, /*AsExpression=*/true);
4395     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4396                            CaptureExpr->getExprLoc());
4397   }
4398   ExprResult Res = Ref;
4399   if (!S.getLangOpts().CPlusPlus &&
4400       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4401       Ref->getType()->isPointerType()) {
4402     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4403     if (!Res.isUsable())
4404       return ExprError();
4405   }
4406   return S.DefaultLvalueConversion(Res.get());
4407 }
4408 
4409 namespace {
4410 // OpenMP directives parsed in this section are represented as a
4411 // CapturedStatement with an associated statement.  If a syntax error
4412 // is detected during the parsing of the associated statement, the
4413 // compiler must abort processing and close the CapturedStatement.
4414 //
4415 // Combined directives such as 'target parallel' have more than one
4416 // nested CapturedStatements.  This RAII ensures that we unwind out
4417 // of all the nested CapturedStatements when an error is found.
4418 class CaptureRegionUnwinderRAII {
4419 private:
4420   Sema &S;
4421   bool &ErrorFound;
4422   OpenMPDirectiveKind DKind = OMPD_unknown;
4423 
4424 public:
4425   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4426                             OpenMPDirectiveKind DKind)
4427       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4428   ~CaptureRegionUnwinderRAII() {
4429     if (ErrorFound) {
4430       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4431       while (--ThisCaptureLevel >= 0)
4432         S.ActOnCapturedRegionError();
4433     }
4434   }
4435 };
4436 } // namespace
4437 
4438 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4439   // Capture variables captured by reference in lambdas for target-based
4440   // directives.
4441   if (!CurContext->isDependentContext() &&
4442       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4443        isOpenMPTargetDataManagementDirective(
4444            DSAStack->getCurrentDirective()))) {
4445     QualType Type = V->getType();
4446     if (const auto *RD = Type.getCanonicalType()
4447                              .getNonReferenceType()
4448                              ->getAsCXXRecordDecl()) {
4449       bool SavedForceCaptureByReferenceInTargetExecutable =
4450           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4451       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4452           /*V=*/true);
4453       if (RD->isLambda()) {
4454         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4455         FieldDecl *ThisCapture;
4456         RD->getCaptureFields(Captures, ThisCapture);
4457         for (const LambdaCapture &LC : RD->captures()) {
4458           if (LC.getCaptureKind() == LCK_ByRef) {
4459             VarDecl *VD = LC.getCapturedVar();
4460             DeclContext *VDC = VD->getDeclContext();
4461             if (!VDC->Encloses(CurContext))
4462               continue;
4463             MarkVariableReferenced(LC.getLocation(), VD);
4464           } else if (LC.getCaptureKind() == LCK_This) {
4465             QualType ThisTy = getCurrentThisType();
4466             if (!ThisTy.isNull() &&
4467                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4468               CheckCXXThisCapture(LC.getLocation());
4469           }
4470         }
4471       }
4472       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4473           SavedForceCaptureByReferenceInTargetExecutable);
4474     }
4475   }
4476 }
4477 
4478 static bool checkOrderedOrderSpecified(Sema &S,
4479                                        const ArrayRef<OMPClause *> Clauses) {
4480   const OMPOrderedClause *Ordered = nullptr;
4481   const OMPOrderClause *Order = nullptr;
4482 
4483   for (const OMPClause *Clause : Clauses) {
4484     if (Clause->getClauseKind() == OMPC_ordered)
4485       Ordered = cast<OMPOrderedClause>(Clause);
4486     else if (Clause->getClauseKind() == OMPC_order) {
4487       Order = cast<OMPOrderClause>(Clause);
4488       if (Order->getKind() != OMPC_ORDER_concurrent)
4489         Order = nullptr;
4490     }
4491     if (Ordered && Order)
4492       break;
4493   }
4494 
4495   if (Ordered && Order) {
4496     S.Diag(Order->getKindKwLoc(),
4497            diag::err_omp_simple_clause_incompatible_with_ordered)
4498         << getOpenMPClauseName(OMPC_order)
4499         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4500         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4501     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4502         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4503     return true;
4504   }
4505   return false;
4506 }
4507 
4508 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4509                                       ArrayRef<OMPClause *> Clauses) {
4510   handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
4511                                      /* ScopeEntry */ false);
4512   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4513       DSAStack->getCurrentDirective() == OMPD_critical ||
4514       DSAStack->getCurrentDirective() == OMPD_section ||
4515       DSAStack->getCurrentDirective() == OMPD_master ||
4516       DSAStack->getCurrentDirective() == OMPD_masked)
4517     return S;
4518 
4519   bool ErrorFound = false;
4520   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4521       *this, ErrorFound, DSAStack->getCurrentDirective());
4522   if (!S.isUsable()) {
4523     ErrorFound = true;
4524     return StmtError();
4525   }
4526 
4527   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4528   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4529   OMPOrderedClause *OC = nullptr;
4530   OMPScheduleClause *SC = nullptr;
4531   SmallVector<const OMPLinearClause *, 4> LCs;
4532   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4533   // This is required for proper codegen.
4534   for (OMPClause *Clause : Clauses) {
4535     if (!LangOpts.OpenMPSimd &&
4536         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4537         Clause->getClauseKind() == OMPC_in_reduction) {
4538       // Capture taskgroup task_reduction descriptors inside the tasking regions
4539       // with the corresponding in_reduction items.
4540       auto *IRC = cast<OMPInReductionClause>(Clause);
4541       for (Expr *E : IRC->taskgroup_descriptors())
4542         if (E)
4543           MarkDeclarationsReferencedInExpr(E);
4544     }
4545     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4546         Clause->getClauseKind() == OMPC_copyprivate ||
4547         (getLangOpts().OpenMPUseTLS &&
4548          getASTContext().getTargetInfo().isTLSSupported() &&
4549          Clause->getClauseKind() == OMPC_copyin)) {
4550       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4551       // Mark all variables in private list clauses as used in inner region.
4552       for (Stmt *VarRef : Clause->children()) {
4553         if (auto *E = cast_or_null<Expr>(VarRef)) {
4554           MarkDeclarationsReferencedInExpr(E);
4555         }
4556       }
4557       DSAStack->setForceVarCapturing(/*V=*/false);
4558     } else if (isOpenMPLoopTransformationDirective(
4559                    DSAStack->getCurrentDirective())) {
4560       assert(CaptureRegions.empty() &&
4561              "No captured regions in loop transformation directives.");
4562     } else if (CaptureRegions.size() > 1 ||
4563                CaptureRegions.back() != OMPD_unknown) {
4564       if (auto *C = OMPClauseWithPreInit::get(Clause))
4565         PICs.push_back(C);
4566       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4567         if (Expr *E = C->getPostUpdateExpr())
4568           MarkDeclarationsReferencedInExpr(E);
4569       }
4570     }
4571     if (Clause->getClauseKind() == OMPC_schedule)
4572       SC = cast<OMPScheduleClause>(Clause);
4573     else if (Clause->getClauseKind() == OMPC_ordered)
4574       OC = cast<OMPOrderedClause>(Clause);
4575     else if (Clause->getClauseKind() == OMPC_linear)
4576       LCs.push_back(cast<OMPLinearClause>(Clause));
4577   }
4578   // Capture allocator expressions if used.
4579   for (Expr *E : DSAStack->getInnerAllocators())
4580     MarkDeclarationsReferencedInExpr(E);
4581   // OpenMP, 2.7.1 Loop Construct, Restrictions
4582   // The nonmonotonic modifier cannot be specified if an ordered clause is
4583   // specified.
4584   if (SC &&
4585       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4586        SC->getSecondScheduleModifier() ==
4587            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4588       OC) {
4589     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4590              ? SC->getFirstScheduleModifierLoc()
4591              : SC->getSecondScheduleModifierLoc(),
4592          diag::err_omp_simple_clause_incompatible_with_ordered)
4593         << getOpenMPClauseName(OMPC_schedule)
4594         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4595                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4596         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4597     ErrorFound = true;
4598   }
4599   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4600   // If an order(concurrent) clause is present, an ordered clause may not appear
4601   // on the same directive.
4602   if (checkOrderedOrderSpecified(*this, Clauses))
4603     ErrorFound = true;
4604   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4605     for (const OMPLinearClause *C : LCs) {
4606       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4607           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4608     }
4609     ErrorFound = true;
4610   }
4611   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4612       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4613       OC->getNumForLoops()) {
4614     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4615         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4616     ErrorFound = true;
4617   }
4618   if (ErrorFound) {
4619     return StmtError();
4620   }
4621   StmtResult SR = S;
4622   unsigned CompletedRegions = 0;
4623   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4624     // Mark all variables in private list clauses as used in inner region.
4625     // Required for proper codegen of combined directives.
4626     // TODO: add processing for other clauses.
4627     if (ThisCaptureRegion != OMPD_unknown) {
4628       for (const clang::OMPClauseWithPreInit *C : PICs) {
4629         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4630         // Find the particular capture region for the clause if the
4631         // directive is a combined one with multiple capture regions.
4632         // If the directive is not a combined one, the capture region
4633         // associated with the clause is OMPD_unknown and is generated
4634         // only once.
4635         if (CaptureRegion == ThisCaptureRegion ||
4636             CaptureRegion == OMPD_unknown) {
4637           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4638             for (Decl *D : DS->decls())
4639               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4640           }
4641         }
4642       }
4643     }
4644     if (ThisCaptureRegion == OMPD_target) {
4645       // Capture allocator traits in the target region. They are used implicitly
4646       // and, thus, are not captured by default.
4647       for (OMPClause *C : Clauses) {
4648         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4649           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4650                ++I) {
4651             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4652             if (Expr *E = D.AllocatorTraits)
4653               MarkDeclarationsReferencedInExpr(E);
4654           }
4655           continue;
4656         }
4657       }
4658     }
4659     if (ThisCaptureRegion == OMPD_parallel) {
4660       // Capture temp arrays for inscan reductions and locals in aligned
4661       // clauses.
4662       for (OMPClause *C : Clauses) {
4663         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4664           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4665             continue;
4666           for (Expr *E : RC->copy_array_temps())
4667             MarkDeclarationsReferencedInExpr(E);
4668         }
4669         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4670           for (Expr *E : AC->varlists())
4671             MarkDeclarationsReferencedInExpr(E);
4672         }
4673       }
4674     }
4675     if (++CompletedRegions == CaptureRegions.size())
4676       DSAStack->setBodyComplete();
4677     SR = ActOnCapturedRegionEnd(SR.get());
4678   }
4679   return SR;
4680 }
4681 
4682 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4683                               OpenMPDirectiveKind CancelRegion,
4684                               SourceLocation StartLoc) {
4685   // CancelRegion is only needed for cancel and cancellation_point.
4686   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4687     return false;
4688 
4689   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4690       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4691     return false;
4692 
4693   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4694       << getOpenMPDirectiveName(CancelRegion);
4695   return true;
4696 }
4697 
4698 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4699                                   OpenMPDirectiveKind CurrentRegion,
4700                                   const DeclarationNameInfo &CurrentName,
4701                                   OpenMPDirectiveKind CancelRegion,
4702                                   OpenMPBindClauseKind BindKind,
4703                                   SourceLocation StartLoc) {
4704   if (Stack->getCurScope()) {
4705     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4706     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4707     bool NestingProhibited = false;
4708     bool CloseNesting = true;
4709     bool OrphanSeen = false;
4710     enum {
4711       NoRecommend,
4712       ShouldBeInParallelRegion,
4713       ShouldBeInOrderedRegion,
4714       ShouldBeInTargetRegion,
4715       ShouldBeInTeamsRegion,
4716       ShouldBeInLoopSimdRegion,
4717     } Recommend = NoRecommend;
4718     if (isOpenMPSimdDirective(ParentRegion) &&
4719         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4720          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4721           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4722           CurrentRegion != OMPD_scan))) {
4723       // OpenMP [2.16, Nesting of Regions]
4724       // OpenMP constructs may not be nested inside a simd region.
4725       // OpenMP [2.8.1,simd Construct, Restrictions]
4726       // An ordered construct with the simd clause is the only OpenMP
4727       // construct that can appear in the simd region.
4728       // Allowing a SIMD construct nested in another SIMD construct is an
4729       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4730       // message.
4731       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4732       // The only OpenMP constructs that can be encountered during execution of
4733       // a simd region are the atomic construct, the loop construct, the simd
4734       // construct and the ordered construct with the simd clause.
4735       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4736                                  ? diag::err_omp_prohibited_region_simd
4737                                  : diag::warn_omp_nesting_simd)
4738           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4739       return CurrentRegion != OMPD_simd;
4740     }
4741     if (ParentRegion == OMPD_atomic) {
4742       // OpenMP [2.16, Nesting of Regions]
4743       // OpenMP constructs may not be nested inside an atomic region.
4744       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4745       return true;
4746     }
4747     if (CurrentRegion == OMPD_section) {
4748       // OpenMP [2.7.2, sections Construct, Restrictions]
4749       // Orphaned section directives are prohibited. That is, the section
4750       // directives must appear within the sections construct and must not be
4751       // encountered elsewhere in the sections region.
4752       if (ParentRegion != OMPD_sections &&
4753           ParentRegion != OMPD_parallel_sections) {
4754         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4755             << (ParentRegion != OMPD_unknown)
4756             << getOpenMPDirectiveName(ParentRegion);
4757         return true;
4758       }
4759       return false;
4760     }
4761     // Allow some constructs (except teams and cancellation constructs) to be
4762     // orphaned (they could be used in functions, called from OpenMP regions
4763     // with the required preconditions).
4764     if (ParentRegion == OMPD_unknown &&
4765         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4766         CurrentRegion != OMPD_cancellation_point &&
4767         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4768       return false;
4769     if (CurrentRegion == OMPD_cancellation_point ||
4770         CurrentRegion == OMPD_cancel) {
4771       // OpenMP [2.16, Nesting of Regions]
4772       // A cancellation point construct for which construct-type-clause is
4773       // taskgroup must be nested inside a task construct. A cancellation
4774       // point construct for which construct-type-clause is not taskgroup must
4775       // be closely nested inside an OpenMP construct that matches the type
4776       // specified in construct-type-clause.
4777       // A cancel construct for which construct-type-clause is taskgroup must be
4778       // nested inside a task construct. A cancel construct for which
4779       // construct-type-clause is not taskgroup must be closely nested inside an
4780       // OpenMP construct that matches the type specified in
4781       // construct-type-clause.
4782       NestingProhibited =
4783           !((CancelRegion == OMPD_parallel &&
4784              (ParentRegion == OMPD_parallel ||
4785               ParentRegion == OMPD_target_parallel)) ||
4786             (CancelRegion == OMPD_for &&
4787              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4788               ParentRegion == OMPD_target_parallel_for ||
4789               ParentRegion == OMPD_distribute_parallel_for ||
4790               ParentRegion == OMPD_teams_distribute_parallel_for ||
4791               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4792             (CancelRegion == OMPD_taskgroup &&
4793              (ParentRegion == OMPD_task ||
4794               (SemaRef.getLangOpts().OpenMP >= 50 &&
4795                (ParentRegion == OMPD_taskloop ||
4796                 ParentRegion == OMPD_master_taskloop ||
4797                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4798             (CancelRegion == OMPD_sections &&
4799              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4800               ParentRegion == OMPD_parallel_sections)));
4801       OrphanSeen = ParentRegion == OMPD_unknown;
4802     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4803       // OpenMP 5.1 [2.22, Nesting of Regions]
4804       // A masked region may not be closely nested inside a worksharing, loop,
4805       // atomic, task, or taskloop region.
4806       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4807                           isOpenMPGenericLoopDirective(ParentRegion) ||
4808                           isOpenMPTaskingDirective(ParentRegion);
4809     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4810       // OpenMP [2.16, Nesting of Regions]
4811       // A critical region may not be nested (closely or otherwise) inside a
4812       // critical region with the same name. Note that this restriction is not
4813       // sufficient to prevent deadlock.
4814       SourceLocation PreviousCriticalLoc;
4815       bool DeadLock = Stack->hasDirective(
4816           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4817                                               const DeclarationNameInfo &DNI,
4818                                               SourceLocation Loc) {
4819             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4820               PreviousCriticalLoc = Loc;
4821               return true;
4822             }
4823             return false;
4824           },
4825           false /* skip top directive */);
4826       if (DeadLock) {
4827         SemaRef.Diag(StartLoc,
4828                      diag::err_omp_prohibited_region_critical_same_name)
4829             << CurrentName.getName();
4830         if (PreviousCriticalLoc.isValid())
4831           SemaRef.Diag(PreviousCriticalLoc,
4832                        diag::note_omp_previous_critical_region);
4833         return true;
4834       }
4835     } else if (CurrentRegion == OMPD_barrier) {
4836       // OpenMP 5.1 [2.22, Nesting of Regions]
4837       // A barrier region may not be closely nested inside a worksharing, loop,
4838       // task, taskloop, critical, ordered, atomic, or masked region.
4839       NestingProhibited =
4840           isOpenMPWorksharingDirective(ParentRegion) ||
4841           isOpenMPGenericLoopDirective(ParentRegion) ||
4842           isOpenMPTaskingDirective(ParentRegion) ||
4843           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4844           ParentRegion == OMPD_parallel_master ||
4845           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4846     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4847                !isOpenMPParallelDirective(CurrentRegion) &&
4848                !isOpenMPTeamsDirective(CurrentRegion)) {
4849       // OpenMP 5.1 [2.22, Nesting of Regions]
4850       // A loop region that binds to a parallel region or a worksharing region
4851       // may not be closely nested inside a worksharing, loop, task, taskloop,
4852       // critical, ordered, atomic, or masked region.
4853       NestingProhibited =
4854           isOpenMPWorksharingDirective(ParentRegion) ||
4855           isOpenMPGenericLoopDirective(ParentRegion) ||
4856           isOpenMPTaskingDirective(ParentRegion) ||
4857           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4858           ParentRegion == OMPD_parallel_master ||
4859           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4860       Recommend = ShouldBeInParallelRegion;
4861     } else if (CurrentRegion == OMPD_ordered) {
4862       // OpenMP [2.16, Nesting of Regions]
4863       // An ordered region may not be closely nested inside a critical,
4864       // atomic, or explicit task region.
4865       // An ordered region must be closely nested inside a loop region (or
4866       // parallel loop region) with an ordered clause.
4867       // OpenMP [2.8.1,simd Construct, Restrictions]
4868       // An ordered construct with the simd clause is the only OpenMP construct
4869       // that can appear in the simd region.
4870       NestingProhibited = ParentRegion == OMPD_critical ||
4871                           isOpenMPTaskingDirective(ParentRegion) ||
4872                           !(isOpenMPSimdDirective(ParentRegion) ||
4873                             Stack->isParentOrderedRegion());
4874       Recommend = ShouldBeInOrderedRegion;
4875     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4876       // OpenMP [2.16, Nesting of Regions]
4877       // If specified, a teams construct must be contained within a target
4878       // construct.
4879       NestingProhibited =
4880           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4881           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4882            ParentRegion != OMPD_target);
4883       OrphanSeen = ParentRegion == OMPD_unknown;
4884       Recommend = ShouldBeInTargetRegion;
4885     } else if (CurrentRegion == OMPD_scan) {
4886       // OpenMP [2.16, Nesting of Regions]
4887       // If specified, a teams construct must be contained within a target
4888       // construct.
4889       NestingProhibited =
4890           SemaRef.LangOpts.OpenMP < 50 ||
4891           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4892            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4893            ParentRegion != OMPD_parallel_for_simd);
4894       OrphanSeen = ParentRegion == OMPD_unknown;
4895       Recommend = ShouldBeInLoopSimdRegion;
4896     }
4897     if (!NestingProhibited &&
4898         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4899         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4900         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4901       // OpenMP [5.1, 2.22, Nesting of Regions]
4902       // distribute, distribute simd, distribute parallel worksharing-loop,
4903       // distribute parallel worksharing-loop SIMD, loop, parallel regions,
4904       // including any parallel regions arising from combined constructs,
4905       // omp_get_num_teams() regions, and omp_get_team_num() regions are the
4906       // only OpenMP regions that may be strictly nested inside the teams
4907       // region.
4908       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4909                           !isOpenMPDistributeDirective(CurrentRegion) &&
4910                           CurrentRegion != OMPD_loop;
4911       Recommend = ShouldBeInParallelRegion;
4912     }
4913     if (!NestingProhibited && CurrentRegion == OMPD_loop) {
4914       // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
4915       // If the bind clause is present on the loop construct and binding is
4916       // teams then the corresponding loop region must be strictly nested inside
4917       // a teams region.
4918       NestingProhibited = BindKind == OMPC_BIND_teams &&
4919                           ParentRegion != OMPD_teams &&
4920                           ParentRegion != OMPD_target_teams;
4921       Recommend = ShouldBeInTeamsRegion;
4922     }
4923     if (!NestingProhibited &&
4924         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4925       // OpenMP 4.5 [2.17 Nesting of Regions]
4926       // The region associated with the distribute construct must be strictly
4927       // nested inside a teams region
4928       NestingProhibited =
4929           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4930       Recommend = ShouldBeInTeamsRegion;
4931     }
4932     if (!NestingProhibited &&
4933         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4934          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4935       // OpenMP 4.5 [2.17 Nesting of Regions]
4936       // If a target, target update, target data, target enter data, or
4937       // target exit data construct is encountered during execution of a
4938       // target region, the behavior is unspecified.
4939       NestingProhibited = Stack->hasDirective(
4940           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4941                              SourceLocation) {
4942             if (isOpenMPTargetExecutionDirective(K)) {
4943               OffendingRegion = K;
4944               return true;
4945             }
4946             return false;
4947           },
4948           false /* don't skip top directive */);
4949       CloseNesting = false;
4950     }
4951     if (NestingProhibited) {
4952       if (OrphanSeen) {
4953         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4954             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4955       } else {
4956         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4957             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4958             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4959       }
4960       return true;
4961     }
4962   }
4963   return false;
4964 }
4965 
4966 struct Kind2Unsigned {
4967   using argument_type = OpenMPDirectiveKind;
4968   unsigned operator()(argument_type DK) { return unsigned(DK); }
4969 };
4970 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4971                            ArrayRef<OMPClause *> Clauses,
4972                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4973   bool ErrorFound = false;
4974   unsigned NamedModifiersNumber = 0;
4975   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4976   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4977   SmallVector<SourceLocation, 4> NameModifierLoc;
4978   for (const OMPClause *C : Clauses) {
4979     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4980       // At most one if clause without a directive-name-modifier can appear on
4981       // the directive.
4982       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4983       if (FoundNameModifiers[CurNM]) {
4984         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4985             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4986             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4987         ErrorFound = true;
4988       } else if (CurNM != OMPD_unknown) {
4989         NameModifierLoc.push_back(IC->getNameModifierLoc());
4990         ++NamedModifiersNumber;
4991       }
4992       FoundNameModifiers[CurNM] = IC;
4993       if (CurNM == OMPD_unknown)
4994         continue;
4995       // Check if the specified name modifier is allowed for the current
4996       // directive.
4997       // At most one if clause with the particular directive-name-modifier can
4998       // appear on the directive.
4999       if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
5000         S.Diag(IC->getNameModifierLoc(),
5001                diag::err_omp_wrong_if_directive_name_modifier)
5002             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
5003         ErrorFound = true;
5004       }
5005     }
5006   }
5007   // If any if clause on the directive includes a directive-name-modifier then
5008   // all if clauses on the directive must include a directive-name-modifier.
5009   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5010     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5011       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5012              diag::err_omp_no_more_if_clause);
5013     } else {
5014       std::string Values;
5015       std::string Sep(", ");
5016       unsigned AllowedCnt = 0;
5017       unsigned TotalAllowedNum =
5018           AllowedNameModifiers.size() - NamedModifiersNumber;
5019       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5020            ++Cnt) {
5021         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5022         if (!FoundNameModifiers[NM]) {
5023           Values += "'";
5024           Values += getOpenMPDirectiveName(NM);
5025           Values += "'";
5026           if (AllowedCnt + 2 == TotalAllowedNum)
5027             Values += " or ";
5028           else if (AllowedCnt + 1 != TotalAllowedNum)
5029             Values += Sep;
5030           ++AllowedCnt;
5031         }
5032       }
5033       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5034              diag::err_omp_unnamed_if_clause)
5035           << (TotalAllowedNum > 1) << Values;
5036     }
5037     for (SourceLocation Loc : NameModifierLoc) {
5038       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5039     }
5040     ErrorFound = true;
5041   }
5042   return ErrorFound;
5043 }
5044 
5045 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
5046                                                    SourceLocation &ELoc,
5047                                                    SourceRange &ERange,
5048                                                    bool AllowArraySection) {
5049   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5050       RefExpr->containsUnexpandedParameterPack())
5051     return std::make_pair(nullptr, true);
5052 
5053   // OpenMP [3.1, C/C++]
5054   //  A list item is a variable name.
5055   // OpenMP  [2.9.3.3, Restrictions, p.1]
5056   //  A variable that is part of another variable (as an array or
5057   //  structure element) cannot appear in a private clause.
5058   RefExpr = RefExpr->IgnoreParens();
5059   enum {
5060     NoArrayExpr = -1,
5061     ArraySubscript = 0,
5062     OMPArraySection = 1
5063   } IsArrayExpr = NoArrayExpr;
5064   if (AllowArraySection) {
5065     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5066       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5067       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5068         Base = TempASE->getBase()->IgnoreParenImpCasts();
5069       RefExpr = Base;
5070       IsArrayExpr = ArraySubscript;
5071     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5072       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5073       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5074         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5075       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5076         Base = TempASE->getBase()->IgnoreParenImpCasts();
5077       RefExpr = Base;
5078       IsArrayExpr = OMPArraySection;
5079     }
5080   }
5081   ELoc = RefExpr->getExprLoc();
5082   ERange = RefExpr->getSourceRange();
5083   RefExpr = RefExpr->IgnoreParenImpCasts();
5084   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5085   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5086   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5087       (S.getCurrentThisType().isNull() || !ME ||
5088        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5089        !isa<FieldDecl>(ME->getMemberDecl()))) {
5090     if (IsArrayExpr != NoArrayExpr) {
5091       S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5092           << IsArrayExpr << ERange;
5093     } else {
5094       S.Diag(ELoc,
5095              AllowArraySection
5096                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5097                  : diag::err_omp_expected_var_name_member_expr)
5098           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5099     }
5100     return std::make_pair(nullptr, false);
5101   }
5102   return std::make_pair(
5103       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5104 }
5105 
5106 namespace {
5107 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5108 /// target regions.
5109 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5110   DSAStackTy *S = nullptr;
5111 
5112 public:
5113   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5114     return S->isUsesAllocatorsDecl(E->getDecl())
5115                .getValueOr(
5116                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5117            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5118   }
5119   bool VisitStmt(const Stmt *S) {
5120     for (const Stmt *Child : S->children()) {
5121       if (Child && Visit(Child))
5122         return true;
5123     }
5124     return false;
5125   }
5126   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5127 };
5128 } // namespace
5129 
5130 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5131                                  ArrayRef<OMPClause *> Clauses) {
5132   assert(!S.CurContext->isDependentContext() &&
5133          "Expected non-dependent context.");
5134   auto AllocateRange =
5135       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5136   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5137   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5138     return isOpenMPPrivate(C->getClauseKind());
5139   });
5140   for (OMPClause *Cl : PrivateRange) {
5141     MutableArrayRef<Expr *>::iterator I, It, Et;
5142     if (Cl->getClauseKind() == OMPC_private) {
5143       auto *PC = cast<OMPPrivateClause>(Cl);
5144       I = PC->private_copies().begin();
5145       It = PC->varlist_begin();
5146       Et = PC->varlist_end();
5147     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5148       auto *PC = cast<OMPFirstprivateClause>(Cl);
5149       I = PC->private_copies().begin();
5150       It = PC->varlist_begin();
5151       Et = PC->varlist_end();
5152     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5153       auto *PC = cast<OMPLastprivateClause>(Cl);
5154       I = PC->private_copies().begin();
5155       It = PC->varlist_begin();
5156       Et = PC->varlist_end();
5157     } else if (Cl->getClauseKind() == OMPC_linear) {
5158       auto *PC = cast<OMPLinearClause>(Cl);
5159       I = PC->privates().begin();
5160       It = PC->varlist_begin();
5161       Et = PC->varlist_end();
5162     } else if (Cl->getClauseKind() == OMPC_reduction) {
5163       auto *PC = cast<OMPReductionClause>(Cl);
5164       I = PC->privates().begin();
5165       It = PC->varlist_begin();
5166       Et = PC->varlist_end();
5167     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5168       auto *PC = cast<OMPTaskReductionClause>(Cl);
5169       I = PC->privates().begin();
5170       It = PC->varlist_begin();
5171       Et = PC->varlist_end();
5172     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5173       auto *PC = cast<OMPInReductionClause>(Cl);
5174       I = PC->privates().begin();
5175       It = PC->varlist_begin();
5176       Et = PC->varlist_end();
5177     } else {
5178       llvm_unreachable("Expected private clause.");
5179     }
5180     for (Expr *E : llvm::make_range(It, Et)) {
5181       if (!*I) {
5182         ++I;
5183         continue;
5184       }
5185       SourceLocation ELoc;
5186       SourceRange ERange;
5187       Expr *SimpleRefExpr = E;
5188       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5189                                 /*AllowArraySection=*/true);
5190       DeclToCopy.try_emplace(Res.first,
5191                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5192       ++I;
5193     }
5194   }
5195   for (OMPClause *C : AllocateRange) {
5196     auto *AC = cast<OMPAllocateClause>(C);
5197     if (S.getLangOpts().OpenMP >= 50 &&
5198         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5199         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5200         AC->getAllocator()) {
5201       Expr *Allocator = AC->getAllocator();
5202       // OpenMP, 2.12.5 target Construct
5203       // Memory allocators that do not appear in a uses_allocators clause cannot
5204       // appear as an allocator in an allocate clause or be used in the target
5205       // region unless a requires directive with the dynamic_allocators clause
5206       // is present in the same compilation unit.
5207       AllocatorChecker Checker(Stack);
5208       if (Checker.Visit(Allocator))
5209         S.Diag(Allocator->getExprLoc(),
5210                diag::err_omp_allocator_not_in_uses_allocators)
5211             << Allocator->getSourceRange();
5212     }
5213     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5214         getAllocatorKind(S, Stack, AC->getAllocator());
5215     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5216     // For task, taskloop or target directives, allocation requests to memory
5217     // allocators with the trait access set to thread result in unspecified
5218     // behavior.
5219     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5220         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5221          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5222       S.Diag(AC->getAllocator()->getExprLoc(),
5223              diag::warn_omp_allocate_thread_on_task_target_directive)
5224           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5225     }
5226     for (Expr *E : AC->varlists()) {
5227       SourceLocation ELoc;
5228       SourceRange ERange;
5229       Expr *SimpleRefExpr = E;
5230       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5231       ValueDecl *VD = Res.first;
5232       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5233       if (!isOpenMPPrivate(Data.CKind)) {
5234         S.Diag(E->getExprLoc(),
5235                diag::err_omp_expected_private_copy_for_allocate);
5236         continue;
5237       }
5238       VarDecl *PrivateVD = DeclToCopy[VD];
5239       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5240                                             AllocatorKind, AC->getAllocator()))
5241         continue;
5242       // Placeholder until allocate clause supports align modifier.
5243       Expr *Alignment = nullptr;
5244       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5245                                 Alignment, E->getSourceRange());
5246     }
5247   }
5248 }
5249 
5250 namespace {
5251 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5252 ///
5253 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5254 /// context. DeclRefExpr used inside the new context are changed to refer to the
5255 /// captured variable instead.
5256 class CaptureVars : public TreeTransform<CaptureVars> {
5257   using BaseTransform = TreeTransform<CaptureVars>;
5258 
5259 public:
5260   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5261 
5262   bool AlwaysRebuild() { return true; }
5263 };
5264 } // namespace
5265 
5266 static VarDecl *precomputeExpr(Sema &Actions,
5267                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5268                                StringRef Name) {
5269   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5270   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5271                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5272   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5273       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5274   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5275   BodyStmts.push_back(NewDeclStmt);
5276   return NewVar;
5277 }
5278 
5279 /// Create a closure that computes the number of iterations of a loop.
5280 ///
5281 /// \param Actions   The Sema object.
5282 /// \param LogicalTy Type for the logical iteration number.
5283 /// \param Rel       Comparison operator of the loop condition.
5284 /// \param StartExpr Value of the loop counter at the first iteration.
5285 /// \param StopExpr  Expression the loop counter is compared against in the loop
5286 /// condition. \param StepExpr      Amount of increment after each iteration.
5287 ///
5288 /// \return Closure (CapturedStmt) of the distance calculation.
5289 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5290                                        BinaryOperator::Opcode Rel,
5291                                        Expr *StartExpr, Expr *StopExpr,
5292                                        Expr *StepExpr) {
5293   ASTContext &Ctx = Actions.getASTContext();
5294   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5295 
5296   // Captured regions currently don't support return values, we use an
5297   // out-parameter instead. All inputs are implicit captures.
5298   // TODO: Instead of capturing each DeclRefExpr occurring in
5299   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5300   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5301   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5302                                           {StringRef(), QualType()}};
5303   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5304 
5305   Stmt *Body;
5306   {
5307     Sema::CompoundScopeRAII CompoundScope(Actions);
5308     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5309 
5310     // Get the LValue expression for the result.
5311     ImplicitParamDecl *DistParam = CS->getParam(0);
5312     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5313         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5314 
5315     SmallVector<Stmt *, 4> BodyStmts;
5316 
5317     // Capture all referenced variable references.
5318     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5319     // CapturedStmt, we could compute them before and capture the result, to be
5320     // used jointly with the LoopVar function.
5321     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5322     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5323     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5324     auto BuildVarRef = [&](VarDecl *VD) {
5325       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5326     };
5327 
5328     IntegerLiteral *Zero = IntegerLiteral::Create(
5329         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5330     IntegerLiteral *One = IntegerLiteral::Create(
5331         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5332     Expr *Dist;
5333     if (Rel == BO_NE) {
5334       // When using a != comparison, the increment can be +1 or -1. This can be
5335       // dynamic at runtime, so we need to check for the direction.
5336       Expr *IsNegStep = AssertSuccess(
5337           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5338 
5339       // Positive increment.
5340       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5341           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5342       ForwardRange = AssertSuccess(
5343           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5344       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5345           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5346 
5347       // Negative increment.
5348       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5349           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5350       BackwardRange = AssertSuccess(
5351           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5352       Expr *NegIncAmount = AssertSuccess(
5353           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5354       Expr *BackwardDist = AssertSuccess(
5355           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5356 
5357       // Use the appropriate case.
5358       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5359           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5360     } else {
5361       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5362              "Expected one of these relational operators");
5363 
5364       // We can derive the direction from any other comparison operator. It is
5365       // non well-formed OpenMP if Step increments/decrements in the other
5366       // directions. Whether at least the first iteration passes the loop
5367       // condition.
5368       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5369           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5370 
5371       // Compute the range between first and last counter value.
5372       Expr *Range;
5373       if (Rel == BO_GE || Rel == BO_GT)
5374         Range = AssertSuccess(Actions.BuildBinOp(
5375             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5376       else
5377         Range = AssertSuccess(Actions.BuildBinOp(
5378             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5379 
5380       // Ensure unsigned range space.
5381       Range =
5382           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5383 
5384       if (Rel == BO_LE || Rel == BO_GE) {
5385         // Add one to the range if the relational operator is inclusive.
5386         Range =
5387             AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One));
5388       }
5389 
5390       // Divide by the absolute step amount. If the range is not a multiple of
5391       // the step size, rounding-up the effective upper bound ensures that the
5392       // last iteration is included.
5393       // Note that the rounding-up may cause an overflow in a temporry that
5394       // could be avoided, but would have occurred in a C-style for-loop as well.
5395       Expr *Divisor = BuildVarRef(NewStep);
5396       if (Rel == BO_GE || Rel == BO_GT)
5397         Divisor =
5398             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5399       Expr *DivisorMinusOne =
5400           AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One));
5401       Expr *RangeRoundUp = AssertSuccess(
5402           Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne));
5403       Dist = AssertSuccess(
5404           Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor));
5405 
5406       // If there is not at least one iteration, the range contains garbage. Fix
5407       // to zero in this case.
5408       Dist = AssertSuccess(
5409           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5410     }
5411 
5412     // Assign the result to the out-parameter.
5413     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5414         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5415     BodyStmts.push_back(ResultAssign);
5416 
5417     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5418   }
5419 
5420   return cast<CapturedStmt>(
5421       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5422 }
5423 
5424 /// Create a closure that computes the loop variable from the logical iteration
5425 /// number.
5426 ///
5427 /// \param Actions   The Sema object.
5428 /// \param LoopVarTy Type for the loop variable used for result value.
5429 /// \param LogicalTy Type for the logical iteration number.
5430 /// \param StartExpr Value of the loop counter at the first iteration.
5431 /// \param Step      Amount of increment after each iteration.
5432 /// \param Deref     Whether the loop variable is a dereference of the loop
5433 /// counter variable.
5434 ///
5435 /// \return Closure (CapturedStmt) of the loop value calculation.
5436 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5437                                       QualType LogicalTy,
5438                                       DeclRefExpr *StartExpr, Expr *Step,
5439                                       bool Deref) {
5440   ASTContext &Ctx = Actions.getASTContext();
5441 
5442   // Pass the result as an out-parameter. Passing as return value would require
5443   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5444   // invoke a copy constructor.
5445   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5446   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5447                                           {"Logical", LogicalTy},
5448                                           {StringRef(), QualType()}};
5449   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5450 
5451   // Capture the initial iterator which represents the LoopVar value at the
5452   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5453   // it in every iteration, capture it by value before it is modified.
5454   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5455   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5456                                             Sema::TryCapture_ExplicitByVal, {});
5457   (void)Invalid;
5458   assert(!Invalid && "Expecting capture-by-value to work.");
5459 
5460   Expr *Body;
5461   {
5462     Sema::CompoundScopeRAII CompoundScope(Actions);
5463     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5464 
5465     ImplicitParamDecl *TargetParam = CS->getParam(0);
5466     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5467         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5468     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5469     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5470         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5471 
5472     // Capture the Start expression.
5473     CaptureVars Recap(Actions);
5474     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5475     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5476 
5477     Expr *Skip = AssertSuccess(
5478         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5479     // TODO: Explicitly cast to the iterator's difference_type instead of
5480     // relying on implicit conversion.
5481     Expr *Advanced =
5482         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5483 
5484     if (Deref) {
5485       // For range-based for-loops convert the loop counter value to a concrete
5486       // loop variable value by dereferencing the iterator.
5487       Advanced =
5488           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5489     }
5490 
5491     // Assign the result to the output parameter.
5492     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5493                                             BO_Assign, TargetRef, Advanced));
5494   }
5495   return cast<CapturedStmt>(
5496       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5497 }
5498 
5499 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5500   ASTContext &Ctx = getASTContext();
5501 
5502   // Extract the common elements of ForStmt and CXXForRangeStmt:
5503   // Loop variable, repeat condition, increment
5504   Expr *Cond, *Inc;
5505   VarDecl *LIVDecl, *LUVDecl;
5506   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5507     Stmt *Init = For->getInit();
5508     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5509       // For statement declares loop variable.
5510       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5511     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5512       // For statement reuses variable.
5513       assert(LCAssign->getOpcode() == BO_Assign &&
5514              "init part must be a loop variable assignment");
5515       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5516       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5517     } else
5518       llvm_unreachable("Cannot determine loop variable");
5519     LUVDecl = LIVDecl;
5520 
5521     Cond = For->getCond();
5522     Inc = For->getInc();
5523   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5524     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5525     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5526     LUVDecl = RangeFor->getLoopVariable();
5527 
5528     Cond = RangeFor->getCond();
5529     Inc = RangeFor->getInc();
5530   } else
5531     llvm_unreachable("unhandled kind of loop");
5532 
5533   QualType CounterTy = LIVDecl->getType();
5534   QualType LVTy = LUVDecl->getType();
5535 
5536   // Analyze the loop condition.
5537   Expr *LHS, *RHS;
5538   BinaryOperator::Opcode CondRel;
5539   Cond = Cond->IgnoreImplicit();
5540   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5541     LHS = CondBinExpr->getLHS();
5542     RHS = CondBinExpr->getRHS();
5543     CondRel = CondBinExpr->getOpcode();
5544   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5545     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5546     LHS = CondCXXOp->getArg(0);
5547     RHS = CondCXXOp->getArg(1);
5548     switch (CondCXXOp->getOperator()) {
5549     case OO_ExclaimEqual:
5550       CondRel = BO_NE;
5551       break;
5552     case OO_Less:
5553       CondRel = BO_LT;
5554       break;
5555     case OO_LessEqual:
5556       CondRel = BO_LE;
5557       break;
5558     case OO_Greater:
5559       CondRel = BO_GT;
5560       break;
5561     case OO_GreaterEqual:
5562       CondRel = BO_GE;
5563       break;
5564     default:
5565       llvm_unreachable("unexpected iterator operator");
5566     }
5567   } else
5568     llvm_unreachable("unexpected loop condition");
5569 
5570   // Normalize such that the loop counter is on the LHS.
5571   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5572       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5573     std::swap(LHS, RHS);
5574     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5575   }
5576   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5577 
5578   // Decide the bit width for the logical iteration counter. By default use the
5579   // unsigned ptrdiff_t integer size (for iterators and pointers).
5580   // TODO: For iterators, use iterator::difference_type,
5581   // std::iterator_traits<>::difference_type or decltype(it - end).
5582   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5583   if (CounterTy->isIntegerType()) {
5584     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5585     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5586   }
5587 
5588   // Analyze the loop increment.
5589   Expr *Step;
5590   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5591     int Direction;
5592     switch (IncUn->getOpcode()) {
5593     case UO_PreInc:
5594     case UO_PostInc:
5595       Direction = 1;
5596       break;
5597     case UO_PreDec:
5598     case UO_PostDec:
5599       Direction = -1;
5600       break;
5601     default:
5602       llvm_unreachable("unhandled unary increment operator");
5603     }
5604     Step = IntegerLiteral::Create(
5605         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5606   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5607     if (IncBin->getOpcode() == BO_AddAssign) {
5608       Step = IncBin->getRHS();
5609     } else if (IncBin->getOpcode() == BO_SubAssign) {
5610       Step =
5611           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5612     } else
5613       llvm_unreachable("unhandled binary increment operator");
5614   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5615     switch (CondCXXOp->getOperator()) {
5616     case OO_PlusPlus:
5617       Step = IntegerLiteral::Create(
5618           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5619       break;
5620     case OO_MinusMinus:
5621       Step = IntegerLiteral::Create(
5622           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5623       break;
5624     case OO_PlusEqual:
5625       Step = CondCXXOp->getArg(1);
5626       break;
5627     case OO_MinusEqual:
5628       Step = AssertSuccess(
5629           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5630       break;
5631     default:
5632       llvm_unreachable("unhandled overloaded increment operator");
5633     }
5634   } else
5635     llvm_unreachable("unknown increment expression");
5636 
5637   CapturedStmt *DistanceFunc =
5638       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5639   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5640       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5641   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5642                                         {}, nullptr, nullptr, {}, nullptr);
5643   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5644                                   LoopVarFunc, LVRef);
5645 }
5646 
5647 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
5648   // Handle a literal loop.
5649   if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
5650     return ActOnOpenMPCanonicalLoop(AStmt);
5651 
5652   // If not a literal loop, it must be the result of a loop transformation.
5653   OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
5654   assert(
5655       isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
5656       "Loop transformation directive expected");
5657   return LoopTransform;
5658 }
5659 
5660 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5661                                             CXXScopeSpec &MapperIdScopeSpec,
5662                                             const DeclarationNameInfo &MapperId,
5663                                             QualType Type,
5664                                             Expr *UnresolvedMapper);
5665 
5666 /// Perform DFS through the structure/class data members trying to find
5667 /// member(s) with user-defined 'default' mapper and generate implicit map
5668 /// clauses for such members with the found 'default' mapper.
5669 static void
5670 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5671                                       SmallVectorImpl<OMPClause *> &Clauses) {
5672   // Check for the deault mapper for data members.
5673   if (S.getLangOpts().OpenMP < 50)
5674     return;
5675   SmallVector<OMPClause *, 4> ImplicitMaps;
5676   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5677     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5678     if (!C)
5679       continue;
5680     SmallVector<Expr *, 4> SubExprs;
5681     auto *MI = C->mapperlist_begin();
5682     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5683          ++I, ++MI) {
5684       // Expression is mapped using mapper - skip it.
5685       if (*MI)
5686         continue;
5687       Expr *E = *I;
5688       // Expression is dependent - skip it, build the mapper when it gets
5689       // instantiated.
5690       if (E->isTypeDependent() || E->isValueDependent() ||
5691           E->containsUnexpandedParameterPack())
5692         continue;
5693       // Array section - need to check for the mapping of the array section
5694       // element.
5695       QualType CanonType = E->getType().getCanonicalType();
5696       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5697         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5698         QualType BaseType =
5699             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5700         QualType ElemType;
5701         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5702           ElemType = ATy->getElementType();
5703         else
5704           ElemType = BaseType->getPointeeType();
5705         CanonType = ElemType;
5706       }
5707 
5708       // DFS over data members in structures/classes.
5709       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5710           1, {CanonType, nullptr});
5711       llvm::DenseMap<const Type *, Expr *> Visited;
5712       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5713           1, {nullptr, 1});
5714       while (!Types.empty()) {
5715         QualType BaseType;
5716         FieldDecl *CurFD;
5717         std::tie(BaseType, CurFD) = Types.pop_back_val();
5718         while (ParentChain.back().second == 0)
5719           ParentChain.pop_back();
5720         --ParentChain.back().second;
5721         if (BaseType.isNull())
5722           continue;
5723         // Only structs/classes are allowed to have mappers.
5724         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5725         if (!RD)
5726           continue;
5727         auto It = Visited.find(BaseType.getTypePtr());
5728         if (It == Visited.end()) {
5729           // Try to find the associated user-defined mapper.
5730           CXXScopeSpec MapperIdScopeSpec;
5731           DeclarationNameInfo DefaultMapperId;
5732           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5733               &S.Context.Idents.get("default")));
5734           DefaultMapperId.setLoc(E->getExprLoc());
5735           ExprResult ER = buildUserDefinedMapperRef(
5736               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5737               BaseType, /*UnresolvedMapper=*/nullptr);
5738           if (ER.isInvalid())
5739             continue;
5740           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5741         }
5742         // Found default mapper.
5743         if (It->second) {
5744           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5745                                                      VK_LValue, OK_Ordinary, E);
5746           OE->setIsUnique(/*V=*/true);
5747           Expr *BaseExpr = OE;
5748           for (const auto &P : ParentChain) {
5749             if (P.first) {
5750               BaseExpr = S.BuildMemberExpr(
5751                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5752                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5753                   DeclAccessPair::make(P.first, P.first->getAccess()),
5754                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5755                   P.first->getType(), VK_LValue, OK_Ordinary);
5756               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5757             }
5758           }
5759           if (CurFD)
5760             BaseExpr = S.BuildMemberExpr(
5761                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5762                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5763                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5764                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5765                 CurFD->getType(), VK_LValue, OK_Ordinary);
5766           SubExprs.push_back(BaseExpr);
5767           continue;
5768         }
5769         // Check for the "default" mapper for data members.
5770         bool FirstIter = true;
5771         for (FieldDecl *FD : RD->fields()) {
5772           if (!FD)
5773             continue;
5774           QualType FieldTy = FD->getType();
5775           if (FieldTy.isNull() ||
5776               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5777             continue;
5778           if (FirstIter) {
5779             FirstIter = false;
5780             ParentChain.emplace_back(CurFD, 1);
5781           } else {
5782             ++ParentChain.back().second;
5783           }
5784           Types.emplace_back(FieldTy, FD);
5785         }
5786       }
5787     }
5788     if (SubExprs.empty())
5789       continue;
5790     CXXScopeSpec MapperIdScopeSpec;
5791     DeclarationNameInfo MapperId;
5792     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5793             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5794             MapperIdScopeSpec, MapperId, C->getMapType(),
5795             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5796             SubExprs, OMPVarListLocTy()))
5797       Clauses.push_back(NewClause);
5798   }
5799 }
5800 
5801 StmtResult Sema::ActOnOpenMPExecutableDirective(
5802     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5803     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5804     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5805   StmtResult Res = StmtError();
5806   OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
5807   if (const OMPBindClause *BC =
5808           OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
5809     BindKind = BC->getBindKind();
5810   // First check CancelRegion which is then used in checkNestingOfRegions.
5811   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5812       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5813                             BindKind, StartLoc))
5814     return StmtError();
5815 
5816   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5817   VarsWithInheritedDSAType VarsWithInheritedDSA;
5818   bool ErrorFound = false;
5819   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5820   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5821       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5822       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5823     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5824 
5825     // Check default data sharing attributes for referenced variables.
5826     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5827     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5828     Stmt *S = AStmt;
5829     while (--ThisCaptureLevel >= 0)
5830       S = cast<CapturedStmt>(S)->getCapturedStmt();
5831     DSAChecker.Visit(S);
5832     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5833         !isOpenMPTaskingDirective(Kind)) {
5834       // Visit subcaptures to generate implicit clauses for captured vars.
5835       auto *CS = cast<CapturedStmt>(AStmt);
5836       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5837       getOpenMPCaptureRegions(CaptureRegions, Kind);
5838       // Ignore outer tasking regions for target directives.
5839       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5840         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5841       DSAChecker.visitSubCaptures(CS);
5842     }
5843     if (DSAChecker.isErrorFound())
5844       return StmtError();
5845     // Generate list of implicitly defined firstprivate variables.
5846     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5847 
5848     SmallVector<Expr *, 4> ImplicitFirstprivates(
5849         DSAChecker.getImplicitFirstprivate().begin(),
5850         DSAChecker.getImplicitFirstprivate().end());
5851     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5852     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5853     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5854         ImplicitMapModifiers[DefaultmapKindNum];
5855     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5856         ImplicitMapModifiersLoc[DefaultmapKindNum];
5857     // Get the original location of present modifier from Defaultmap clause.
5858     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5859     for (OMPClause *C : Clauses) {
5860       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5861         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5862           PresentModifierLocs[DMC->getDefaultmapKind()] =
5863               DMC->getDefaultmapModifierLoc();
5864     }
5865     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5866       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5867       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5868         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5869             Kind, static_cast<OpenMPMapClauseKind>(I));
5870         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5871       }
5872       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5873           DSAChecker.getImplicitMapModifier(Kind);
5874       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5875                                       ImplicitModifier.end());
5876       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5877                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5878     }
5879     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5880     for (OMPClause *C : Clauses) {
5881       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5882         for (Expr *E : IRC->taskgroup_descriptors())
5883           if (E)
5884             ImplicitFirstprivates.emplace_back(E);
5885       }
5886       // OpenMP 5.0, 2.10.1 task Construct
5887       // [detach clause]... The event-handle will be considered as if it was
5888       // specified on a firstprivate clause.
5889       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5890         ImplicitFirstprivates.push_back(DC->getEventHandler());
5891     }
5892     if (!ImplicitFirstprivates.empty()) {
5893       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5894               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5895               SourceLocation())) {
5896         ClausesWithImplicit.push_back(Implicit);
5897         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5898                      ImplicitFirstprivates.size();
5899       } else {
5900         ErrorFound = true;
5901       }
5902     }
5903     // OpenMP 5.0 [2.19.7]
5904     // If a list item appears in a reduction, lastprivate or linear
5905     // clause on a combined target construct then it is treated as
5906     // if it also appears in a map clause with a map-type of tofrom
5907     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5908         isOpenMPTargetExecutionDirective(Kind)) {
5909       SmallVector<Expr *, 4> ImplicitExprs;
5910       for (OMPClause *C : Clauses) {
5911         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5912           for (Expr *E : RC->varlists())
5913             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5914               ImplicitExprs.emplace_back(E);
5915       }
5916       if (!ImplicitExprs.empty()) {
5917         ArrayRef<Expr *> Exprs = ImplicitExprs;
5918         CXXScopeSpec MapperIdScopeSpec;
5919         DeclarationNameInfo MapperId;
5920         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5921                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
5922                 MapperId, OMPC_MAP_tofrom,
5923                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5924                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
5925           ClausesWithImplicit.emplace_back(Implicit);
5926       }
5927     }
5928     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5929       int ClauseKindCnt = -1;
5930       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5931         ++ClauseKindCnt;
5932         if (ImplicitMap.empty())
5933           continue;
5934         CXXScopeSpec MapperIdScopeSpec;
5935         DeclarationNameInfo MapperId;
5936         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5937         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5938                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5939                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5940                 SourceLocation(), SourceLocation(), ImplicitMap,
5941                 OMPVarListLocTy())) {
5942           ClausesWithImplicit.emplace_back(Implicit);
5943           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5944                         ImplicitMap.size();
5945         } else {
5946           ErrorFound = true;
5947         }
5948       }
5949     }
5950     // Build expressions for implicit maps of data members with 'default'
5951     // mappers.
5952     if (LangOpts.OpenMP >= 50)
5953       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5954                                             ClausesWithImplicit);
5955   }
5956 
5957   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5958   switch (Kind) {
5959   case OMPD_parallel:
5960     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5961                                        EndLoc);
5962     AllowedNameModifiers.push_back(OMPD_parallel);
5963     break;
5964   case OMPD_simd:
5965     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5966                                    VarsWithInheritedDSA);
5967     if (LangOpts.OpenMP >= 50)
5968       AllowedNameModifiers.push_back(OMPD_simd);
5969     break;
5970   case OMPD_tile:
5971     Res =
5972         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5973     break;
5974   case OMPD_unroll:
5975     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
5976                                      EndLoc);
5977     break;
5978   case OMPD_for:
5979     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5980                                   VarsWithInheritedDSA);
5981     break;
5982   case OMPD_for_simd:
5983     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5984                                       EndLoc, VarsWithInheritedDSA);
5985     if (LangOpts.OpenMP >= 50)
5986       AllowedNameModifiers.push_back(OMPD_simd);
5987     break;
5988   case OMPD_sections:
5989     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5990                                        EndLoc);
5991     break;
5992   case OMPD_section:
5993     assert(ClausesWithImplicit.empty() &&
5994            "No clauses are allowed for 'omp section' directive");
5995     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5996     break;
5997   case OMPD_single:
5998     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5999                                      EndLoc);
6000     break;
6001   case OMPD_master:
6002     assert(ClausesWithImplicit.empty() &&
6003            "No clauses are allowed for 'omp master' directive");
6004     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
6005     break;
6006   case OMPD_masked:
6007     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
6008                                      EndLoc);
6009     break;
6010   case OMPD_critical:
6011     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
6012                                        StartLoc, EndLoc);
6013     break;
6014   case OMPD_parallel_for:
6015     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
6016                                           EndLoc, VarsWithInheritedDSA);
6017     AllowedNameModifiers.push_back(OMPD_parallel);
6018     break;
6019   case OMPD_parallel_for_simd:
6020     Res = ActOnOpenMPParallelForSimdDirective(
6021         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6022     AllowedNameModifiers.push_back(OMPD_parallel);
6023     if (LangOpts.OpenMP >= 50)
6024       AllowedNameModifiers.push_back(OMPD_simd);
6025     break;
6026   case OMPD_parallel_master:
6027     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
6028                                              StartLoc, EndLoc);
6029     AllowedNameModifiers.push_back(OMPD_parallel);
6030     break;
6031   case OMPD_parallel_sections:
6032     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
6033                                                StartLoc, EndLoc);
6034     AllowedNameModifiers.push_back(OMPD_parallel);
6035     break;
6036   case OMPD_task:
6037     Res =
6038         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6039     AllowedNameModifiers.push_back(OMPD_task);
6040     break;
6041   case OMPD_taskyield:
6042     assert(ClausesWithImplicit.empty() &&
6043            "No clauses are allowed for 'omp taskyield' directive");
6044     assert(AStmt == nullptr &&
6045            "No associated statement allowed for 'omp taskyield' directive");
6046     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
6047     break;
6048   case OMPD_barrier:
6049     assert(ClausesWithImplicit.empty() &&
6050            "No clauses are allowed for 'omp barrier' directive");
6051     assert(AStmt == nullptr &&
6052            "No associated statement allowed for 'omp barrier' directive");
6053     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
6054     break;
6055   case OMPD_taskwait:
6056     assert(AStmt == nullptr &&
6057            "No associated statement allowed for 'omp taskwait' directive");
6058     Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
6059     break;
6060   case OMPD_taskgroup:
6061     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
6062                                         EndLoc);
6063     break;
6064   case OMPD_flush:
6065     assert(AStmt == nullptr &&
6066            "No associated statement allowed for 'omp flush' directive");
6067     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
6068     break;
6069   case OMPD_depobj:
6070     assert(AStmt == nullptr &&
6071            "No associated statement allowed for 'omp depobj' directive");
6072     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
6073     break;
6074   case OMPD_scan:
6075     assert(AStmt == nullptr &&
6076            "No associated statement allowed for 'omp scan' directive");
6077     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
6078     break;
6079   case OMPD_ordered:
6080     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
6081                                       EndLoc);
6082     break;
6083   case OMPD_atomic:
6084     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
6085                                      EndLoc);
6086     break;
6087   case OMPD_teams:
6088     Res =
6089         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6090     break;
6091   case OMPD_target:
6092     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6093                                      EndLoc);
6094     AllowedNameModifiers.push_back(OMPD_target);
6095     break;
6096   case OMPD_target_parallel:
6097     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6098                                              StartLoc, EndLoc);
6099     AllowedNameModifiers.push_back(OMPD_target);
6100     AllowedNameModifiers.push_back(OMPD_parallel);
6101     break;
6102   case OMPD_target_parallel_for:
6103     Res = ActOnOpenMPTargetParallelForDirective(
6104         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6105     AllowedNameModifiers.push_back(OMPD_target);
6106     AllowedNameModifiers.push_back(OMPD_parallel);
6107     break;
6108   case OMPD_cancellation_point:
6109     assert(ClausesWithImplicit.empty() &&
6110            "No clauses are allowed for 'omp cancellation point' directive");
6111     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6112                                "cancellation point' directive");
6113     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6114     break;
6115   case OMPD_cancel:
6116     assert(AStmt == nullptr &&
6117            "No associated statement allowed for 'omp cancel' directive");
6118     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6119                                      CancelRegion);
6120     AllowedNameModifiers.push_back(OMPD_cancel);
6121     break;
6122   case OMPD_target_data:
6123     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6124                                          EndLoc);
6125     AllowedNameModifiers.push_back(OMPD_target_data);
6126     break;
6127   case OMPD_target_enter_data:
6128     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6129                                               EndLoc, AStmt);
6130     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6131     break;
6132   case OMPD_target_exit_data:
6133     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6134                                              EndLoc, AStmt);
6135     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6136     break;
6137   case OMPD_taskloop:
6138     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6139                                        EndLoc, VarsWithInheritedDSA);
6140     AllowedNameModifiers.push_back(OMPD_taskloop);
6141     break;
6142   case OMPD_taskloop_simd:
6143     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6144                                            EndLoc, VarsWithInheritedDSA);
6145     AllowedNameModifiers.push_back(OMPD_taskloop);
6146     if (LangOpts.OpenMP >= 50)
6147       AllowedNameModifiers.push_back(OMPD_simd);
6148     break;
6149   case OMPD_master_taskloop:
6150     Res = ActOnOpenMPMasterTaskLoopDirective(
6151         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6152     AllowedNameModifiers.push_back(OMPD_taskloop);
6153     break;
6154   case OMPD_master_taskloop_simd:
6155     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6156         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6157     AllowedNameModifiers.push_back(OMPD_taskloop);
6158     if (LangOpts.OpenMP >= 50)
6159       AllowedNameModifiers.push_back(OMPD_simd);
6160     break;
6161   case OMPD_parallel_master_taskloop:
6162     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6163         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6164     AllowedNameModifiers.push_back(OMPD_taskloop);
6165     AllowedNameModifiers.push_back(OMPD_parallel);
6166     break;
6167   case OMPD_parallel_master_taskloop_simd:
6168     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6169         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6170     AllowedNameModifiers.push_back(OMPD_taskloop);
6171     AllowedNameModifiers.push_back(OMPD_parallel);
6172     if (LangOpts.OpenMP >= 50)
6173       AllowedNameModifiers.push_back(OMPD_simd);
6174     break;
6175   case OMPD_distribute:
6176     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6177                                          EndLoc, VarsWithInheritedDSA);
6178     break;
6179   case OMPD_target_update:
6180     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6181                                            EndLoc, AStmt);
6182     AllowedNameModifiers.push_back(OMPD_target_update);
6183     break;
6184   case OMPD_distribute_parallel_for:
6185     Res = ActOnOpenMPDistributeParallelForDirective(
6186         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6187     AllowedNameModifiers.push_back(OMPD_parallel);
6188     break;
6189   case OMPD_distribute_parallel_for_simd:
6190     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6191         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6192     AllowedNameModifiers.push_back(OMPD_parallel);
6193     if (LangOpts.OpenMP >= 50)
6194       AllowedNameModifiers.push_back(OMPD_simd);
6195     break;
6196   case OMPD_distribute_simd:
6197     Res = ActOnOpenMPDistributeSimdDirective(
6198         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6199     if (LangOpts.OpenMP >= 50)
6200       AllowedNameModifiers.push_back(OMPD_simd);
6201     break;
6202   case OMPD_target_parallel_for_simd:
6203     Res = ActOnOpenMPTargetParallelForSimdDirective(
6204         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6205     AllowedNameModifiers.push_back(OMPD_target);
6206     AllowedNameModifiers.push_back(OMPD_parallel);
6207     if (LangOpts.OpenMP >= 50)
6208       AllowedNameModifiers.push_back(OMPD_simd);
6209     break;
6210   case OMPD_target_simd:
6211     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6212                                          EndLoc, VarsWithInheritedDSA);
6213     AllowedNameModifiers.push_back(OMPD_target);
6214     if (LangOpts.OpenMP >= 50)
6215       AllowedNameModifiers.push_back(OMPD_simd);
6216     break;
6217   case OMPD_teams_distribute:
6218     Res = ActOnOpenMPTeamsDistributeDirective(
6219         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6220     break;
6221   case OMPD_teams_distribute_simd:
6222     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6223         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6224     if (LangOpts.OpenMP >= 50)
6225       AllowedNameModifiers.push_back(OMPD_simd);
6226     break;
6227   case OMPD_teams_distribute_parallel_for_simd:
6228     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6229         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6230     AllowedNameModifiers.push_back(OMPD_parallel);
6231     if (LangOpts.OpenMP >= 50)
6232       AllowedNameModifiers.push_back(OMPD_simd);
6233     break;
6234   case OMPD_teams_distribute_parallel_for:
6235     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6236         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6237     AllowedNameModifiers.push_back(OMPD_parallel);
6238     break;
6239   case OMPD_target_teams:
6240     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6241                                           EndLoc);
6242     AllowedNameModifiers.push_back(OMPD_target);
6243     break;
6244   case OMPD_target_teams_distribute:
6245     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6246         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6247     AllowedNameModifiers.push_back(OMPD_target);
6248     break;
6249   case OMPD_target_teams_distribute_parallel_for:
6250     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6251         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6252     AllowedNameModifiers.push_back(OMPD_target);
6253     AllowedNameModifiers.push_back(OMPD_parallel);
6254     break;
6255   case OMPD_target_teams_distribute_parallel_for_simd:
6256     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6257         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6258     AllowedNameModifiers.push_back(OMPD_target);
6259     AllowedNameModifiers.push_back(OMPD_parallel);
6260     if (LangOpts.OpenMP >= 50)
6261       AllowedNameModifiers.push_back(OMPD_simd);
6262     break;
6263   case OMPD_target_teams_distribute_simd:
6264     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6265         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6266     AllowedNameModifiers.push_back(OMPD_target);
6267     if (LangOpts.OpenMP >= 50)
6268       AllowedNameModifiers.push_back(OMPD_simd);
6269     break;
6270   case OMPD_interop:
6271     assert(AStmt == nullptr &&
6272            "No associated statement allowed for 'omp interop' directive");
6273     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6274     break;
6275   case OMPD_dispatch:
6276     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6277                                        EndLoc);
6278     break;
6279   case OMPD_loop:
6280     Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6281                                           EndLoc, VarsWithInheritedDSA);
6282     break;
6283   case OMPD_declare_target:
6284   case OMPD_end_declare_target:
6285   case OMPD_threadprivate:
6286   case OMPD_allocate:
6287   case OMPD_declare_reduction:
6288   case OMPD_declare_mapper:
6289   case OMPD_declare_simd:
6290   case OMPD_requires:
6291   case OMPD_declare_variant:
6292   case OMPD_begin_declare_variant:
6293   case OMPD_end_declare_variant:
6294     llvm_unreachable("OpenMP Directive is not allowed");
6295   case OMPD_unknown:
6296   default:
6297     llvm_unreachable("Unknown OpenMP directive");
6298   }
6299 
6300   ErrorFound = Res.isInvalid() || ErrorFound;
6301 
6302   // Check variables in the clauses if default(none) or
6303   // default(firstprivate) was specified.
6304   if (DSAStack->getDefaultDSA() == DSA_none ||
6305       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6306     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6307     for (OMPClause *C : Clauses) {
6308       switch (C->getClauseKind()) {
6309       case OMPC_num_threads:
6310       case OMPC_dist_schedule:
6311         // Do not analyse if no parent teams directive.
6312         if (isOpenMPTeamsDirective(Kind))
6313           break;
6314         continue;
6315       case OMPC_if:
6316         if (isOpenMPTeamsDirective(Kind) &&
6317             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6318           break;
6319         if (isOpenMPParallelDirective(Kind) &&
6320             isOpenMPTaskLoopDirective(Kind) &&
6321             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6322           break;
6323         continue;
6324       case OMPC_schedule:
6325       case OMPC_detach:
6326         break;
6327       case OMPC_grainsize:
6328       case OMPC_num_tasks:
6329       case OMPC_final:
6330       case OMPC_priority:
6331       case OMPC_novariants:
6332       case OMPC_nocontext:
6333         // Do not analyze if no parent parallel directive.
6334         if (isOpenMPParallelDirective(Kind))
6335           break;
6336         continue;
6337       case OMPC_ordered:
6338       case OMPC_device:
6339       case OMPC_num_teams:
6340       case OMPC_thread_limit:
6341       case OMPC_hint:
6342       case OMPC_collapse:
6343       case OMPC_safelen:
6344       case OMPC_simdlen:
6345       case OMPC_sizes:
6346       case OMPC_default:
6347       case OMPC_proc_bind:
6348       case OMPC_private:
6349       case OMPC_firstprivate:
6350       case OMPC_lastprivate:
6351       case OMPC_shared:
6352       case OMPC_reduction:
6353       case OMPC_task_reduction:
6354       case OMPC_in_reduction:
6355       case OMPC_linear:
6356       case OMPC_aligned:
6357       case OMPC_copyin:
6358       case OMPC_copyprivate:
6359       case OMPC_nowait:
6360       case OMPC_untied:
6361       case OMPC_mergeable:
6362       case OMPC_allocate:
6363       case OMPC_read:
6364       case OMPC_write:
6365       case OMPC_update:
6366       case OMPC_capture:
6367       case OMPC_compare:
6368       case OMPC_seq_cst:
6369       case OMPC_acq_rel:
6370       case OMPC_acquire:
6371       case OMPC_release:
6372       case OMPC_relaxed:
6373       case OMPC_depend:
6374       case OMPC_threads:
6375       case OMPC_simd:
6376       case OMPC_map:
6377       case OMPC_nogroup:
6378       case OMPC_defaultmap:
6379       case OMPC_to:
6380       case OMPC_from:
6381       case OMPC_use_device_ptr:
6382       case OMPC_use_device_addr:
6383       case OMPC_is_device_ptr:
6384       case OMPC_nontemporal:
6385       case OMPC_order:
6386       case OMPC_destroy:
6387       case OMPC_inclusive:
6388       case OMPC_exclusive:
6389       case OMPC_uses_allocators:
6390       case OMPC_affinity:
6391       case OMPC_bind:
6392         continue;
6393       case OMPC_allocator:
6394       case OMPC_flush:
6395       case OMPC_depobj:
6396       case OMPC_threadprivate:
6397       case OMPC_uniform:
6398       case OMPC_unknown:
6399       case OMPC_unified_address:
6400       case OMPC_unified_shared_memory:
6401       case OMPC_reverse_offload:
6402       case OMPC_dynamic_allocators:
6403       case OMPC_atomic_default_mem_order:
6404       case OMPC_device_type:
6405       case OMPC_match:
6406       case OMPC_when:
6407       default:
6408         llvm_unreachable("Unexpected clause");
6409       }
6410       for (Stmt *CC : C->children()) {
6411         if (CC)
6412           DSAChecker.Visit(CC);
6413       }
6414     }
6415     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6416       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6417   }
6418   for (const auto &P : VarsWithInheritedDSA) {
6419     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6420       continue;
6421     ErrorFound = true;
6422     if (DSAStack->getDefaultDSA() == DSA_none ||
6423         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6424       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6425           << P.first << P.second->getSourceRange();
6426       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6427     } else if (getLangOpts().OpenMP >= 50) {
6428       Diag(P.second->getExprLoc(),
6429            diag::err_omp_defaultmap_no_attr_for_variable)
6430           << P.first << P.second->getSourceRange();
6431       Diag(DSAStack->getDefaultDSALocation(),
6432            diag::note_omp_defaultmap_attr_none);
6433     }
6434   }
6435 
6436   if (!AllowedNameModifiers.empty())
6437     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6438                  ErrorFound;
6439 
6440   if (ErrorFound)
6441     return StmtError();
6442 
6443   if (!CurContext->isDependentContext() &&
6444       isOpenMPTargetExecutionDirective(Kind) &&
6445       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6446         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6447         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6448         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6449     // Register target to DSA Stack.
6450     DSAStack->addTargetDirLocation(StartLoc);
6451   }
6452 
6453   return Res;
6454 }
6455 
6456 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6457     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6458     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6459     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6460     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6461   assert(Aligneds.size() == Alignments.size());
6462   assert(Linears.size() == LinModifiers.size());
6463   assert(Linears.size() == Steps.size());
6464   if (!DG || DG.get().isNull())
6465     return DeclGroupPtrTy();
6466 
6467   const int SimdId = 0;
6468   if (!DG.get().isSingleDecl()) {
6469     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6470         << SimdId;
6471     return DG;
6472   }
6473   Decl *ADecl = DG.get().getSingleDecl();
6474   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6475     ADecl = FTD->getTemplatedDecl();
6476 
6477   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6478   if (!FD) {
6479     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6480     return DeclGroupPtrTy();
6481   }
6482 
6483   // OpenMP [2.8.2, declare simd construct, Description]
6484   // The parameter of the simdlen clause must be a constant positive integer
6485   // expression.
6486   ExprResult SL;
6487   if (Simdlen)
6488     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6489   // OpenMP [2.8.2, declare simd construct, Description]
6490   // The special this pointer can be used as if was one of the arguments to the
6491   // function in any of the linear, aligned, or uniform clauses.
6492   // The uniform clause declares one or more arguments to have an invariant
6493   // value for all concurrent invocations of the function in the execution of a
6494   // single SIMD loop.
6495   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6496   const Expr *UniformedLinearThis = nullptr;
6497   for (const Expr *E : Uniforms) {
6498     E = E->IgnoreParenImpCasts();
6499     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6500       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6501         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6502             FD->getParamDecl(PVD->getFunctionScopeIndex())
6503                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6504           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6505           continue;
6506         }
6507     if (isa<CXXThisExpr>(E)) {
6508       UniformedLinearThis = E;
6509       continue;
6510     }
6511     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6512         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6513   }
6514   // OpenMP [2.8.2, declare simd construct, Description]
6515   // The aligned clause declares that the object to which each list item points
6516   // is aligned to the number of bytes expressed in the optional parameter of
6517   // the aligned clause.
6518   // The special this pointer can be used as if was one of the arguments to the
6519   // function in any of the linear, aligned, or uniform clauses.
6520   // The type of list items appearing in the aligned clause must be array,
6521   // pointer, reference to array, or reference to pointer.
6522   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6523   const Expr *AlignedThis = nullptr;
6524   for (const Expr *E : Aligneds) {
6525     E = E->IgnoreParenImpCasts();
6526     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6527       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6528         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6529         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6530             FD->getParamDecl(PVD->getFunctionScopeIndex())
6531                     ->getCanonicalDecl() == CanonPVD) {
6532           // OpenMP  [2.8.1, simd construct, Restrictions]
6533           // A list-item cannot appear in more than one aligned clause.
6534           if (AlignedArgs.count(CanonPVD) > 0) {
6535             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6536                 << 1 << getOpenMPClauseName(OMPC_aligned)
6537                 << E->getSourceRange();
6538             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6539                  diag::note_omp_explicit_dsa)
6540                 << getOpenMPClauseName(OMPC_aligned);
6541             continue;
6542           }
6543           AlignedArgs[CanonPVD] = E;
6544           QualType QTy = PVD->getType()
6545                              .getNonReferenceType()
6546                              .getUnqualifiedType()
6547                              .getCanonicalType();
6548           const Type *Ty = QTy.getTypePtrOrNull();
6549           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6550             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6551                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6552             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6553           }
6554           continue;
6555         }
6556       }
6557     if (isa<CXXThisExpr>(E)) {
6558       if (AlignedThis) {
6559         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6560             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6561         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6562             << getOpenMPClauseName(OMPC_aligned);
6563       }
6564       AlignedThis = E;
6565       continue;
6566     }
6567     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6568         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6569   }
6570   // The optional parameter of the aligned clause, alignment, must be a constant
6571   // positive integer expression. If no optional parameter is specified,
6572   // implementation-defined default alignments for SIMD instructions on the
6573   // target platforms are assumed.
6574   SmallVector<const Expr *, 4> NewAligns;
6575   for (Expr *E : Alignments) {
6576     ExprResult Align;
6577     if (E)
6578       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6579     NewAligns.push_back(Align.get());
6580   }
6581   // OpenMP [2.8.2, declare simd construct, Description]
6582   // The linear clause declares one or more list items to be private to a SIMD
6583   // lane and to have a linear relationship with respect to the iteration space
6584   // of a loop.
6585   // The special this pointer can be used as if was one of the arguments to the
6586   // function in any of the linear, aligned, or uniform clauses.
6587   // When a linear-step expression is specified in a linear clause it must be
6588   // either a constant integer expression or an integer-typed parameter that is
6589   // specified in a uniform clause on the directive.
6590   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6591   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6592   auto MI = LinModifiers.begin();
6593   for (const Expr *E : Linears) {
6594     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6595     ++MI;
6596     E = E->IgnoreParenImpCasts();
6597     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6598       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6599         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6600         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6601             FD->getParamDecl(PVD->getFunctionScopeIndex())
6602                     ->getCanonicalDecl() == CanonPVD) {
6603           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6604           // A list-item cannot appear in more than one linear clause.
6605           if (LinearArgs.count(CanonPVD) > 0) {
6606             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6607                 << getOpenMPClauseName(OMPC_linear)
6608                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6609             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6610                  diag::note_omp_explicit_dsa)
6611                 << getOpenMPClauseName(OMPC_linear);
6612             continue;
6613           }
6614           // Each argument can appear in at most one uniform or linear clause.
6615           if (UniformedArgs.count(CanonPVD) > 0) {
6616             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6617                 << getOpenMPClauseName(OMPC_linear)
6618                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6619             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6620                  diag::note_omp_explicit_dsa)
6621                 << getOpenMPClauseName(OMPC_uniform);
6622             continue;
6623           }
6624           LinearArgs[CanonPVD] = E;
6625           if (E->isValueDependent() || E->isTypeDependent() ||
6626               E->isInstantiationDependent() ||
6627               E->containsUnexpandedParameterPack())
6628             continue;
6629           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6630                                       PVD->getOriginalType(),
6631                                       /*IsDeclareSimd=*/true);
6632           continue;
6633         }
6634       }
6635     if (isa<CXXThisExpr>(E)) {
6636       if (UniformedLinearThis) {
6637         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6638             << getOpenMPClauseName(OMPC_linear)
6639             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6640             << E->getSourceRange();
6641         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6642             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6643                                                    : OMPC_linear);
6644         continue;
6645       }
6646       UniformedLinearThis = E;
6647       if (E->isValueDependent() || E->isTypeDependent() ||
6648           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6649         continue;
6650       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6651                                   E->getType(), /*IsDeclareSimd=*/true);
6652       continue;
6653     }
6654     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6655         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6656   }
6657   Expr *Step = nullptr;
6658   Expr *NewStep = nullptr;
6659   SmallVector<Expr *, 4> NewSteps;
6660   for (Expr *E : Steps) {
6661     // Skip the same step expression, it was checked already.
6662     if (Step == E || !E) {
6663       NewSteps.push_back(E ? NewStep : nullptr);
6664       continue;
6665     }
6666     Step = E;
6667     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6668       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6669         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6670         if (UniformedArgs.count(CanonPVD) == 0) {
6671           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6672               << Step->getSourceRange();
6673         } else if (E->isValueDependent() || E->isTypeDependent() ||
6674                    E->isInstantiationDependent() ||
6675                    E->containsUnexpandedParameterPack() ||
6676                    CanonPVD->getType()->hasIntegerRepresentation()) {
6677           NewSteps.push_back(Step);
6678         } else {
6679           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6680               << Step->getSourceRange();
6681         }
6682         continue;
6683       }
6684     NewStep = Step;
6685     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6686         !Step->isInstantiationDependent() &&
6687         !Step->containsUnexpandedParameterPack()) {
6688       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6689                     .get();
6690       if (NewStep)
6691         NewStep =
6692             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6693     }
6694     NewSteps.push_back(NewStep);
6695   }
6696   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6697       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6698       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6699       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6700       const_cast<Expr **>(Linears.data()), Linears.size(),
6701       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6702       NewSteps.data(), NewSteps.size(), SR);
6703   ADecl->addAttr(NewAttr);
6704   return DG;
6705 }
6706 
6707 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6708                          QualType NewType) {
6709   assert(NewType->isFunctionProtoType() &&
6710          "Expected function type with prototype.");
6711   assert(FD->getType()->isFunctionNoProtoType() &&
6712          "Expected function with type with no prototype.");
6713   assert(FDWithProto->getType()->isFunctionProtoType() &&
6714          "Expected function with prototype.");
6715   // Synthesize parameters with the same types.
6716   FD->setType(NewType);
6717   SmallVector<ParmVarDecl *, 16> Params;
6718   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6719     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6720                                       SourceLocation(), nullptr, P->getType(),
6721                                       /*TInfo=*/nullptr, SC_None, nullptr);
6722     Param->setScopeInfo(0, Params.size());
6723     Param->setImplicit();
6724     Params.push_back(Param);
6725   }
6726 
6727   FD->setParams(Params);
6728 }
6729 
6730 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6731   if (D->isInvalidDecl())
6732     return;
6733   FunctionDecl *FD = nullptr;
6734   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6735     FD = UTemplDecl->getTemplatedDecl();
6736   else
6737     FD = cast<FunctionDecl>(D);
6738   assert(FD && "Expected a function declaration!");
6739 
6740   // If we are instantiating templates we do *not* apply scoped assumptions but
6741   // only global ones. We apply scoped assumption to the template definition
6742   // though.
6743   if (!inTemplateInstantiation()) {
6744     for (AssumptionAttr *AA : OMPAssumeScoped)
6745       FD->addAttr(AA);
6746   }
6747   for (AssumptionAttr *AA : OMPAssumeGlobal)
6748     FD->addAttr(AA);
6749 }
6750 
6751 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6752     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6753 
6754 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6755     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6756     SmallVectorImpl<FunctionDecl *> &Bases) {
6757   if (!D.getIdentifier())
6758     return;
6759 
6760   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6761 
6762   // Template specialization is an extension, check if we do it.
6763   bool IsTemplated = !TemplateParamLists.empty();
6764   if (IsTemplated &
6765       !DVScope.TI->isExtensionActive(
6766           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6767     return;
6768 
6769   IdentifierInfo *BaseII = D.getIdentifier();
6770   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6771                       LookupOrdinaryName);
6772   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6773 
6774   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6775   QualType FType = TInfo->getType();
6776 
6777   bool IsConstexpr =
6778       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6779   bool IsConsteval =
6780       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6781 
6782   for (auto *Candidate : Lookup) {
6783     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6784     FunctionDecl *UDecl = nullptr;
6785     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
6786       auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
6787       if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
6788         UDecl = FTD->getTemplatedDecl();
6789     } else if (!IsTemplated)
6790       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6791     if (!UDecl)
6792       continue;
6793 
6794     // Don't specialize constexpr/consteval functions with
6795     // non-constexpr/consteval functions.
6796     if (UDecl->isConstexpr() && !IsConstexpr)
6797       continue;
6798     if (UDecl->isConsteval() && !IsConsteval)
6799       continue;
6800 
6801     QualType UDeclTy = UDecl->getType();
6802     if (!UDeclTy->isDependentType()) {
6803       QualType NewType = Context.mergeFunctionTypes(
6804           FType, UDeclTy, /* OfBlockPointer */ false,
6805           /* Unqualified */ false, /* AllowCXX */ true);
6806       if (NewType.isNull())
6807         continue;
6808     }
6809 
6810     // Found a base!
6811     Bases.push_back(UDecl);
6812   }
6813 
6814   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6815       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6816   // If no base was found we create a declaration that we use as base.
6817   if (Bases.empty() && UseImplicitBase) {
6818     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6819     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6820     BaseD->setImplicit(true);
6821     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6822       Bases.push_back(BaseTemplD->getTemplatedDecl());
6823     else
6824       Bases.push_back(cast<FunctionDecl>(BaseD));
6825   }
6826 
6827   std::string MangledName;
6828   MangledName += D.getIdentifier()->getName();
6829   MangledName += getOpenMPVariantManglingSeparatorStr();
6830   MangledName += DVScope.NameSuffix;
6831   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6832 
6833   VariantII.setMangledOpenMPVariantName(true);
6834   D.SetIdentifier(&VariantII, D.getBeginLoc());
6835 }
6836 
6837 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6838     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6839   // Do not mark function as is used to prevent its emission if this is the
6840   // only place where it is used.
6841   EnterExpressionEvaluationContext Unevaluated(
6842       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6843 
6844   FunctionDecl *FD = nullptr;
6845   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6846     FD = UTemplDecl->getTemplatedDecl();
6847   else
6848     FD = cast<FunctionDecl>(D);
6849   auto *VariantFuncRef = DeclRefExpr::Create(
6850       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6851       /* RefersToEnclosingVariableOrCapture */ false,
6852       /* NameLoc */ FD->getLocation(), FD->getType(),
6853       ExprValueKind::VK_PRValue);
6854 
6855   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6856   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6857       Context, VariantFuncRef, DVScope.TI,
6858       /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
6859       /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
6860       /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
6861   for (FunctionDecl *BaseFD : Bases)
6862     BaseFD->addAttr(OMPDeclareVariantA);
6863 }
6864 
6865 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6866                                  SourceLocation LParenLoc,
6867                                  MultiExprArg ArgExprs,
6868                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6869   // The common case is a regular call we do not want to specialize at all. Try
6870   // to make that case fast by bailing early.
6871   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6872   if (!CE)
6873     return Call;
6874 
6875   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6876   if (!CalleeFnDecl)
6877     return Call;
6878 
6879   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6880     return Call;
6881 
6882   ASTContext &Context = getASTContext();
6883   std::function<void(StringRef)> DiagUnknownTrait = [this,
6884                                                      CE](StringRef ISATrait) {
6885     // TODO Track the selector locations in a way that is accessible here to
6886     // improve the diagnostic location.
6887     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6888         << ISATrait;
6889   };
6890   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6891                           getCurFunctionDecl(), DSAStack->getConstructTraits());
6892 
6893   QualType CalleeFnType = CalleeFnDecl->getType();
6894 
6895   SmallVector<Expr *, 4> Exprs;
6896   SmallVector<VariantMatchInfo, 4> VMIs;
6897   while (CalleeFnDecl) {
6898     for (OMPDeclareVariantAttr *A :
6899          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6900       Expr *VariantRef = A->getVariantFuncRef();
6901 
6902       VariantMatchInfo VMI;
6903       OMPTraitInfo &TI = A->getTraitInfo();
6904       TI.getAsVariantMatchInfo(Context, VMI);
6905       if (!isVariantApplicableInContext(VMI, OMPCtx,
6906                                         /* DeviceSetOnly */ false))
6907         continue;
6908 
6909       VMIs.push_back(VMI);
6910       Exprs.push_back(VariantRef);
6911     }
6912 
6913     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6914   }
6915 
6916   ExprResult NewCall;
6917   do {
6918     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6919     if (BestIdx < 0)
6920       return Call;
6921     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6922     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6923 
6924     {
6925       // Try to build a (member) call expression for the current best applicable
6926       // variant expression. We allow this to fail in which case we continue
6927       // with the next best variant expression. The fail case is part of the
6928       // implementation defined behavior in the OpenMP standard when it talks
6929       // about what differences in the function prototypes: "Any differences
6930       // that the specific OpenMP context requires in the prototype of the
6931       // variant from the base function prototype are implementation defined."
6932       // This wording is there to allow the specialized variant to have a
6933       // different type than the base function. This is intended and OK but if
6934       // we cannot create a call the difference is not in the "implementation
6935       // defined range" we allow.
6936       Sema::TentativeAnalysisScope Trap(*this);
6937 
6938       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6939         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6940         BestExpr = MemberExpr::CreateImplicit(
6941             Context, MemberCall->getImplicitObjectArgument(),
6942             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6943             MemberCall->getValueKind(), MemberCall->getObjectKind());
6944       }
6945       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6946                               ExecConfig);
6947       if (NewCall.isUsable()) {
6948         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6949           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6950           QualType NewType = Context.mergeFunctionTypes(
6951               CalleeFnType, NewCalleeFnDecl->getType(),
6952               /* OfBlockPointer */ false,
6953               /* Unqualified */ false, /* AllowCXX */ true);
6954           if (!NewType.isNull())
6955             break;
6956           // Don't use the call if the function type was not compatible.
6957           NewCall = nullptr;
6958         }
6959       }
6960     }
6961 
6962     VMIs.erase(VMIs.begin() + BestIdx);
6963     Exprs.erase(Exprs.begin() + BestIdx);
6964   } while (!VMIs.empty());
6965 
6966   if (!NewCall.isUsable())
6967     return Call;
6968   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6969 }
6970 
6971 Optional<std::pair<FunctionDecl *, Expr *>>
6972 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6973                                         Expr *VariantRef, OMPTraitInfo &TI,
6974                                         unsigned NumAppendArgs,
6975                                         SourceRange SR) {
6976   if (!DG || DG.get().isNull())
6977     return None;
6978 
6979   const int VariantId = 1;
6980   // Must be applied only to single decl.
6981   if (!DG.get().isSingleDecl()) {
6982     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6983         << VariantId << SR;
6984     return None;
6985   }
6986   Decl *ADecl = DG.get().getSingleDecl();
6987   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6988     ADecl = FTD->getTemplatedDecl();
6989 
6990   // Decl must be a function.
6991   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6992   if (!FD) {
6993     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6994         << VariantId << SR;
6995     return None;
6996   }
6997 
6998   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6999     return FD->hasAttrs() &&
7000            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
7001             FD->hasAttr<TargetAttr>());
7002   };
7003   // OpenMP is not compatible with CPU-specific attributes.
7004   if (HasMultiVersionAttributes(FD)) {
7005     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
7006         << SR;
7007     return None;
7008   }
7009 
7010   // Allow #pragma omp declare variant only if the function is not used.
7011   if (FD->isUsed(false))
7012     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
7013         << FD->getLocation();
7014 
7015   // Check if the function was emitted already.
7016   const FunctionDecl *Definition;
7017   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
7018       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
7019     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
7020         << FD->getLocation();
7021 
7022   // The VariantRef must point to function.
7023   if (!VariantRef) {
7024     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
7025     return None;
7026   }
7027 
7028   auto ShouldDelayChecks = [](Expr *&E, bool) {
7029     return E && (E->isTypeDependent() || E->isValueDependent() ||
7030                  E->containsUnexpandedParameterPack() ||
7031                  E->isInstantiationDependent());
7032   };
7033   // Do not check templates, wait until instantiation.
7034   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
7035       TI.anyScoreOrCondition(ShouldDelayChecks))
7036     return std::make_pair(FD, VariantRef);
7037 
7038   // Deal with non-constant score and user condition expressions.
7039   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
7040                                                      bool IsScore) -> bool {
7041     if (!E || E->isIntegerConstantExpr(Context))
7042       return false;
7043 
7044     if (IsScore) {
7045       // We warn on non-constant scores and pretend they were not present.
7046       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
7047           << E;
7048       E = nullptr;
7049     } else {
7050       // We could replace a non-constant user condition with "false" but we
7051       // will soon need to handle these anyway for the dynamic version of
7052       // OpenMP context selectors.
7053       Diag(E->getExprLoc(),
7054            diag::err_omp_declare_variant_user_condition_not_constant)
7055           << E;
7056     }
7057     return true;
7058   };
7059   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
7060     return None;
7061 
7062   QualType AdjustedFnType = FD->getType();
7063   if (NumAppendArgs) {
7064     const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
7065     if (!PTy) {
7066       Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
7067           << SR;
7068       return None;
7069     }
7070     // Adjust the function type to account for an extra omp_interop_t for each
7071     // specified in the append_args clause.
7072     const TypeDecl *TD = nullptr;
7073     LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
7074                         SR.getBegin(), Sema::LookupOrdinaryName);
7075     if (LookupName(Result, getCurScope())) {
7076       NamedDecl *ND = Result.getFoundDecl();
7077       TD = dyn_cast_or_null<TypeDecl>(ND);
7078     }
7079     if (!TD) {
7080       Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
7081       return None;
7082     }
7083     QualType InteropType = Context.getTypeDeclType(TD);
7084     if (PTy->isVariadic()) {
7085       Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
7086       return None;
7087     }
7088     llvm::SmallVector<QualType, 8> Params;
7089     Params.append(PTy->param_type_begin(), PTy->param_type_end());
7090     Params.insert(Params.end(), NumAppendArgs, InteropType);
7091     AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
7092                                              PTy->getExtProtoInfo());
7093   }
7094 
7095   // Convert VariantRef expression to the type of the original function to
7096   // resolve possible conflicts.
7097   ExprResult VariantRefCast = VariantRef;
7098   if (LangOpts.CPlusPlus) {
7099     QualType FnPtrType;
7100     auto *Method = dyn_cast<CXXMethodDecl>(FD);
7101     if (Method && !Method->isStatic()) {
7102       const Type *ClassType =
7103           Context.getTypeDeclType(Method->getParent()).getTypePtr();
7104       FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
7105       ExprResult ER;
7106       {
7107         // Build adrr_of unary op to correctly handle type checks for member
7108         // functions.
7109         Sema::TentativeAnalysisScope Trap(*this);
7110         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
7111                                   VariantRef);
7112       }
7113       if (!ER.isUsable()) {
7114         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7115             << VariantId << VariantRef->getSourceRange();
7116         return None;
7117       }
7118       VariantRef = ER.get();
7119     } else {
7120       FnPtrType = Context.getPointerType(AdjustedFnType);
7121     }
7122     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
7123     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
7124       ImplicitConversionSequence ICS = TryImplicitConversion(
7125           VariantRef, FnPtrType.getUnqualifiedType(),
7126           /*SuppressUserConversions=*/false, AllowedExplicit::None,
7127           /*InOverloadResolution=*/false,
7128           /*CStyle=*/false,
7129           /*AllowObjCWritebackConversion=*/false);
7130       if (ICS.isFailure()) {
7131         Diag(VariantRef->getExprLoc(),
7132              diag::err_omp_declare_variant_incompat_types)
7133             << VariantRef->getType()
7134             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7135             << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
7136         return None;
7137       }
7138       VariantRefCast = PerformImplicitConversion(
7139           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7140       if (!VariantRefCast.isUsable())
7141         return None;
7142     }
7143     // Drop previously built artificial addr_of unary op for member functions.
7144     if (Method && !Method->isStatic()) {
7145       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7146       if (auto *UO = dyn_cast<UnaryOperator>(
7147               PossibleAddrOfVariantRef->IgnoreImplicit()))
7148         VariantRefCast = UO->getSubExpr();
7149     }
7150   }
7151 
7152   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7153   if (!ER.isUsable() ||
7154       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7155     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7156         << VariantId << VariantRef->getSourceRange();
7157     return None;
7158   }
7159 
7160   // The VariantRef must point to function.
7161   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7162   if (!DRE) {
7163     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7164         << VariantId << VariantRef->getSourceRange();
7165     return None;
7166   }
7167   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7168   if (!NewFD) {
7169     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7170         << VariantId << VariantRef->getSourceRange();
7171     return None;
7172   }
7173 
7174   // Check if function types are compatible in C.
7175   if (!LangOpts.CPlusPlus) {
7176     QualType NewType =
7177         Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
7178     if (NewType.isNull()) {
7179       Diag(VariantRef->getExprLoc(),
7180            diag::err_omp_declare_variant_incompat_types)
7181           << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
7182           << VariantRef->getSourceRange();
7183       return None;
7184     }
7185     if (NewType->isFunctionProtoType()) {
7186       if (FD->getType()->isFunctionNoProtoType())
7187         setPrototype(*this, FD, NewFD, NewType);
7188       else if (NewFD->getType()->isFunctionNoProtoType())
7189         setPrototype(*this, NewFD, FD, NewType);
7190     }
7191   }
7192 
7193   // Check if variant function is not marked with declare variant directive.
7194   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7195     Diag(VariantRef->getExprLoc(),
7196          diag::warn_omp_declare_variant_marked_as_declare_variant)
7197         << VariantRef->getSourceRange();
7198     SourceRange SR =
7199         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7200     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7201     return None;
7202   }
7203 
7204   enum DoesntSupport {
7205     VirtFuncs = 1,
7206     Constructors = 3,
7207     Destructors = 4,
7208     DeletedFuncs = 5,
7209     DefaultedFuncs = 6,
7210     ConstexprFuncs = 7,
7211     ConstevalFuncs = 8,
7212   };
7213   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7214     if (CXXFD->isVirtual()) {
7215       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7216           << VirtFuncs;
7217       return None;
7218     }
7219 
7220     if (isa<CXXConstructorDecl>(FD)) {
7221       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7222           << Constructors;
7223       return None;
7224     }
7225 
7226     if (isa<CXXDestructorDecl>(FD)) {
7227       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7228           << Destructors;
7229       return None;
7230     }
7231   }
7232 
7233   if (FD->isDeleted()) {
7234     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7235         << DeletedFuncs;
7236     return None;
7237   }
7238 
7239   if (FD->isDefaulted()) {
7240     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7241         << DefaultedFuncs;
7242     return None;
7243   }
7244 
7245   if (FD->isConstexpr()) {
7246     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7247         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7248     return None;
7249   }
7250 
7251   // Check general compatibility.
7252   if (areMultiversionVariantFunctionsCompatible(
7253           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7254           PartialDiagnosticAt(SourceLocation(),
7255                               PartialDiagnostic::NullDiagnostic()),
7256           PartialDiagnosticAt(
7257               VariantRef->getExprLoc(),
7258               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7259           PartialDiagnosticAt(VariantRef->getExprLoc(),
7260                               PDiag(diag::err_omp_declare_variant_diff)
7261                                   << FD->getLocation()),
7262           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7263           /*CLinkageMayDiffer=*/true))
7264     return None;
7265   return std::make_pair(FD, cast<Expr>(DRE));
7266 }
7267 
7268 void Sema::ActOnOpenMPDeclareVariantDirective(
7269     FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
7270     ArrayRef<Expr *> AdjustArgsNothing,
7271     ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
7272     ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
7273     SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
7274     SourceRange SR) {
7275 
7276   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7277   // An adjust_args clause or append_args clause can only be specified if the
7278   // dispatch selector of the construct selector set appears in the match
7279   // clause.
7280 
7281   SmallVector<Expr *, 8> AllAdjustArgs;
7282   llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
7283   llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
7284 
7285   if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
7286     VariantMatchInfo VMI;
7287     TI.getAsVariantMatchInfo(Context, VMI);
7288     if (!llvm::is_contained(
7289             VMI.ConstructTraits,
7290             llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
7291       if (!AllAdjustArgs.empty())
7292         Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7293             << getOpenMPClauseName(OMPC_adjust_args);
7294       if (!AppendArgs.empty())
7295         Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7296             << getOpenMPClauseName(OMPC_append_args);
7297       return;
7298     }
7299   }
7300 
7301   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7302   // Each argument can only appear in a single adjust_args clause for each
7303   // declare variant directive.
7304   llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
7305 
7306   for (Expr *E : AllAdjustArgs) {
7307     E = E->IgnoreParenImpCasts();
7308     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
7309       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7310         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7311         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7312             FD->getParamDecl(PVD->getFunctionScopeIndex())
7313                     ->getCanonicalDecl() == CanonPVD) {
7314           // It's a parameter of the function, check duplicates.
7315           if (!AdjustVars.insert(CanonPVD).second) {
7316             Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
7317                 << PVD;
7318             return;
7319           }
7320           continue;
7321         }
7322       }
7323     }
7324     // Anything that is not a function parameter is an error.
7325     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
7326     return;
7327   }
7328 
7329   auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
7330       Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
7331       AdjustArgsNothing.size(),
7332       const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
7333       AdjustArgsNeedDevicePtr.size(),
7334       const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
7335       AppendArgs.size(), SR);
7336   FD->addAttr(NewAttr);
7337 }
7338 
7339 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7340                                               Stmt *AStmt,
7341                                               SourceLocation StartLoc,
7342                                               SourceLocation EndLoc) {
7343   if (!AStmt)
7344     return StmtError();
7345 
7346   auto *CS = cast<CapturedStmt>(AStmt);
7347   // 1.2.2 OpenMP Language Terminology
7348   // Structured block - An executable statement with a single entry at the
7349   // top and a single exit at the bottom.
7350   // The point of exit cannot be a branch out of the structured block.
7351   // longjmp() and throw() must not violate the entry/exit criteria.
7352   CS->getCapturedDecl()->setNothrow();
7353 
7354   setFunctionHasBranchProtectedScope();
7355 
7356   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7357                                       DSAStack->getTaskgroupReductionRef(),
7358                                       DSAStack->isCancelRegion());
7359 }
7360 
7361 namespace {
7362 /// Iteration space of a single for loop.
7363 struct LoopIterationSpace final {
7364   /// True if the condition operator is the strict compare operator (<, > or
7365   /// !=).
7366   bool IsStrictCompare = false;
7367   /// Condition of the loop.
7368   Expr *PreCond = nullptr;
7369   /// This expression calculates the number of iterations in the loop.
7370   /// It is always possible to calculate it before starting the loop.
7371   Expr *NumIterations = nullptr;
7372   /// The loop counter variable.
7373   Expr *CounterVar = nullptr;
7374   /// Private loop counter variable.
7375   Expr *PrivateCounterVar = nullptr;
7376   /// This is initializer for the initial value of #CounterVar.
7377   Expr *CounterInit = nullptr;
7378   /// This is step for the #CounterVar used to generate its update:
7379   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7380   Expr *CounterStep = nullptr;
7381   /// Should step be subtracted?
7382   bool Subtract = false;
7383   /// Source range of the loop init.
7384   SourceRange InitSrcRange;
7385   /// Source range of the loop condition.
7386   SourceRange CondSrcRange;
7387   /// Source range of the loop increment.
7388   SourceRange IncSrcRange;
7389   /// Minimum value that can have the loop control variable. Used to support
7390   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7391   /// since only such variables can be used in non-loop invariant expressions.
7392   Expr *MinValue = nullptr;
7393   /// Maximum value that can have the loop control variable. Used to support
7394   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7395   /// since only such variables can be used in non-loop invariant expressions.
7396   Expr *MaxValue = nullptr;
7397   /// true, if the lower bound depends on the outer loop control var.
7398   bool IsNonRectangularLB = false;
7399   /// true, if the upper bound depends on the outer loop control var.
7400   bool IsNonRectangularUB = false;
7401   /// Index of the loop this loop depends on and forms non-rectangular loop
7402   /// nest.
7403   unsigned LoopDependentIdx = 0;
7404   /// Final condition for the non-rectangular loop nest support. It is used to
7405   /// check that the number of iterations for this particular counter must be
7406   /// finished.
7407   Expr *FinalCondition = nullptr;
7408 };
7409 
7410 /// Helper class for checking canonical form of the OpenMP loops and
7411 /// extracting iteration space of each loop in the loop nest, that will be used
7412 /// for IR generation.
7413 class OpenMPIterationSpaceChecker {
7414   /// Reference to Sema.
7415   Sema &SemaRef;
7416   /// Does the loop associated directive support non-rectangular loops?
7417   bool SupportsNonRectangular;
7418   /// Data-sharing stack.
7419   DSAStackTy &Stack;
7420   /// A location for diagnostics (when there is no some better location).
7421   SourceLocation DefaultLoc;
7422   /// A location for diagnostics (when increment is not compatible).
7423   SourceLocation ConditionLoc;
7424   /// A source location for referring to loop init later.
7425   SourceRange InitSrcRange;
7426   /// A source location for referring to condition later.
7427   SourceRange ConditionSrcRange;
7428   /// A source location for referring to increment later.
7429   SourceRange IncrementSrcRange;
7430   /// Loop variable.
7431   ValueDecl *LCDecl = nullptr;
7432   /// Reference to loop variable.
7433   Expr *LCRef = nullptr;
7434   /// Lower bound (initializer for the var).
7435   Expr *LB = nullptr;
7436   /// Upper bound.
7437   Expr *UB = nullptr;
7438   /// Loop step (increment).
7439   Expr *Step = nullptr;
7440   /// This flag is true when condition is one of:
7441   ///   Var <  UB
7442   ///   Var <= UB
7443   ///   UB  >  Var
7444   ///   UB  >= Var
7445   /// This will have no value when the condition is !=
7446   llvm::Optional<bool> TestIsLessOp;
7447   /// This flag is true when condition is strict ( < or > ).
7448   bool TestIsStrictOp = false;
7449   /// This flag is true when step is subtracted on each iteration.
7450   bool SubtractStep = false;
7451   /// The outer loop counter this loop depends on (if any).
7452   const ValueDecl *DepDecl = nullptr;
7453   /// Contains number of loop (starts from 1) on which loop counter init
7454   /// expression of this loop depends on.
7455   Optional<unsigned> InitDependOnLC;
7456   /// Contains number of loop (starts from 1) on which loop counter condition
7457   /// expression of this loop depends on.
7458   Optional<unsigned> CondDependOnLC;
7459   /// Checks if the provide statement depends on the loop counter.
7460   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7461   /// Original condition required for checking of the exit condition for
7462   /// non-rectangular loop.
7463   Expr *Condition = nullptr;
7464 
7465 public:
7466   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7467                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7468       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7469         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7470   /// Check init-expr for canonical loop form and save loop counter
7471   /// variable - #Var and its initialization value - #LB.
7472   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7473   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7474   /// for less/greater and for strict/non-strict comparison.
7475   bool checkAndSetCond(Expr *S);
7476   /// Check incr-expr for canonical loop form and return true if it
7477   /// does not conform, otherwise save loop step (#Step).
7478   bool checkAndSetInc(Expr *S);
7479   /// Return the loop counter variable.
7480   ValueDecl *getLoopDecl() const { return LCDecl; }
7481   /// Return the reference expression to loop counter variable.
7482   Expr *getLoopDeclRefExpr() const { return LCRef; }
7483   /// Source range of the loop init.
7484   SourceRange getInitSrcRange() const { return InitSrcRange; }
7485   /// Source range of the loop condition.
7486   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7487   /// Source range of the loop increment.
7488   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7489   /// True if the step should be subtracted.
7490   bool shouldSubtractStep() const { return SubtractStep; }
7491   /// True, if the compare operator is strict (<, > or !=).
7492   bool isStrictTestOp() const { return TestIsStrictOp; }
7493   /// Build the expression to calculate the number of iterations.
7494   Expr *buildNumIterations(
7495       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7496       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7497   /// Build the precondition expression for the loops.
7498   Expr *
7499   buildPreCond(Scope *S, Expr *Cond,
7500                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7501   /// Build reference expression to the counter be used for codegen.
7502   DeclRefExpr *
7503   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7504                   DSAStackTy &DSA) const;
7505   /// Build reference expression to the private counter be used for
7506   /// codegen.
7507   Expr *buildPrivateCounterVar() const;
7508   /// Build initialization of the counter be used for codegen.
7509   Expr *buildCounterInit() const;
7510   /// Build step of the counter be used for codegen.
7511   Expr *buildCounterStep() const;
7512   /// Build loop data with counter value for depend clauses in ordered
7513   /// directives.
7514   Expr *
7515   buildOrderedLoopData(Scope *S, Expr *Counter,
7516                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7517                        SourceLocation Loc, Expr *Inc = nullptr,
7518                        OverloadedOperatorKind OOK = OO_Amp);
7519   /// Builds the minimum value for the loop counter.
7520   std::pair<Expr *, Expr *> buildMinMaxValues(
7521       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7522   /// Builds final condition for the non-rectangular loops.
7523   Expr *buildFinalCondition(Scope *S) const;
7524   /// Return true if any expression is dependent.
7525   bool dependent() const;
7526   /// Returns true if the initializer forms non-rectangular loop.
7527   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7528   /// Returns true if the condition forms non-rectangular loop.
7529   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7530   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7531   unsigned getLoopDependentIdx() const {
7532     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7533   }
7534 
7535 private:
7536   /// Check the right-hand side of an assignment in the increment
7537   /// expression.
7538   bool checkAndSetIncRHS(Expr *RHS);
7539   /// Helper to set loop counter variable and its initializer.
7540   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7541                       bool EmitDiags);
7542   /// Helper to set upper bound.
7543   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7544              SourceRange SR, SourceLocation SL);
7545   /// Helper to set loop increment.
7546   bool setStep(Expr *NewStep, bool Subtract);
7547 };
7548 
7549 bool OpenMPIterationSpaceChecker::dependent() const {
7550   if (!LCDecl) {
7551     assert(!LB && !UB && !Step);
7552     return false;
7553   }
7554   return LCDecl->getType()->isDependentType() ||
7555          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7556          (Step && Step->isValueDependent());
7557 }
7558 
7559 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7560                                                  Expr *NewLCRefExpr,
7561                                                  Expr *NewLB, bool EmitDiags) {
7562   // State consistency checking to ensure correct usage.
7563   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7564          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7565   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7566     return true;
7567   LCDecl = getCanonicalDecl(NewLCDecl);
7568   LCRef = NewLCRefExpr;
7569   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7570     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7571       if ((Ctor->isCopyOrMoveConstructor() ||
7572            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7573           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7574         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7575   LB = NewLB;
7576   if (EmitDiags)
7577     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7578   return false;
7579 }
7580 
7581 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7582                                         llvm::Optional<bool> LessOp,
7583                                         bool StrictOp, SourceRange SR,
7584                                         SourceLocation SL) {
7585   // State consistency checking to ensure correct usage.
7586   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7587          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7588   if (!NewUB || NewUB->containsErrors())
7589     return true;
7590   UB = NewUB;
7591   if (LessOp)
7592     TestIsLessOp = LessOp;
7593   TestIsStrictOp = StrictOp;
7594   ConditionSrcRange = SR;
7595   ConditionLoc = SL;
7596   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7597   return false;
7598 }
7599 
7600 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7601   // State consistency checking to ensure correct usage.
7602   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7603   if (!NewStep || NewStep->containsErrors())
7604     return true;
7605   if (!NewStep->isValueDependent()) {
7606     // Check that the step is integer expression.
7607     SourceLocation StepLoc = NewStep->getBeginLoc();
7608     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7609         StepLoc, getExprAsWritten(NewStep));
7610     if (Val.isInvalid())
7611       return true;
7612     NewStep = Val.get();
7613 
7614     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7615     //  If test-expr is of form var relational-op b and relational-op is < or
7616     //  <= then incr-expr must cause var to increase on each iteration of the
7617     //  loop. If test-expr is of form var relational-op b and relational-op is
7618     //  > or >= then incr-expr must cause var to decrease on each iteration of
7619     //  the loop.
7620     //  If test-expr is of form b relational-op var and relational-op is < or
7621     //  <= then incr-expr must cause var to decrease on each iteration of the
7622     //  loop. If test-expr is of form b relational-op var and relational-op is
7623     //  > or >= then incr-expr must cause var to increase on each iteration of
7624     //  the loop.
7625     Optional<llvm::APSInt> Result =
7626         NewStep->getIntegerConstantExpr(SemaRef.Context);
7627     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7628     bool IsConstNeg =
7629         Result && Result->isSigned() && (Subtract != Result->isNegative());
7630     bool IsConstPos =
7631         Result && Result->isSigned() && (Subtract == Result->isNegative());
7632     bool IsConstZero = Result && !Result->getBoolValue();
7633 
7634     // != with increment is treated as <; != with decrement is treated as >
7635     if (!TestIsLessOp.hasValue())
7636       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7637     if (UB &&
7638         (IsConstZero || (TestIsLessOp.getValue()
7639                              ? (IsConstNeg || (IsUnsigned && Subtract))
7640                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
7641       SemaRef.Diag(NewStep->getExprLoc(),
7642                    diag::err_omp_loop_incr_not_compatible)
7643           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7644       SemaRef.Diag(ConditionLoc,
7645                    diag::note_omp_loop_cond_requres_compatible_incr)
7646           << TestIsLessOp.getValue() << ConditionSrcRange;
7647       return true;
7648     }
7649     if (TestIsLessOp.getValue() == Subtract) {
7650       NewStep =
7651           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7652               .get();
7653       Subtract = !Subtract;
7654     }
7655   }
7656 
7657   Step = NewStep;
7658   SubtractStep = Subtract;
7659   return false;
7660 }
7661 
7662 namespace {
7663 /// Checker for the non-rectangular loops. Checks if the initializer or
7664 /// condition expression references loop counter variable.
7665 class LoopCounterRefChecker final
7666     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7667   Sema &SemaRef;
7668   DSAStackTy &Stack;
7669   const ValueDecl *CurLCDecl = nullptr;
7670   const ValueDecl *DepDecl = nullptr;
7671   const ValueDecl *PrevDepDecl = nullptr;
7672   bool IsInitializer = true;
7673   bool SupportsNonRectangular;
7674   unsigned BaseLoopId = 0;
7675   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7676     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7677       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7678           << (IsInitializer ? 0 : 1);
7679       return false;
7680     }
7681     const auto &&Data = Stack.isLoopControlVariable(VD);
7682     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7683     // The type of the loop iterator on which we depend may not have a random
7684     // access iterator type.
7685     if (Data.first && VD->getType()->isRecordType()) {
7686       SmallString<128> Name;
7687       llvm::raw_svector_ostream OS(Name);
7688       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7689                                /*Qualified=*/true);
7690       SemaRef.Diag(E->getExprLoc(),
7691                    diag::err_omp_wrong_dependency_iterator_type)
7692           << OS.str();
7693       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7694       return false;
7695     }
7696     if (Data.first && !SupportsNonRectangular) {
7697       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7698       return false;
7699     }
7700     if (Data.first &&
7701         (DepDecl || (PrevDepDecl &&
7702                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7703       if (!DepDecl && PrevDepDecl)
7704         DepDecl = PrevDepDecl;
7705       SmallString<128> Name;
7706       llvm::raw_svector_ostream OS(Name);
7707       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7708                                     /*Qualified=*/true);
7709       SemaRef.Diag(E->getExprLoc(),
7710                    diag::err_omp_invariant_or_linear_dependency)
7711           << OS.str();
7712       return false;
7713     }
7714     if (Data.first) {
7715       DepDecl = VD;
7716       BaseLoopId = Data.first;
7717     }
7718     return Data.first;
7719   }
7720 
7721 public:
7722   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7723     const ValueDecl *VD = E->getDecl();
7724     if (isa<VarDecl>(VD))
7725       return checkDecl(E, VD);
7726     return false;
7727   }
7728   bool VisitMemberExpr(const MemberExpr *E) {
7729     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7730       const ValueDecl *VD = E->getMemberDecl();
7731       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7732         return checkDecl(E, VD);
7733     }
7734     return false;
7735   }
7736   bool VisitStmt(const Stmt *S) {
7737     bool Res = false;
7738     for (const Stmt *Child : S->children())
7739       Res = (Child && Visit(Child)) || Res;
7740     return Res;
7741   }
7742   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7743                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7744                                  const ValueDecl *PrevDepDecl = nullptr,
7745                                  bool SupportsNonRectangular = true)
7746       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7747         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7748         SupportsNonRectangular(SupportsNonRectangular) {}
7749   unsigned getBaseLoopId() const {
7750     assert(CurLCDecl && "Expected loop dependency.");
7751     return BaseLoopId;
7752   }
7753   const ValueDecl *getDepDecl() const {
7754     assert(CurLCDecl && "Expected loop dependency.");
7755     return DepDecl;
7756   }
7757 };
7758 } // namespace
7759 
7760 Optional<unsigned>
7761 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7762                                                      bool IsInitializer) {
7763   // Check for the non-rectangular loops.
7764   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7765                                         DepDecl, SupportsNonRectangular);
7766   if (LoopStmtChecker.Visit(S)) {
7767     DepDecl = LoopStmtChecker.getDepDecl();
7768     return LoopStmtChecker.getBaseLoopId();
7769   }
7770   return llvm::None;
7771 }
7772 
7773 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7774   // Check init-expr for canonical loop form and save loop counter
7775   // variable - #Var and its initialization value - #LB.
7776   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7777   //   var = lb
7778   //   integer-type var = lb
7779   //   random-access-iterator-type var = lb
7780   //   pointer-type var = lb
7781   //
7782   if (!S) {
7783     if (EmitDiags) {
7784       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7785     }
7786     return true;
7787   }
7788   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7789     if (!ExprTemp->cleanupsHaveSideEffects())
7790       S = ExprTemp->getSubExpr();
7791 
7792   InitSrcRange = S->getSourceRange();
7793   if (Expr *E = dyn_cast<Expr>(S))
7794     S = E->IgnoreParens();
7795   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7796     if (BO->getOpcode() == BO_Assign) {
7797       Expr *LHS = BO->getLHS()->IgnoreParens();
7798       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7799         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7800           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7801             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7802                                   EmitDiags);
7803         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7804       }
7805       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7806         if (ME->isArrow() &&
7807             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7808           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7809                                 EmitDiags);
7810       }
7811     }
7812   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7813     if (DS->isSingleDecl()) {
7814       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7815         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7816           // Accept non-canonical init form here but emit ext. warning.
7817           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7818             SemaRef.Diag(S->getBeginLoc(),
7819                          diag::ext_omp_loop_not_canonical_init)
7820                 << S->getSourceRange();
7821           return setLCDeclAndLB(
7822               Var,
7823               buildDeclRefExpr(SemaRef, Var,
7824                                Var->getType().getNonReferenceType(),
7825                                DS->getBeginLoc()),
7826               Var->getInit(), EmitDiags);
7827         }
7828       }
7829     }
7830   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7831     if (CE->getOperator() == OO_Equal) {
7832       Expr *LHS = CE->getArg(0);
7833       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7834         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7835           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7836             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7837                                   EmitDiags);
7838         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7839       }
7840       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7841         if (ME->isArrow() &&
7842             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7843           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7844                                 EmitDiags);
7845       }
7846     }
7847   }
7848 
7849   if (dependent() || SemaRef.CurContext->isDependentContext())
7850     return false;
7851   if (EmitDiags) {
7852     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7853         << S->getSourceRange();
7854   }
7855   return true;
7856 }
7857 
7858 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7859 /// variable (which may be the loop variable) if possible.
7860 static const ValueDecl *getInitLCDecl(const Expr *E) {
7861   if (!E)
7862     return nullptr;
7863   E = getExprAsWritten(E);
7864   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7865     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7866       if ((Ctor->isCopyOrMoveConstructor() ||
7867            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7868           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7869         E = CE->getArg(0)->IgnoreParenImpCasts();
7870   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7871     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7872       return getCanonicalDecl(VD);
7873   }
7874   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7875     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7876       return getCanonicalDecl(ME->getMemberDecl());
7877   return nullptr;
7878 }
7879 
7880 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7881   // Check test-expr for canonical form, save upper-bound UB, flags for
7882   // less/greater and for strict/non-strict comparison.
7883   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7884   //   var relational-op b
7885   //   b relational-op var
7886   //
7887   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7888   if (!S) {
7889     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7890         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7891     return true;
7892   }
7893   Condition = S;
7894   S = getExprAsWritten(S);
7895   SourceLocation CondLoc = S->getBeginLoc();
7896   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7897                                BinaryOperatorKind Opcode, const Expr *LHS,
7898                                const Expr *RHS, SourceRange SR,
7899                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7900     if (BinaryOperator::isRelationalOp(Opcode)) {
7901       if (getInitLCDecl(LHS) == LCDecl)
7902         return setUB(const_cast<Expr *>(RHS),
7903                      (Opcode == BO_LT || Opcode == BO_LE),
7904                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7905       if (getInitLCDecl(RHS) == LCDecl)
7906         return setUB(const_cast<Expr *>(LHS),
7907                      (Opcode == BO_GT || Opcode == BO_GE),
7908                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7909     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7910       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7911                    /*LessOp=*/llvm::None,
7912                    /*StrictOp=*/true, SR, OpLoc);
7913     }
7914     return llvm::None;
7915   };
7916   llvm::Optional<bool> Res;
7917   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7918     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7919     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7920                           RBO->getOperatorLoc());
7921   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7922     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7923                           BO->getSourceRange(), BO->getOperatorLoc());
7924   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7925     if (CE->getNumArgs() == 2) {
7926       Res = CheckAndSetCond(
7927           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7928           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7929     }
7930   }
7931   if (Res.hasValue())
7932     return *Res;
7933   if (dependent() || SemaRef.CurContext->isDependentContext())
7934     return false;
7935   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7936       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7937   return true;
7938 }
7939 
7940 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7941   // RHS of canonical loop form increment can be:
7942   //   var + incr
7943   //   incr + var
7944   //   var - incr
7945   //
7946   RHS = RHS->IgnoreParenImpCasts();
7947   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7948     if (BO->isAdditiveOp()) {
7949       bool IsAdd = BO->getOpcode() == BO_Add;
7950       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7951         return setStep(BO->getRHS(), !IsAdd);
7952       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7953         return setStep(BO->getLHS(), /*Subtract=*/false);
7954     }
7955   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7956     bool IsAdd = CE->getOperator() == OO_Plus;
7957     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7958       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7959         return setStep(CE->getArg(1), !IsAdd);
7960       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7961         return setStep(CE->getArg(0), /*Subtract=*/false);
7962     }
7963   }
7964   if (dependent() || SemaRef.CurContext->isDependentContext())
7965     return false;
7966   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7967       << RHS->getSourceRange() << LCDecl;
7968   return true;
7969 }
7970 
7971 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7972   // Check incr-expr for canonical loop form and return true if it
7973   // does not conform.
7974   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7975   //   ++var
7976   //   var++
7977   //   --var
7978   //   var--
7979   //   var += incr
7980   //   var -= incr
7981   //   var = var + incr
7982   //   var = incr + var
7983   //   var = var - incr
7984   //
7985   if (!S) {
7986     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7987     return true;
7988   }
7989   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7990     if (!ExprTemp->cleanupsHaveSideEffects())
7991       S = ExprTemp->getSubExpr();
7992 
7993   IncrementSrcRange = S->getSourceRange();
7994   S = S->IgnoreParens();
7995   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7996     if (UO->isIncrementDecrementOp() &&
7997         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7998       return setStep(SemaRef
7999                          .ActOnIntegerConstant(UO->getBeginLoc(),
8000                                                (UO->isDecrementOp() ? -1 : 1))
8001                          .get(),
8002                      /*Subtract=*/false);
8003   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
8004     switch (BO->getOpcode()) {
8005     case BO_AddAssign:
8006     case BO_SubAssign:
8007       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8008         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
8009       break;
8010     case BO_Assign:
8011       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8012         return checkAndSetIncRHS(BO->getRHS());
8013       break;
8014     default:
8015       break;
8016     }
8017   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8018     switch (CE->getOperator()) {
8019     case OO_PlusPlus:
8020     case OO_MinusMinus:
8021       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8022         return setStep(SemaRef
8023                            .ActOnIntegerConstant(
8024                                CE->getBeginLoc(),
8025                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
8026                            .get(),
8027                        /*Subtract=*/false);
8028       break;
8029     case OO_PlusEqual:
8030     case OO_MinusEqual:
8031       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8032         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
8033       break;
8034     case OO_Equal:
8035       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8036         return checkAndSetIncRHS(CE->getArg(1));
8037       break;
8038     default:
8039       break;
8040     }
8041   }
8042   if (dependent() || SemaRef.CurContext->isDependentContext())
8043     return false;
8044   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8045       << S->getSourceRange() << LCDecl;
8046   return true;
8047 }
8048 
8049 static ExprResult
8050 tryBuildCapture(Sema &SemaRef, Expr *Capture,
8051                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8052   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
8053     return Capture;
8054   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
8055     return SemaRef.PerformImplicitConversion(
8056         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
8057         /*AllowExplicit=*/true);
8058   auto I = Captures.find(Capture);
8059   if (I != Captures.end())
8060     return buildCapture(SemaRef, Capture, I->second);
8061   DeclRefExpr *Ref = nullptr;
8062   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
8063   Captures[Capture] = Ref;
8064   return Res;
8065 }
8066 
8067 /// Calculate number of iterations, transforming to unsigned, if number of
8068 /// iterations may be larger than the original type.
8069 static Expr *
8070 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
8071                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
8072                   bool TestIsStrictOp, bool RoundToStep,
8073                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8074   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8075   if (!NewStep.isUsable())
8076     return nullptr;
8077   llvm::APSInt LRes, SRes;
8078   bool IsLowerConst = false, IsStepConst = false;
8079   if (Optional<llvm::APSInt> Res =
8080           Lower->getIntegerConstantExpr(SemaRef.Context)) {
8081     LRes = *Res;
8082     IsLowerConst = true;
8083   }
8084   if (Optional<llvm::APSInt> Res =
8085           Step->getIntegerConstantExpr(SemaRef.Context)) {
8086     SRes = *Res;
8087     IsStepConst = true;
8088   }
8089   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
8090                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
8091                           (TestIsStrictOp && LRes.isStrictlyPositive()));
8092   bool NeedToReorganize = false;
8093   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
8094   if (!NoNeedToConvert && IsLowerConst &&
8095       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
8096     NoNeedToConvert = true;
8097     if (RoundToStep) {
8098       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
8099                         ? LRes.getBitWidth()
8100                         : SRes.getBitWidth();
8101       LRes = LRes.extend(BW + 1);
8102       LRes.setIsSigned(true);
8103       SRes = SRes.extend(BW + 1);
8104       SRes.setIsSigned(true);
8105       LRes -= SRes;
8106       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
8107       LRes = LRes.trunc(BW);
8108     }
8109     if (TestIsStrictOp) {
8110       unsigned BW = LRes.getBitWidth();
8111       LRes = LRes.extend(BW + 1);
8112       LRes.setIsSigned(true);
8113       ++LRes;
8114       NoNeedToConvert =
8115           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
8116       // truncate to the original bitwidth.
8117       LRes = LRes.trunc(BW);
8118     }
8119     NeedToReorganize = NoNeedToConvert;
8120   }
8121   llvm::APSInt URes;
8122   bool IsUpperConst = false;
8123   if (Optional<llvm::APSInt> Res =
8124           Upper->getIntegerConstantExpr(SemaRef.Context)) {
8125     URes = *Res;
8126     IsUpperConst = true;
8127   }
8128   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
8129       (!RoundToStep || IsStepConst)) {
8130     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
8131                                                           : URes.getBitWidth();
8132     LRes = LRes.extend(BW + 1);
8133     LRes.setIsSigned(true);
8134     URes = URes.extend(BW + 1);
8135     URes.setIsSigned(true);
8136     URes -= LRes;
8137     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
8138     NeedToReorganize = NoNeedToConvert;
8139   }
8140   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
8141   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
8142   // unsigned.
8143   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
8144       !LCTy->isDependentType() && LCTy->isIntegerType()) {
8145     QualType LowerTy = Lower->getType();
8146     QualType UpperTy = Upper->getType();
8147     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
8148     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
8149     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
8150         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
8151       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
8152           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
8153       Upper =
8154           SemaRef
8155               .PerformImplicitConversion(
8156                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8157                   CastType, Sema::AA_Converting)
8158               .get();
8159       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
8160       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
8161     }
8162   }
8163   if (!Lower || !Upper || NewStep.isInvalid())
8164     return nullptr;
8165 
8166   ExprResult Diff;
8167   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
8168   // 1]).
8169   if (NeedToReorganize) {
8170     Diff = Lower;
8171 
8172     if (RoundToStep) {
8173       // Lower - Step
8174       Diff =
8175           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
8176       if (!Diff.isUsable())
8177         return nullptr;
8178     }
8179 
8180     // Lower - Step [+ 1]
8181     if (TestIsStrictOp)
8182       Diff = SemaRef.BuildBinOp(
8183           S, DefaultLoc, BO_Add, Diff.get(),
8184           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8185     if (!Diff.isUsable())
8186       return nullptr;
8187 
8188     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8189     if (!Diff.isUsable())
8190       return nullptr;
8191 
8192     // Upper - (Lower - Step [+ 1]).
8193     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
8194     if (!Diff.isUsable())
8195       return nullptr;
8196   } else {
8197     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8198 
8199     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8200       // BuildBinOp already emitted error, this one is to point user to upper
8201       // and lower bound, and to tell what is passed to 'operator-'.
8202       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8203           << Upper->getSourceRange() << Lower->getSourceRange();
8204       return nullptr;
8205     }
8206 
8207     if (!Diff.isUsable())
8208       return nullptr;
8209 
8210     // Upper - Lower [- 1]
8211     if (TestIsStrictOp)
8212       Diff = SemaRef.BuildBinOp(
8213           S, DefaultLoc, BO_Sub, Diff.get(),
8214           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8215     if (!Diff.isUsable())
8216       return nullptr;
8217 
8218     if (RoundToStep) {
8219       // Upper - Lower [- 1] + Step
8220       Diff =
8221           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8222       if (!Diff.isUsable())
8223         return nullptr;
8224     }
8225   }
8226 
8227   // Parentheses (for dumping/debugging purposes only).
8228   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8229   if (!Diff.isUsable())
8230     return nullptr;
8231 
8232   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8233   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8234   if (!Diff.isUsable())
8235     return nullptr;
8236 
8237   return Diff.get();
8238 }
8239 
8240 /// Build the expression to calculate the number of iterations.
8241 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8242     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8243     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8244   QualType VarType = LCDecl->getType().getNonReferenceType();
8245   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8246       !SemaRef.getLangOpts().CPlusPlus)
8247     return nullptr;
8248   Expr *LBVal = LB;
8249   Expr *UBVal = UB;
8250   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8251   // max(LB(MinVal), LB(MaxVal))
8252   if (InitDependOnLC) {
8253     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8254     if (!IS.MinValue || !IS.MaxValue)
8255       return nullptr;
8256     // OuterVar = Min
8257     ExprResult MinValue =
8258         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8259     if (!MinValue.isUsable())
8260       return nullptr;
8261 
8262     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8263                                              IS.CounterVar, MinValue.get());
8264     if (!LBMinVal.isUsable())
8265       return nullptr;
8266     // OuterVar = Min, LBVal
8267     LBMinVal =
8268         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8269     if (!LBMinVal.isUsable())
8270       return nullptr;
8271     // (OuterVar = Min, LBVal)
8272     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8273     if (!LBMinVal.isUsable())
8274       return nullptr;
8275 
8276     // OuterVar = Max
8277     ExprResult MaxValue =
8278         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8279     if (!MaxValue.isUsable())
8280       return nullptr;
8281 
8282     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8283                                              IS.CounterVar, MaxValue.get());
8284     if (!LBMaxVal.isUsable())
8285       return nullptr;
8286     // OuterVar = Max, LBVal
8287     LBMaxVal =
8288         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8289     if (!LBMaxVal.isUsable())
8290       return nullptr;
8291     // (OuterVar = Max, LBVal)
8292     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8293     if (!LBMaxVal.isUsable())
8294       return nullptr;
8295 
8296     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8297     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8298     if (!LBMin || !LBMax)
8299       return nullptr;
8300     // LB(MinVal) < LB(MaxVal)
8301     ExprResult MinLessMaxRes =
8302         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8303     if (!MinLessMaxRes.isUsable())
8304       return nullptr;
8305     Expr *MinLessMax =
8306         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8307     if (!MinLessMax)
8308       return nullptr;
8309     if (TestIsLessOp.getValue()) {
8310       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8311       // LB(MaxVal))
8312       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8313                                                     MinLessMax, LBMin, LBMax);
8314       if (!MinLB.isUsable())
8315         return nullptr;
8316       LBVal = MinLB.get();
8317     } else {
8318       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8319       // LB(MaxVal))
8320       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8321                                                     MinLessMax, LBMax, LBMin);
8322       if (!MaxLB.isUsable())
8323         return nullptr;
8324       LBVal = MaxLB.get();
8325     }
8326   }
8327   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8328   // min(UB(MinVal), UB(MaxVal))
8329   if (CondDependOnLC) {
8330     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8331     if (!IS.MinValue || !IS.MaxValue)
8332       return nullptr;
8333     // OuterVar = Min
8334     ExprResult MinValue =
8335         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8336     if (!MinValue.isUsable())
8337       return nullptr;
8338 
8339     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8340                                              IS.CounterVar, MinValue.get());
8341     if (!UBMinVal.isUsable())
8342       return nullptr;
8343     // OuterVar = Min, UBVal
8344     UBMinVal =
8345         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8346     if (!UBMinVal.isUsable())
8347       return nullptr;
8348     // (OuterVar = Min, UBVal)
8349     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8350     if (!UBMinVal.isUsable())
8351       return nullptr;
8352 
8353     // OuterVar = Max
8354     ExprResult MaxValue =
8355         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8356     if (!MaxValue.isUsable())
8357       return nullptr;
8358 
8359     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8360                                              IS.CounterVar, MaxValue.get());
8361     if (!UBMaxVal.isUsable())
8362       return nullptr;
8363     // OuterVar = Max, UBVal
8364     UBMaxVal =
8365         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8366     if (!UBMaxVal.isUsable())
8367       return nullptr;
8368     // (OuterVar = Max, UBVal)
8369     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8370     if (!UBMaxVal.isUsable())
8371       return nullptr;
8372 
8373     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8374     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8375     if (!UBMin || !UBMax)
8376       return nullptr;
8377     // UB(MinVal) > UB(MaxVal)
8378     ExprResult MinGreaterMaxRes =
8379         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8380     if (!MinGreaterMaxRes.isUsable())
8381       return nullptr;
8382     Expr *MinGreaterMax =
8383         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8384     if (!MinGreaterMax)
8385       return nullptr;
8386     if (TestIsLessOp.getValue()) {
8387       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8388       // UB(MaxVal))
8389       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8390           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8391       if (!MaxUB.isUsable())
8392         return nullptr;
8393       UBVal = MaxUB.get();
8394     } else {
8395       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8396       // UB(MaxVal))
8397       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8398           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8399       if (!MinUB.isUsable())
8400         return nullptr;
8401       UBVal = MinUB.get();
8402     }
8403   }
8404   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8405   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8406   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8407   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8408   if (!Upper || !Lower)
8409     return nullptr;
8410 
8411   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8412                                       Step, VarType, TestIsStrictOp,
8413                                       /*RoundToStep=*/true, Captures);
8414   if (!Diff.isUsable())
8415     return nullptr;
8416 
8417   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8418   QualType Type = Diff.get()->getType();
8419   ASTContext &C = SemaRef.Context;
8420   bool UseVarType = VarType->hasIntegerRepresentation() &&
8421                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8422   if (!Type->isIntegerType() || UseVarType) {
8423     unsigned NewSize =
8424         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8425     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8426                                : Type->hasSignedIntegerRepresentation();
8427     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8428     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8429       Diff = SemaRef.PerformImplicitConversion(
8430           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8431       if (!Diff.isUsable())
8432         return nullptr;
8433     }
8434   }
8435   if (LimitedType) {
8436     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8437     if (NewSize != C.getTypeSize(Type)) {
8438       if (NewSize < C.getTypeSize(Type)) {
8439         assert(NewSize == 64 && "incorrect loop var size");
8440         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8441             << InitSrcRange << ConditionSrcRange;
8442       }
8443       QualType NewType = C.getIntTypeForBitwidth(
8444           NewSize, Type->hasSignedIntegerRepresentation() ||
8445                        C.getTypeSize(Type) < NewSize);
8446       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8447         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8448                                                  Sema::AA_Converting, true);
8449         if (!Diff.isUsable())
8450           return nullptr;
8451       }
8452     }
8453   }
8454 
8455   return Diff.get();
8456 }
8457 
8458 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8459     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8460   // Do not build for iterators, they cannot be used in non-rectangular loop
8461   // nests.
8462   if (LCDecl->getType()->isRecordType())
8463     return std::make_pair(nullptr, nullptr);
8464   // If we subtract, the min is in the condition, otherwise the min is in the
8465   // init value.
8466   Expr *MinExpr = nullptr;
8467   Expr *MaxExpr = nullptr;
8468   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8469   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8470   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8471                                            : CondDependOnLC.hasValue();
8472   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8473                                            : InitDependOnLC.hasValue();
8474   Expr *Lower =
8475       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8476   Expr *Upper =
8477       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8478   if (!Upper || !Lower)
8479     return std::make_pair(nullptr, nullptr);
8480 
8481   if (TestIsLessOp.getValue())
8482     MinExpr = Lower;
8483   else
8484     MaxExpr = Upper;
8485 
8486   // Build minimum/maximum value based on number of iterations.
8487   QualType VarType = LCDecl->getType().getNonReferenceType();
8488 
8489   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8490                                       Step, VarType, TestIsStrictOp,
8491                                       /*RoundToStep=*/false, Captures);
8492   if (!Diff.isUsable())
8493     return std::make_pair(nullptr, nullptr);
8494 
8495   // ((Upper - Lower [- 1]) / Step) * Step
8496   // Parentheses (for dumping/debugging purposes only).
8497   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8498   if (!Diff.isUsable())
8499     return std::make_pair(nullptr, nullptr);
8500 
8501   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8502   if (!NewStep.isUsable())
8503     return std::make_pair(nullptr, nullptr);
8504   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8505   if (!Diff.isUsable())
8506     return std::make_pair(nullptr, nullptr);
8507 
8508   // Parentheses (for dumping/debugging purposes only).
8509   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8510   if (!Diff.isUsable())
8511     return std::make_pair(nullptr, nullptr);
8512 
8513   // Convert to the ptrdiff_t, if original type is pointer.
8514   if (VarType->isAnyPointerType() &&
8515       !SemaRef.Context.hasSameType(
8516           Diff.get()->getType(),
8517           SemaRef.Context.getUnsignedPointerDiffType())) {
8518     Diff = SemaRef.PerformImplicitConversion(
8519         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8520         Sema::AA_Converting, /*AllowExplicit=*/true);
8521   }
8522   if (!Diff.isUsable())
8523     return std::make_pair(nullptr, nullptr);
8524 
8525   if (TestIsLessOp.getValue()) {
8526     // MinExpr = Lower;
8527     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8528     Diff = SemaRef.BuildBinOp(
8529         S, DefaultLoc, BO_Add,
8530         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8531         Diff.get());
8532     if (!Diff.isUsable())
8533       return std::make_pair(nullptr, nullptr);
8534   } else {
8535     // MaxExpr = Upper;
8536     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8537     Diff = SemaRef.BuildBinOp(
8538         S, DefaultLoc, BO_Sub,
8539         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8540         Diff.get());
8541     if (!Diff.isUsable())
8542       return std::make_pair(nullptr, nullptr);
8543   }
8544 
8545   // Convert to the original type.
8546   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8547     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8548                                              Sema::AA_Converting,
8549                                              /*AllowExplicit=*/true);
8550   if (!Diff.isUsable())
8551     return std::make_pair(nullptr, nullptr);
8552 
8553   Sema::TentativeAnalysisScope Trap(SemaRef);
8554   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8555   if (!Diff.isUsable())
8556     return std::make_pair(nullptr, nullptr);
8557 
8558   if (TestIsLessOp.getValue())
8559     MaxExpr = Diff.get();
8560   else
8561     MinExpr = Diff.get();
8562 
8563   return std::make_pair(MinExpr, MaxExpr);
8564 }
8565 
8566 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8567   if (InitDependOnLC || CondDependOnLC)
8568     return Condition;
8569   return nullptr;
8570 }
8571 
8572 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8573     Scope *S, Expr *Cond,
8574     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8575   // Do not build a precondition when the condition/initialization is dependent
8576   // to prevent pessimistic early loop exit.
8577   // TODO: this can be improved by calculating min/max values but not sure that
8578   // it will be very effective.
8579   if (CondDependOnLC || InitDependOnLC)
8580     return SemaRef
8581         .PerformImplicitConversion(
8582             SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8583             SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8584             /*AllowExplicit=*/true)
8585         .get();
8586 
8587   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8588   Sema::TentativeAnalysisScope Trap(SemaRef);
8589 
8590   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8591   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8592   if (!NewLB.isUsable() || !NewUB.isUsable())
8593     return nullptr;
8594 
8595   ExprResult CondExpr = SemaRef.BuildBinOp(
8596       S, DefaultLoc,
8597       TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
8598                               : (TestIsStrictOp ? BO_GT : BO_GE),
8599       NewLB.get(), NewUB.get());
8600   if (CondExpr.isUsable()) {
8601     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8602                                                 SemaRef.Context.BoolTy))
8603       CondExpr = SemaRef.PerformImplicitConversion(
8604           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8605           /*AllowExplicit=*/true);
8606   }
8607 
8608   // Otherwise use original loop condition and evaluate it in runtime.
8609   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8610 }
8611 
8612 /// Build reference expression to the counter be used for codegen.
8613 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8614     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8615     DSAStackTy &DSA) const {
8616   auto *VD = dyn_cast<VarDecl>(LCDecl);
8617   if (!VD) {
8618     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8619     DeclRefExpr *Ref = buildDeclRefExpr(
8620         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8621     const DSAStackTy::DSAVarData Data =
8622         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8623     // If the loop control decl is explicitly marked as private, do not mark it
8624     // as captured again.
8625     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8626       Captures.insert(std::make_pair(LCRef, Ref));
8627     return Ref;
8628   }
8629   return cast<DeclRefExpr>(LCRef);
8630 }
8631 
8632 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8633   if (LCDecl && !LCDecl->isInvalidDecl()) {
8634     QualType Type = LCDecl->getType().getNonReferenceType();
8635     VarDecl *PrivateVar = buildVarDecl(
8636         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8637         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8638         isa<VarDecl>(LCDecl)
8639             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8640             : nullptr);
8641     if (PrivateVar->isInvalidDecl())
8642       return nullptr;
8643     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8644   }
8645   return nullptr;
8646 }
8647 
8648 /// Build initialization of the counter to be used for codegen.
8649 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8650 
8651 /// Build step of the counter be used for codegen.
8652 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8653 
8654 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8655     Scope *S, Expr *Counter,
8656     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8657     Expr *Inc, OverloadedOperatorKind OOK) {
8658   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8659   if (!Cnt)
8660     return nullptr;
8661   if (Inc) {
8662     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8663            "Expected only + or - operations for depend clauses.");
8664     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8665     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8666     if (!Cnt)
8667       return nullptr;
8668   }
8669   QualType VarType = LCDecl->getType().getNonReferenceType();
8670   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8671       !SemaRef.getLangOpts().CPlusPlus)
8672     return nullptr;
8673   // Upper - Lower
8674   Expr *Upper = TestIsLessOp.getValue()
8675                     ? Cnt
8676                     : tryBuildCapture(SemaRef, LB, Captures).get();
8677   Expr *Lower = TestIsLessOp.getValue()
8678                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8679                     : Cnt;
8680   if (!Upper || !Lower)
8681     return nullptr;
8682 
8683   ExprResult Diff = calculateNumIters(
8684       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8685       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8686   if (!Diff.isUsable())
8687     return nullptr;
8688 
8689   return Diff.get();
8690 }
8691 } // namespace
8692 
8693 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8694   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8695   assert(Init && "Expected loop in canonical form.");
8696   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8697   if (AssociatedLoops > 0 &&
8698       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8699     DSAStack->loopStart();
8700     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8701                                     *DSAStack, ForLoc);
8702     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8703       if (ValueDecl *D = ISC.getLoopDecl()) {
8704         auto *VD = dyn_cast<VarDecl>(D);
8705         DeclRefExpr *PrivateRef = nullptr;
8706         if (!VD) {
8707           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8708             VD = Private;
8709           } else {
8710             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8711                                       /*WithInit=*/false);
8712             VD = cast<VarDecl>(PrivateRef->getDecl());
8713           }
8714         }
8715         DSAStack->addLoopControlVariable(D, VD);
8716         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8717         if (LD != D->getCanonicalDecl()) {
8718           DSAStack->resetPossibleLoopCounter();
8719           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8720             MarkDeclarationsReferencedInExpr(
8721                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8722                                  Var->getType().getNonLValueExprType(Context),
8723                                  ForLoc, /*RefersToCapture=*/true));
8724         }
8725         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8726         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8727         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8728         // associated for-loop of a simd construct with just one associated
8729         // for-loop may be listed in a linear clause with a constant-linear-step
8730         // that is the increment of the associated for-loop. The loop iteration
8731         // variable(s) in the associated for-loop(s) of a for or parallel for
8732         // construct may be listed in a private or lastprivate clause.
8733         DSAStackTy::DSAVarData DVar =
8734             DSAStack->getTopDSA(D, /*FromParent=*/false);
8735         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8736         // is declared in the loop and it is predetermined as a private.
8737         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8738         OpenMPClauseKind PredeterminedCKind =
8739             isOpenMPSimdDirective(DKind)
8740                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8741                 : OMPC_private;
8742         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8743               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8744               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8745                                          DVar.CKind != OMPC_private))) ||
8746              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8747                DKind == OMPD_master_taskloop ||
8748                DKind == OMPD_parallel_master_taskloop ||
8749                isOpenMPDistributeDirective(DKind)) &&
8750               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8751               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8752             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8753           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8754               << getOpenMPClauseName(DVar.CKind)
8755               << getOpenMPDirectiveName(DKind)
8756               << getOpenMPClauseName(PredeterminedCKind);
8757           if (DVar.RefExpr == nullptr)
8758             DVar.CKind = PredeterminedCKind;
8759           reportOriginalDsa(*this, DSAStack, D, DVar,
8760                             /*IsLoopIterVar=*/true);
8761         } else if (LoopDeclRefExpr) {
8762           // Make the loop iteration variable private (for worksharing
8763           // constructs), linear (for simd directives with the only one
8764           // associated loop) or lastprivate (for simd directives with several
8765           // collapsed or ordered loops).
8766           if (DVar.CKind == OMPC_unknown)
8767             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8768                              PrivateRef);
8769         }
8770       }
8771     }
8772     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8773   }
8774 }
8775 
8776 /// Called on a for stmt to check and extract its iteration space
8777 /// for further processing (such as collapsing).
8778 static bool checkOpenMPIterationSpace(
8779     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8780     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8781     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8782     Expr *OrderedLoopCountExpr,
8783     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8784     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8785     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8786   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8787   // OpenMP [2.9.1, Canonical Loop Form]
8788   //   for (init-expr; test-expr; incr-expr) structured-block
8789   //   for (range-decl: range-expr) structured-block
8790   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8791     S = CanonLoop->getLoopStmt();
8792   auto *For = dyn_cast_or_null<ForStmt>(S);
8793   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8794   // Ranged for is supported only in OpenMP 5.0.
8795   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8796     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8797         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8798         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8799         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8800     if (TotalNestedLoopCount > 1) {
8801       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8802         SemaRef.Diag(DSA.getConstructLoc(),
8803                      diag::note_omp_collapse_ordered_expr)
8804             << 2 << CollapseLoopCountExpr->getSourceRange()
8805             << OrderedLoopCountExpr->getSourceRange();
8806       else if (CollapseLoopCountExpr)
8807         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8808                      diag::note_omp_collapse_ordered_expr)
8809             << 0 << CollapseLoopCountExpr->getSourceRange();
8810       else
8811         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8812                      diag::note_omp_collapse_ordered_expr)
8813             << 1 << OrderedLoopCountExpr->getSourceRange();
8814     }
8815     return true;
8816   }
8817   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8818          "No loop body.");
8819   // Postpone analysis in dependent contexts for ranged for loops.
8820   if (CXXFor && SemaRef.CurContext->isDependentContext())
8821     return false;
8822 
8823   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8824                                   For ? For->getForLoc() : CXXFor->getForLoc());
8825 
8826   // Check init.
8827   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8828   if (ISC.checkAndSetInit(Init))
8829     return true;
8830 
8831   bool HasErrors = false;
8832 
8833   // Check loop variable's type.
8834   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8835     // OpenMP [2.6, Canonical Loop Form]
8836     // Var is one of the following:
8837     //   A variable of signed or unsigned integer type.
8838     //   For C++, a variable of a random access iterator type.
8839     //   For C, a variable of a pointer type.
8840     QualType VarType = LCDecl->getType().getNonReferenceType();
8841     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8842         !VarType->isPointerType() &&
8843         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8844       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8845           << SemaRef.getLangOpts().CPlusPlus;
8846       HasErrors = true;
8847     }
8848 
8849     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8850     // a Construct
8851     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8852     // parallel for construct is (are) private.
8853     // The loop iteration variable in the associated for-loop of a simd
8854     // construct with just one associated for-loop is linear with a
8855     // constant-linear-step that is the increment of the associated for-loop.
8856     // Exclude loop var from the list of variables with implicitly defined data
8857     // sharing attributes.
8858     VarsWithImplicitDSA.erase(LCDecl);
8859 
8860     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8861 
8862     // Check test-expr.
8863     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8864 
8865     // Check incr-expr.
8866     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8867   }
8868 
8869   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8870     return HasErrors;
8871 
8872   // Build the loop's iteration space representation.
8873   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8874       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8875   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8876       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8877                              (isOpenMPWorksharingDirective(DKind) ||
8878                               isOpenMPGenericLoopDirective(DKind) ||
8879                               isOpenMPTaskLoopDirective(DKind) ||
8880                               isOpenMPDistributeDirective(DKind) ||
8881                               isOpenMPLoopTransformationDirective(DKind)),
8882                              Captures);
8883   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8884       ISC.buildCounterVar(Captures, DSA);
8885   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8886       ISC.buildPrivateCounterVar();
8887   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8888   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8889   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8890   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8891       ISC.getConditionSrcRange();
8892   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8893       ISC.getIncrementSrcRange();
8894   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8895   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8896       ISC.isStrictTestOp();
8897   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8898            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8899       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8900   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8901       ISC.buildFinalCondition(DSA.getCurScope());
8902   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8903       ISC.doesInitDependOnLC();
8904   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8905       ISC.doesCondDependOnLC();
8906   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8907       ISC.getLoopDependentIdx();
8908 
8909   HasErrors |=
8910       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8911        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8912        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8913        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8914        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8915        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8916   if (!HasErrors && DSA.isOrderedRegion()) {
8917     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8918       if (CurrentNestedLoopCount <
8919           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8920         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8921             CurrentNestedLoopCount,
8922             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8923         DSA.getOrderedRegionParam().second->setLoopCounter(
8924             CurrentNestedLoopCount,
8925             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8926       }
8927     }
8928     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8929       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8930         // Erroneous case - clause has some problems.
8931         continue;
8932       }
8933       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8934           Pair.second.size() <= CurrentNestedLoopCount) {
8935         // Erroneous case - clause has some problems.
8936         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8937         continue;
8938       }
8939       Expr *CntValue;
8940       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8941         CntValue = ISC.buildOrderedLoopData(
8942             DSA.getCurScope(),
8943             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8944             Pair.first->getDependencyLoc());
8945       else
8946         CntValue = ISC.buildOrderedLoopData(
8947             DSA.getCurScope(),
8948             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8949             Pair.first->getDependencyLoc(),
8950             Pair.second[CurrentNestedLoopCount].first,
8951             Pair.second[CurrentNestedLoopCount].second);
8952       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8953     }
8954   }
8955 
8956   return HasErrors;
8957 }
8958 
8959 /// Build 'VarRef = Start.
8960 static ExprResult
8961 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8962                  ExprResult Start, bool IsNonRectangularLB,
8963                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8964   // Build 'VarRef = Start.
8965   ExprResult NewStart = IsNonRectangularLB
8966                             ? Start.get()
8967                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8968   if (!NewStart.isUsable())
8969     return ExprError();
8970   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8971                                    VarRef.get()->getType())) {
8972     NewStart = SemaRef.PerformImplicitConversion(
8973         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8974         /*AllowExplicit=*/true);
8975     if (!NewStart.isUsable())
8976       return ExprError();
8977   }
8978 
8979   ExprResult Init =
8980       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8981   return Init;
8982 }
8983 
8984 /// Build 'VarRef = Start + Iter * Step'.
8985 static ExprResult buildCounterUpdate(
8986     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8987     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8988     bool IsNonRectangularLB,
8989     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8990   // Add parentheses (for debugging purposes only).
8991   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8992   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8993       !Step.isUsable())
8994     return ExprError();
8995 
8996   ExprResult NewStep = Step;
8997   if (Captures)
8998     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8999   if (NewStep.isInvalid())
9000     return ExprError();
9001   ExprResult Update =
9002       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
9003   if (!Update.isUsable())
9004     return ExprError();
9005 
9006   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
9007   // 'VarRef = Start (+|-) Iter * Step'.
9008   if (!Start.isUsable())
9009     return ExprError();
9010   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
9011   if (!NewStart.isUsable())
9012     return ExprError();
9013   if (Captures && !IsNonRectangularLB)
9014     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
9015   if (NewStart.isInvalid())
9016     return ExprError();
9017 
9018   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
9019   ExprResult SavedUpdate = Update;
9020   ExprResult UpdateVal;
9021   if (VarRef.get()->getType()->isOverloadableType() ||
9022       NewStart.get()->getType()->isOverloadableType() ||
9023       Update.get()->getType()->isOverloadableType()) {
9024     Sema::TentativeAnalysisScope Trap(SemaRef);
9025 
9026     Update =
9027         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9028     if (Update.isUsable()) {
9029       UpdateVal =
9030           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
9031                              VarRef.get(), SavedUpdate.get());
9032       if (UpdateVal.isUsable()) {
9033         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
9034                                             UpdateVal.get());
9035       }
9036     }
9037   }
9038 
9039   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
9040   if (!Update.isUsable() || !UpdateVal.isUsable()) {
9041     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
9042                                 NewStart.get(), SavedUpdate.get());
9043     if (!Update.isUsable())
9044       return ExprError();
9045 
9046     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
9047                                      VarRef.get()->getType())) {
9048       Update = SemaRef.PerformImplicitConversion(
9049           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
9050       if (!Update.isUsable())
9051         return ExprError();
9052     }
9053 
9054     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
9055   }
9056   return Update;
9057 }
9058 
9059 /// Convert integer expression \a E to make it have at least \a Bits
9060 /// bits.
9061 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
9062   if (E == nullptr)
9063     return ExprError();
9064   ASTContext &C = SemaRef.Context;
9065   QualType OldType = E->getType();
9066   unsigned HasBits = C.getTypeSize(OldType);
9067   if (HasBits >= Bits)
9068     return ExprResult(E);
9069   // OK to convert to signed, because new type has more bits than old.
9070   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
9071   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
9072                                            true);
9073 }
9074 
9075 /// Check if the given expression \a E is a constant integer that fits
9076 /// into \a Bits bits.
9077 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
9078   if (E == nullptr)
9079     return false;
9080   if (Optional<llvm::APSInt> Result =
9081           E->getIntegerConstantExpr(SemaRef.Context))
9082     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
9083   return false;
9084 }
9085 
9086 /// Build preinits statement for the given declarations.
9087 static Stmt *buildPreInits(ASTContext &Context,
9088                            MutableArrayRef<Decl *> PreInits) {
9089   if (!PreInits.empty()) {
9090     return new (Context) DeclStmt(
9091         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
9092         SourceLocation(), SourceLocation());
9093   }
9094   return nullptr;
9095 }
9096 
9097 /// Build preinits statement for the given declarations.
9098 static Stmt *
9099 buildPreInits(ASTContext &Context,
9100               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9101   if (!Captures.empty()) {
9102     SmallVector<Decl *, 16> PreInits;
9103     for (const auto &Pair : Captures)
9104       PreInits.push_back(Pair.second->getDecl());
9105     return buildPreInits(Context, PreInits);
9106   }
9107   return nullptr;
9108 }
9109 
9110 /// Build postupdate expression for the given list of postupdates expressions.
9111 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
9112   Expr *PostUpdate = nullptr;
9113   if (!PostUpdates.empty()) {
9114     for (Expr *E : PostUpdates) {
9115       Expr *ConvE = S.BuildCStyleCastExpr(
9116                          E->getExprLoc(),
9117                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
9118                          E->getExprLoc(), E)
9119                         .get();
9120       PostUpdate = PostUpdate
9121                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
9122                                               PostUpdate, ConvE)
9123                              .get()
9124                        : ConvE;
9125     }
9126   }
9127   return PostUpdate;
9128 }
9129 
9130 /// Called on a for stmt to check itself and nested loops (if any).
9131 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
9132 /// number of collapsed loops otherwise.
9133 static unsigned
9134 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
9135                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
9136                 DSAStackTy &DSA,
9137                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
9138                 OMPLoopBasedDirective::HelperExprs &Built) {
9139   unsigned NestedLoopCount = 1;
9140   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
9141                                     !isOpenMPLoopTransformationDirective(DKind);
9142 
9143   if (CollapseLoopCountExpr) {
9144     // Found 'collapse' clause - calculate collapse number.
9145     Expr::EvalResult Result;
9146     if (!CollapseLoopCountExpr->isValueDependent() &&
9147         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
9148       NestedLoopCount = Result.Val.getInt().getLimitedValue();
9149     } else {
9150       Built.clear(/*Size=*/1);
9151       return 1;
9152     }
9153   }
9154   unsigned OrderedLoopCount = 1;
9155   if (OrderedLoopCountExpr) {
9156     // Found 'ordered' clause - calculate collapse number.
9157     Expr::EvalResult EVResult;
9158     if (!OrderedLoopCountExpr->isValueDependent() &&
9159         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
9160                                             SemaRef.getASTContext())) {
9161       llvm::APSInt Result = EVResult.Val.getInt();
9162       if (Result.getLimitedValue() < NestedLoopCount) {
9163         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
9164                      diag::err_omp_wrong_ordered_loop_count)
9165             << OrderedLoopCountExpr->getSourceRange();
9166         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9167                      diag::note_collapse_loop_count)
9168             << CollapseLoopCountExpr->getSourceRange();
9169       }
9170       OrderedLoopCount = Result.getLimitedValue();
9171     } else {
9172       Built.clear(/*Size=*/1);
9173       return 1;
9174     }
9175   }
9176   // This is helper routine for loop directives (e.g., 'for', 'simd',
9177   // 'for simd', etc.).
9178   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9179   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
9180   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
9181   if (!OMPLoopBasedDirective::doForAllLoops(
9182           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
9183           SupportsNonPerfectlyNested, NumLoops,
9184           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
9185            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
9186            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
9187             if (checkOpenMPIterationSpace(
9188                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
9189                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
9190                     VarsWithImplicitDSA, IterSpaces, Captures))
9191               return true;
9192             if (Cnt > 0 && Cnt >= NestedLoopCount &&
9193                 IterSpaces[Cnt].CounterVar) {
9194               // Handle initialization of captured loop iterator variables.
9195               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
9196               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
9197                 Captures[DRE] = DRE;
9198               }
9199             }
9200             return false;
9201           },
9202           [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
9203             Stmt *DependentPreInits = Transform->getPreInits();
9204             if (!DependentPreInits)
9205               return;
9206             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9207               auto *D = cast<VarDecl>(C);
9208               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9209                                                   Transform->getBeginLoc());
9210               Captures[Ref] = Ref;
9211             }
9212           }))
9213     return 0;
9214 
9215   Built.clear(/* size */ NestedLoopCount);
9216 
9217   if (SemaRef.CurContext->isDependentContext())
9218     return NestedLoopCount;
9219 
9220   // An example of what is generated for the following code:
9221   //
9222   //   #pragma omp simd collapse(2) ordered(2)
9223   //   for (i = 0; i < NI; ++i)
9224   //     for (k = 0; k < NK; ++k)
9225   //       for (j = J0; j < NJ; j+=2) {
9226   //         <loop body>
9227   //       }
9228   //
9229   // We generate the code below.
9230   // Note: the loop body may be outlined in CodeGen.
9231   // Note: some counters may be C++ classes, operator- is used to find number of
9232   // iterations and operator+= to calculate counter value.
9233   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9234   // or i64 is currently supported).
9235   //
9236   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9237   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9238   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9239   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9240   //     // similar updates for vars in clauses (e.g. 'linear')
9241   //     <loop body (using local i and j)>
9242   //   }
9243   //   i = NI; // assign final values of counters
9244   //   j = NJ;
9245   //
9246 
9247   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9248   // the iteration counts of the collapsed for loops.
9249   // Precondition tests if there is at least one iteration (all conditions are
9250   // true).
9251   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9252   Expr *N0 = IterSpaces[0].NumIterations;
9253   ExprResult LastIteration32 =
9254       widenIterationCount(/*Bits=*/32,
9255                           SemaRef
9256                               .PerformImplicitConversion(
9257                                   N0->IgnoreImpCasts(), N0->getType(),
9258                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9259                               .get(),
9260                           SemaRef);
9261   ExprResult LastIteration64 = widenIterationCount(
9262       /*Bits=*/64,
9263       SemaRef
9264           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9265                                      Sema::AA_Converting,
9266                                      /*AllowExplicit=*/true)
9267           .get(),
9268       SemaRef);
9269 
9270   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9271     return NestedLoopCount;
9272 
9273   ASTContext &C = SemaRef.Context;
9274   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9275 
9276   Scope *CurScope = DSA.getCurScope();
9277   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9278     if (PreCond.isUsable()) {
9279       PreCond =
9280           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9281                              PreCond.get(), IterSpaces[Cnt].PreCond);
9282     }
9283     Expr *N = IterSpaces[Cnt].NumIterations;
9284     SourceLocation Loc = N->getExprLoc();
9285     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9286     if (LastIteration32.isUsable())
9287       LastIteration32 = SemaRef.BuildBinOp(
9288           CurScope, Loc, BO_Mul, LastIteration32.get(),
9289           SemaRef
9290               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9291                                          Sema::AA_Converting,
9292                                          /*AllowExplicit=*/true)
9293               .get());
9294     if (LastIteration64.isUsable())
9295       LastIteration64 = SemaRef.BuildBinOp(
9296           CurScope, Loc, BO_Mul, LastIteration64.get(),
9297           SemaRef
9298               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9299                                          Sema::AA_Converting,
9300                                          /*AllowExplicit=*/true)
9301               .get());
9302   }
9303 
9304   // Choose either the 32-bit or 64-bit version.
9305   ExprResult LastIteration = LastIteration64;
9306   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9307       (LastIteration32.isUsable() &&
9308        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9309        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9310         fitsInto(
9311             /*Bits=*/32,
9312             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9313             LastIteration64.get(), SemaRef))))
9314     LastIteration = LastIteration32;
9315   QualType VType = LastIteration.get()->getType();
9316   QualType RealVType = VType;
9317   QualType StrideVType = VType;
9318   if (isOpenMPTaskLoopDirective(DKind)) {
9319     VType =
9320         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9321     StrideVType =
9322         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9323   }
9324 
9325   if (!LastIteration.isUsable())
9326     return 0;
9327 
9328   // Save the number of iterations.
9329   ExprResult NumIterations = LastIteration;
9330   {
9331     LastIteration = SemaRef.BuildBinOp(
9332         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9333         LastIteration.get(),
9334         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9335     if (!LastIteration.isUsable())
9336       return 0;
9337   }
9338 
9339   // Calculate the last iteration number beforehand instead of doing this on
9340   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9341   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9342   ExprResult CalcLastIteration;
9343   if (!IsConstant) {
9344     ExprResult SaveRef =
9345         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9346     LastIteration = SaveRef;
9347 
9348     // Prepare SaveRef + 1.
9349     NumIterations = SemaRef.BuildBinOp(
9350         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9351         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9352     if (!NumIterations.isUsable())
9353       return 0;
9354   }
9355 
9356   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9357 
9358   // Build variables passed into runtime, necessary for worksharing directives.
9359   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9360   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9361       isOpenMPDistributeDirective(DKind) ||
9362       isOpenMPGenericLoopDirective(DKind) ||
9363       isOpenMPLoopTransformationDirective(DKind)) {
9364     // Lower bound variable, initialized with zero.
9365     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9366     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9367     SemaRef.AddInitializerToDecl(LBDecl,
9368                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9369                                  /*DirectInit*/ false);
9370 
9371     // Upper bound variable, initialized with last iteration number.
9372     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9373     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9374     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9375                                  /*DirectInit*/ false);
9376 
9377     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9378     // This will be used to implement clause 'lastprivate'.
9379     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9380     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9381     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9382     SemaRef.AddInitializerToDecl(ILDecl,
9383                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9384                                  /*DirectInit*/ false);
9385 
9386     // Stride variable returned by runtime (we initialize it to 1 by default).
9387     VarDecl *STDecl =
9388         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9389     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9390     SemaRef.AddInitializerToDecl(STDecl,
9391                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9392                                  /*DirectInit*/ false);
9393 
9394     // Build expression: UB = min(UB, LastIteration)
9395     // It is necessary for CodeGen of directives with static scheduling.
9396     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9397                                                 UB.get(), LastIteration.get());
9398     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9399         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9400         LastIteration.get(), UB.get());
9401     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9402                              CondOp.get());
9403     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9404 
9405     // If we have a combined directive that combines 'distribute', 'for' or
9406     // 'simd' we need to be able to access the bounds of the schedule of the
9407     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9408     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9409     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9410       // Lower bound variable, initialized with zero.
9411       VarDecl *CombLBDecl =
9412           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9413       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9414       SemaRef.AddInitializerToDecl(
9415           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9416           /*DirectInit*/ false);
9417 
9418       // Upper bound variable, initialized with last iteration number.
9419       VarDecl *CombUBDecl =
9420           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9421       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9422       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9423                                    /*DirectInit*/ false);
9424 
9425       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9426           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9427       ExprResult CombCondOp =
9428           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9429                                      LastIteration.get(), CombUB.get());
9430       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9431                                    CombCondOp.get());
9432       CombEUB =
9433           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9434 
9435       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9436       // We expect to have at least 2 more parameters than the 'parallel'
9437       // directive does - the lower and upper bounds of the previous schedule.
9438       assert(CD->getNumParams() >= 4 &&
9439              "Unexpected number of parameters in loop combined directive");
9440 
9441       // Set the proper type for the bounds given what we learned from the
9442       // enclosed loops.
9443       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9444       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9445 
9446       // Previous lower and upper bounds are obtained from the region
9447       // parameters.
9448       PrevLB =
9449           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9450       PrevUB =
9451           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9452     }
9453   }
9454 
9455   // Build the iteration variable and its initialization before loop.
9456   ExprResult IV;
9457   ExprResult Init, CombInit;
9458   {
9459     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9460     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9461     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9462                  isOpenMPGenericLoopDirective(DKind) ||
9463                  isOpenMPTaskLoopDirective(DKind) ||
9464                  isOpenMPDistributeDirective(DKind) ||
9465                  isOpenMPLoopTransformationDirective(DKind))
9466                     ? LB.get()
9467                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9468     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9469     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9470 
9471     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9472       Expr *CombRHS =
9473           (isOpenMPWorksharingDirective(DKind) ||
9474            isOpenMPGenericLoopDirective(DKind) ||
9475            isOpenMPTaskLoopDirective(DKind) ||
9476            isOpenMPDistributeDirective(DKind))
9477               ? CombLB.get()
9478               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9479       CombInit =
9480           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9481       CombInit =
9482           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9483     }
9484   }
9485 
9486   bool UseStrictCompare =
9487       RealVType->hasUnsignedIntegerRepresentation() &&
9488       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9489         return LIS.IsStrictCompare;
9490       });
9491   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9492   // unsigned IV)) for worksharing loops.
9493   SourceLocation CondLoc = AStmt->getBeginLoc();
9494   Expr *BoundUB = UB.get();
9495   if (UseStrictCompare) {
9496     BoundUB =
9497         SemaRef
9498             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9499                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9500             .get();
9501     BoundUB =
9502         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9503   }
9504   ExprResult Cond =
9505       (isOpenMPWorksharingDirective(DKind) ||
9506        isOpenMPGenericLoopDirective(DKind) ||
9507        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9508        isOpenMPLoopTransformationDirective(DKind))
9509           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9510                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9511                                BoundUB)
9512           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9513                                NumIterations.get());
9514   ExprResult CombDistCond;
9515   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9516     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9517                                       NumIterations.get());
9518   }
9519 
9520   ExprResult CombCond;
9521   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9522     Expr *BoundCombUB = CombUB.get();
9523     if (UseStrictCompare) {
9524       BoundCombUB =
9525           SemaRef
9526               .BuildBinOp(
9527                   CurScope, CondLoc, BO_Add, BoundCombUB,
9528                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9529               .get();
9530       BoundCombUB =
9531           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9532               .get();
9533     }
9534     CombCond =
9535         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9536                            IV.get(), BoundCombUB);
9537   }
9538   // Loop increment (IV = IV + 1)
9539   SourceLocation IncLoc = AStmt->getBeginLoc();
9540   ExprResult Inc =
9541       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9542                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9543   if (!Inc.isUsable())
9544     return 0;
9545   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9546   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9547   if (!Inc.isUsable())
9548     return 0;
9549 
9550   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9551   // Used for directives with static scheduling.
9552   // In combined construct, add combined version that use CombLB and CombUB
9553   // base variables for the update
9554   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9555   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9556       isOpenMPGenericLoopDirective(DKind) ||
9557       isOpenMPDistributeDirective(DKind) ||
9558       isOpenMPLoopTransformationDirective(DKind)) {
9559     // LB + ST
9560     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9561     if (!NextLB.isUsable())
9562       return 0;
9563     // LB = LB + ST
9564     NextLB =
9565         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9566     NextLB =
9567         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9568     if (!NextLB.isUsable())
9569       return 0;
9570     // UB + ST
9571     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9572     if (!NextUB.isUsable())
9573       return 0;
9574     // UB = UB + ST
9575     NextUB =
9576         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9577     NextUB =
9578         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9579     if (!NextUB.isUsable())
9580       return 0;
9581     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9582       CombNextLB =
9583           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9584       if (!NextLB.isUsable())
9585         return 0;
9586       // LB = LB + ST
9587       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9588                                       CombNextLB.get());
9589       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9590                                                /*DiscardedValue*/ false);
9591       if (!CombNextLB.isUsable())
9592         return 0;
9593       // UB + ST
9594       CombNextUB =
9595           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9596       if (!CombNextUB.isUsable())
9597         return 0;
9598       // UB = UB + ST
9599       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9600                                       CombNextUB.get());
9601       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9602                                                /*DiscardedValue*/ false);
9603       if (!CombNextUB.isUsable())
9604         return 0;
9605     }
9606   }
9607 
9608   // Create increment expression for distribute loop when combined in a same
9609   // directive with for as IV = IV + ST; ensure upper bound expression based
9610   // on PrevUB instead of NumIterations - used to implement 'for' when found
9611   // in combination with 'distribute', like in 'distribute parallel for'
9612   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9613   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9614   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9615     DistCond = SemaRef.BuildBinOp(
9616         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9617     assert(DistCond.isUsable() && "distribute cond expr was not built");
9618 
9619     DistInc =
9620         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9621     assert(DistInc.isUsable() && "distribute inc expr was not built");
9622     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9623                                  DistInc.get());
9624     DistInc =
9625         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9626     assert(DistInc.isUsable() && "distribute inc expr was not built");
9627 
9628     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9629     // construct
9630     ExprResult NewPrevUB = PrevUB;
9631     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9632     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9633                                      PrevUB.get()->getType())) {
9634       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9635           DistEUBLoc,
9636           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9637           DistEUBLoc, NewPrevUB.get());
9638       if (!NewPrevUB.isUsable())
9639         return 0;
9640     }
9641     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9642                                                 UB.get(), NewPrevUB.get());
9643     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9644         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9645     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9646                                  CondOp.get());
9647     PrevEUB =
9648         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9649 
9650     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9651     // parallel for is in combination with a distribute directive with
9652     // schedule(static, 1)
9653     Expr *BoundPrevUB = PrevUB.get();
9654     if (UseStrictCompare) {
9655       BoundPrevUB =
9656           SemaRef
9657               .BuildBinOp(
9658                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9659                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9660               .get();
9661       BoundPrevUB =
9662           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9663               .get();
9664     }
9665     ParForInDistCond =
9666         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9667                            IV.get(), BoundPrevUB);
9668   }
9669 
9670   // Build updates and final values of the loop counters.
9671   bool HasErrors = false;
9672   Built.Counters.resize(NestedLoopCount);
9673   Built.Inits.resize(NestedLoopCount);
9674   Built.Updates.resize(NestedLoopCount);
9675   Built.Finals.resize(NestedLoopCount);
9676   Built.DependentCounters.resize(NestedLoopCount);
9677   Built.DependentInits.resize(NestedLoopCount);
9678   Built.FinalsConditions.resize(NestedLoopCount);
9679   {
9680     // We implement the following algorithm for obtaining the
9681     // original loop iteration variable values based on the
9682     // value of the collapsed loop iteration variable IV.
9683     //
9684     // Let n+1 be the number of collapsed loops in the nest.
9685     // Iteration variables (I0, I1, .... In)
9686     // Iteration counts (N0, N1, ... Nn)
9687     //
9688     // Acc = IV;
9689     //
9690     // To compute Ik for loop k, 0 <= k <= n, generate:
9691     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9692     //    Ik = Acc / Prod;
9693     //    Acc -= Ik * Prod;
9694     //
9695     ExprResult Acc = IV;
9696     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9697       LoopIterationSpace &IS = IterSpaces[Cnt];
9698       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9699       ExprResult Iter;
9700 
9701       // Compute prod
9702       ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9703       for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
9704         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9705                                   IterSpaces[K].NumIterations);
9706 
9707       // Iter = Acc / Prod
9708       // If there is at least one more inner loop to avoid
9709       // multiplication by 1.
9710       if (Cnt + 1 < NestedLoopCount)
9711         Iter =
9712             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
9713       else
9714         Iter = Acc;
9715       if (!Iter.isUsable()) {
9716         HasErrors = true;
9717         break;
9718       }
9719 
9720       // Update Acc:
9721       // Acc -= Iter * Prod
9722       // Check if there is at least one more inner loop to avoid
9723       // multiplication by 1.
9724       if (Cnt + 1 < NestedLoopCount)
9725         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
9726                                   Prod.get());
9727       else
9728         Prod = Iter;
9729       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
9730 
9731       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9732       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9733       DeclRefExpr *CounterVar = buildDeclRefExpr(
9734           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9735           /*RefersToCapture=*/true);
9736       ExprResult Init =
9737           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9738                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9739       if (!Init.isUsable()) {
9740         HasErrors = true;
9741         break;
9742       }
9743       ExprResult Update = buildCounterUpdate(
9744           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9745           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9746       if (!Update.isUsable()) {
9747         HasErrors = true;
9748         break;
9749       }
9750 
9751       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9752       ExprResult Final =
9753           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9754                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9755                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9756       if (!Final.isUsable()) {
9757         HasErrors = true;
9758         break;
9759       }
9760 
9761       if (!Update.isUsable() || !Final.isUsable()) {
9762         HasErrors = true;
9763         break;
9764       }
9765       // Save results
9766       Built.Counters[Cnt] = IS.CounterVar;
9767       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9768       Built.Inits[Cnt] = Init.get();
9769       Built.Updates[Cnt] = Update.get();
9770       Built.Finals[Cnt] = Final.get();
9771       Built.DependentCounters[Cnt] = nullptr;
9772       Built.DependentInits[Cnt] = nullptr;
9773       Built.FinalsConditions[Cnt] = nullptr;
9774       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9775         Built.DependentCounters[Cnt] =
9776             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9777         Built.DependentInits[Cnt] =
9778             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9779         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9780       }
9781     }
9782   }
9783 
9784   if (HasErrors)
9785     return 0;
9786 
9787   // Save results
9788   Built.IterationVarRef = IV.get();
9789   Built.LastIteration = LastIteration.get();
9790   Built.NumIterations = NumIterations.get();
9791   Built.CalcLastIteration = SemaRef
9792                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9793                                                      /*DiscardedValue=*/false)
9794                                 .get();
9795   Built.PreCond = PreCond.get();
9796   Built.PreInits = buildPreInits(C, Captures);
9797   Built.Cond = Cond.get();
9798   Built.Init = Init.get();
9799   Built.Inc = Inc.get();
9800   Built.LB = LB.get();
9801   Built.UB = UB.get();
9802   Built.IL = IL.get();
9803   Built.ST = ST.get();
9804   Built.EUB = EUB.get();
9805   Built.NLB = NextLB.get();
9806   Built.NUB = NextUB.get();
9807   Built.PrevLB = PrevLB.get();
9808   Built.PrevUB = PrevUB.get();
9809   Built.DistInc = DistInc.get();
9810   Built.PrevEUB = PrevEUB.get();
9811   Built.DistCombinedFields.LB = CombLB.get();
9812   Built.DistCombinedFields.UB = CombUB.get();
9813   Built.DistCombinedFields.EUB = CombEUB.get();
9814   Built.DistCombinedFields.Init = CombInit.get();
9815   Built.DistCombinedFields.Cond = CombCond.get();
9816   Built.DistCombinedFields.NLB = CombNextLB.get();
9817   Built.DistCombinedFields.NUB = CombNextUB.get();
9818   Built.DistCombinedFields.DistCond = CombDistCond.get();
9819   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9820 
9821   return NestedLoopCount;
9822 }
9823 
9824 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9825   auto CollapseClauses =
9826       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9827   if (CollapseClauses.begin() != CollapseClauses.end())
9828     return (*CollapseClauses.begin())->getNumForLoops();
9829   return nullptr;
9830 }
9831 
9832 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9833   auto OrderedClauses =
9834       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9835   if (OrderedClauses.begin() != OrderedClauses.end())
9836     return (*OrderedClauses.begin())->getNumForLoops();
9837   return nullptr;
9838 }
9839 
9840 static bool checkSimdlenSafelenSpecified(Sema &S,
9841                                          const ArrayRef<OMPClause *> Clauses) {
9842   const OMPSafelenClause *Safelen = nullptr;
9843   const OMPSimdlenClause *Simdlen = nullptr;
9844 
9845   for (const OMPClause *Clause : Clauses) {
9846     if (Clause->getClauseKind() == OMPC_safelen)
9847       Safelen = cast<OMPSafelenClause>(Clause);
9848     else if (Clause->getClauseKind() == OMPC_simdlen)
9849       Simdlen = cast<OMPSimdlenClause>(Clause);
9850     if (Safelen && Simdlen)
9851       break;
9852   }
9853 
9854   if (Simdlen && Safelen) {
9855     const Expr *SimdlenLength = Simdlen->getSimdlen();
9856     const Expr *SafelenLength = Safelen->getSafelen();
9857     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9858         SimdlenLength->isInstantiationDependent() ||
9859         SimdlenLength->containsUnexpandedParameterPack())
9860       return false;
9861     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9862         SafelenLength->isInstantiationDependent() ||
9863         SafelenLength->containsUnexpandedParameterPack())
9864       return false;
9865     Expr::EvalResult SimdlenResult, SafelenResult;
9866     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9867     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9868     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9869     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9870     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9871     // If both simdlen and safelen clauses are specified, the value of the
9872     // simdlen parameter must be less than or equal to the value of the safelen
9873     // parameter.
9874     if (SimdlenRes > SafelenRes) {
9875       S.Diag(SimdlenLength->getExprLoc(),
9876              diag::err_omp_wrong_simdlen_safelen_values)
9877           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9878       return true;
9879     }
9880   }
9881   return false;
9882 }
9883 
9884 StmtResult
9885 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9886                                SourceLocation StartLoc, SourceLocation EndLoc,
9887                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9888   if (!AStmt)
9889     return StmtError();
9890 
9891   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9892   OMPLoopBasedDirective::HelperExprs B;
9893   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9894   // define the nested loops number.
9895   unsigned NestedLoopCount = checkOpenMPLoop(
9896       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9897       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9898   if (NestedLoopCount == 0)
9899     return StmtError();
9900 
9901   assert((CurContext->isDependentContext() || B.builtAll()) &&
9902          "omp simd loop exprs were not built");
9903 
9904   if (!CurContext->isDependentContext()) {
9905     // Finalize the clauses that need pre-built expressions for CodeGen.
9906     for (OMPClause *C : Clauses) {
9907       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9908         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9909                                      B.NumIterations, *this, CurScope,
9910                                      DSAStack))
9911           return StmtError();
9912     }
9913   }
9914 
9915   if (checkSimdlenSafelenSpecified(*this, Clauses))
9916     return StmtError();
9917 
9918   setFunctionHasBranchProtectedScope();
9919   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9920                                   Clauses, AStmt, B);
9921 }
9922 
9923 StmtResult
9924 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9925                               SourceLocation StartLoc, SourceLocation EndLoc,
9926                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9927   if (!AStmt)
9928     return StmtError();
9929 
9930   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9931   OMPLoopBasedDirective::HelperExprs B;
9932   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9933   // define the nested loops number.
9934   unsigned NestedLoopCount = checkOpenMPLoop(
9935       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9936       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9937   if (NestedLoopCount == 0)
9938     return StmtError();
9939 
9940   assert((CurContext->isDependentContext() || B.builtAll()) &&
9941          "omp for loop exprs were not built");
9942 
9943   if (!CurContext->isDependentContext()) {
9944     // Finalize the clauses that need pre-built expressions for CodeGen.
9945     for (OMPClause *C : Clauses) {
9946       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9947         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9948                                      B.NumIterations, *this, CurScope,
9949                                      DSAStack))
9950           return StmtError();
9951     }
9952   }
9953 
9954   setFunctionHasBranchProtectedScope();
9955   return OMPForDirective::Create(
9956       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9957       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9958 }
9959 
9960 StmtResult Sema::ActOnOpenMPForSimdDirective(
9961     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9962     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9963   if (!AStmt)
9964     return StmtError();
9965 
9966   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9967   OMPLoopBasedDirective::HelperExprs B;
9968   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9969   // define the nested loops number.
9970   unsigned NestedLoopCount =
9971       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9972                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9973                       VarsWithImplicitDSA, B);
9974   if (NestedLoopCount == 0)
9975     return StmtError();
9976 
9977   assert((CurContext->isDependentContext() || B.builtAll()) &&
9978          "omp for simd loop exprs were not built");
9979 
9980   if (!CurContext->isDependentContext()) {
9981     // Finalize the clauses that need pre-built expressions for CodeGen.
9982     for (OMPClause *C : Clauses) {
9983       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9984         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9985                                      B.NumIterations, *this, CurScope,
9986                                      DSAStack))
9987           return StmtError();
9988     }
9989   }
9990 
9991   if (checkSimdlenSafelenSpecified(*this, Clauses))
9992     return StmtError();
9993 
9994   setFunctionHasBranchProtectedScope();
9995   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9996                                      Clauses, AStmt, B);
9997 }
9998 
9999 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10000                                               Stmt *AStmt,
10001                                               SourceLocation StartLoc,
10002                                               SourceLocation EndLoc) {
10003   if (!AStmt)
10004     return StmtError();
10005 
10006   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10007   auto BaseStmt = AStmt;
10008   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10009     BaseStmt = CS->getCapturedStmt();
10010   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10011     auto S = C->children();
10012     if (S.begin() == S.end())
10013       return StmtError();
10014     // All associated statements must be '#pragma omp section' except for
10015     // the first one.
10016     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10017       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10018         if (SectionStmt)
10019           Diag(SectionStmt->getBeginLoc(),
10020                diag::err_omp_sections_substmt_not_section);
10021         return StmtError();
10022       }
10023       cast<OMPSectionDirective>(SectionStmt)
10024           ->setHasCancel(DSAStack->isCancelRegion());
10025     }
10026   } else {
10027     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
10028     return StmtError();
10029   }
10030 
10031   setFunctionHasBranchProtectedScope();
10032 
10033   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10034                                       DSAStack->getTaskgroupReductionRef(),
10035                                       DSAStack->isCancelRegion());
10036 }
10037 
10038 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
10039                                              SourceLocation StartLoc,
10040                                              SourceLocation EndLoc) {
10041   if (!AStmt)
10042     return StmtError();
10043 
10044   setFunctionHasBranchProtectedScope();
10045   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
10046 
10047   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
10048                                      DSAStack->isCancelRegion());
10049 }
10050 
10051 static Expr *getDirectCallExpr(Expr *E) {
10052   E = E->IgnoreParenCasts()->IgnoreImplicit();
10053   if (auto *CE = dyn_cast<CallExpr>(E))
10054     if (CE->getDirectCallee())
10055       return E;
10056   return nullptr;
10057 }
10058 
10059 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10060                                               Stmt *AStmt,
10061                                               SourceLocation StartLoc,
10062                                               SourceLocation EndLoc) {
10063   if (!AStmt)
10064     return StmtError();
10065 
10066   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
10067 
10068   // 5.1 OpenMP
10069   // expression-stmt : an expression statement with one of the following forms:
10070   //   expression = target-call ( [expression-list] );
10071   //   target-call ( [expression-list] );
10072 
10073   SourceLocation TargetCallLoc;
10074 
10075   if (!CurContext->isDependentContext()) {
10076     Expr *TargetCall = nullptr;
10077 
10078     auto *E = dyn_cast<Expr>(S);
10079     if (!E) {
10080       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10081       return StmtError();
10082     }
10083 
10084     E = E->IgnoreParenCasts()->IgnoreImplicit();
10085 
10086     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
10087       if (BO->getOpcode() == BO_Assign)
10088         TargetCall = getDirectCallExpr(BO->getRHS());
10089     } else {
10090       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
10091         if (COCE->getOperator() == OO_Equal)
10092           TargetCall = getDirectCallExpr(COCE->getArg(1));
10093       if (!TargetCall)
10094         TargetCall = getDirectCallExpr(E);
10095     }
10096     if (!TargetCall) {
10097       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10098       return StmtError();
10099     }
10100     TargetCallLoc = TargetCall->getExprLoc();
10101   }
10102 
10103   setFunctionHasBranchProtectedScope();
10104 
10105   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10106                                       TargetCallLoc);
10107 }
10108 
10109 StmtResult Sema::ActOnOpenMPGenericLoopDirective(
10110     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10111     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10112   if (!AStmt)
10113     return StmtError();
10114 
10115   // OpenMP 5.1 [2.11.7, loop construct]
10116   // A list item may not appear in a lastprivate clause unless it is the
10117   // loop iteration variable of a loop that is associated with the construct.
10118   for (OMPClause *C : Clauses) {
10119     if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
10120       for (Expr *RefExpr : LPC->varlists()) {
10121         SourceLocation ELoc;
10122         SourceRange ERange;
10123         Expr *SimpleRefExpr = RefExpr;
10124         auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10125         if (ValueDecl *D = Res.first) {
10126           auto &&Info = DSAStack->isLoopControlVariable(D);
10127           if (!Info.first) {
10128             Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration);
10129             return StmtError();
10130           }
10131         }
10132       }
10133     }
10134   }
10135 
10136   auto *CS = cast<CapturedStmt>(AStmt);
10137   // 1.2.2 OpenMP Language Terminology
10138   // Structured block - An executable statement with a single entry at the
10139   // top and a single exit at the bottom.
10140   // The point of exit cannot be a branch out of the structured block.
10141   // longjmp() and throw() must not violate the entry/exit criteria.
10142   CS->getCapturedDecl()->setNothrow();
10143 
10144   OMPLoopDirective::HelperExprs B;
10145   // In presence of clause 'collapse', it will define the nested loops number.
10146   unsigned NestedLoopCount = checkOpenMPLoop(
10147       OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10148       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10149   if (NestedLoopCount == 0)
10150     return StmtError();
10151 
10152   assert((CurContext->isDependentContext() || B.builtAll()) &&
10153          "omp loop exprs were not built");
10154 
10155   setFunctionHasBranchProtectedScope();
10156   return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
10157                                          NestedLoopCount, Clauses, AStmt, B);
10158 }
10159 
10160 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10161                                             Stmt *AStmt,
10162                                             SourceLocation StartLoc,
10163                                             SourceLocation EndLoc) {
10164   if (!AStmt)
10165     return StmtError();
10166 
10167   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10168 
10169   setFunctionHasBranchProtectedScope();
10170 
10171   // OpenMP [2.7.3, single Construct, Restrictions]
10172   // The copyprivate clause must not be used with the nowait clause.
10173   const OMPClause *Nowait = nullptr;
10174   const OMPClause *Copyprivate = nullptr;
10175   for (const OMPClause *Clause : Clauses) {
10176     if (Clause->getClauseKind() == OMPC_nowait)
10177       Nowait = Clause;
10178     else if (Clause->getClauseKind() == OMPC_copyprivate)
10179       Copyprivate = Clause;
10180     if (Copyprivate && Nowait) {
10181       Diag(Copyprivate->getBeginLoc(),
10182            diag::err_omp_single_copyprivate_with_nowait);
10183       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
10184       return StmtError();
10185     }
10186   }
10187 
10188   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10189 }
10190 
10191 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
10192                                             SourceLocation StartLoc,
10193                                             SourceLocation EndLoc) {
10194   if (!AStmt)
10195     return StmtError();
10196 
10197   setFunctionHasBranchProtectedScope();
10198 
10199   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
10200 }
10201 
10202 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10203                                             Stmt *AStmt,
10204                                             SourceLocation StartLoc,
10205                                             SourceLocation EndLoc) {
10206   if (!AStmt)
10207     return StmtError();
10208 
10209   setFunctionHasBranchProtectedScope();
10210 
10211   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10212 }
10213 
10214 StmtResult Sema::ActOnOpenMPCriticalDirective(
10215     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
10216     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
10217   if (!AStmt)
10218     return StmtError();
10219 
10220   bool ErrorFound = false;
10221   llvm::APSInt Hint;
10222   SourceLocation HintLoc;
10223   bool DependentHint = false;
10224   for (const OMPClause *C : Clauses) {
10225     if (C->getClauseKind() == OMPC_hint) {
10226       if (!DirName.getName()) {
10227         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
10228         ErrorFound = true;
10229       }
10230       Expr *E = cast<OMPHintClause>(C)->getHint();
10231       if (E->isTypeDependent() || E->isValueDependent() ||
10232           E->isInstantiationDependent()) {
10233         DependentHint = true;
10234       } else {
10235         Hint = E->EvaluateKnownConstInt(Context);
10236         HintLoc = C->getBeginLoc();
10237       }
10238     }
10239   }
10240   if (ErrorFound)
10241     return StmtError();
10242   const auto Pair = DSAStack->getCriticalWithHint(DirName);
10243   if (Pair.first && DirName.getName() && !DependentHint) {
10244     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
10245       Diag(StartLoc, diag::err_omp_critical_with_hint);
10246       if (HintLoc.isValid())
10247         Diag(HintLoc, diag::note_omp_critical_hint_here)
10248             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
10249       else
10250         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10251       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10252         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10253             << 1
10254             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10255                         /*Radix=*/10, /*Signed=*/false);
10256       } else {
10257         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10258       }
10259     }
10260   }
10261 
10262   setFunctionHasBranchProtectedScope();
10263 
10264   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10265                                            Clauses, AStmt);
10266   if (!Pair.first && DirName.getName() && !DependentHint)
10267     DSAStack->addCriticalWithHint(Dir, Hint);
10268   return Dir;
10269 }
10270 
10271 StmtResult Sema::ActOnOpenMPParallelForDirective(
10272     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10273     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10274   if (!AStmt)
10275     return StmtError();
10276 
10277   auto *CS = cast<CapturedStmt>(AStmt);
10278   // 1.2.2 OpenMP Language Terminology
10279   // Structured block - An executable statement with a single entry at the
10280   // top and a single exit at the bottom.
10281   // The point of exit cannot be a branch out of the structured block.
10282   // longjmp() and throw() must not violate the entry/exit criteria.
10283   CS->getCapturedDecl()->setNothrow();
10284 
10285   OMPLoopBasedDirective::HelperExprs B;
10286   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10287   // define the nested loops number.
10288   unsigned NestedLoopCount =
10289       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10290                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10291                       VarsWithImplicitDSA, B);
10292   if (NestedLoopCount == 0)
10293     return StmtError();
10294 
10295   assert((CurContext->isDependentContext() || B.builtAll()) &&
10296          "omp parallel for loop exprs were not built");
10297 
10298   if (!CurContext->isDependentContext()) {
10299     // Finalize the clauses that need pre-built expressions for CodeGen.
10300     for (OMPClause *C : Clauses) {
10301       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10302         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10303                                      B.NumIterations, *this, CurScope,
10304                                      DSAStack))
10305           return StmtError();
10306     }
10307   }
10308 
10309   setFunctionHasBranchProtectedScope();
10310   return OMPParallelForDirective::Create(
10311       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10312       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10313 }
10314 
10315 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10316     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10317     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10318   if (!AStmt)
10319     return StmtError();
10320 
10321   auto *CS = cast<CapturedStmt>(AStmt);
10322   // 1.2.2 OpenMP Language Terminology
10323   // Structured block - An executable statement with a single entry at the
10324   // top and a single exit at the bottom.
10325   // The point of exit cannot be a branch out of the structured block.
10326   // longjmp() and throw() must not violate the entry/exit criteria.
10327   CS->getCapturedDecl()->setNothrow();
10328 
10329   OMPLoopBasedDirective::HelperExprs B;
10330   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10331   // define the nested loops number.
10332   unsigned NestedLoopCount =
10333       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10334                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10335                       VarsWithImplicitDSA, B);
10336   if (NestedLoopCount == 0)
10337     return StmtError();
10338 
10339   if (!CurContext->isDependentContext()) {
10340     // Finalize the clauses that need pre-built expressions for CodeGen.
10341     for (OMPClause *C : Clauses) {
10342       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10343         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10344                                      B.NumIterations, *this, CurScope,
10345                                      DSAStack))
10346           return StmtError();
10347     }
10348   }
10349 
10350   if (checkSimdlenSafelenSpecified(*this, Clauses))
10351     return StmtError();
10352 
10353   setFunctionHasBranchProtectedScope();
10354   return OMPParallelForSimdDirective::Create(
10355       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10356 }
10357 
10358 StmtResult
10359 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10360                                          Stmt *AStmt, SourceLocation StartLoc,
10361                                          SourceLocation EndLoc) {
10362   if (!AStmt)
10363     return StmtError();
10364 
10365   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10366   auto *CS = cast<CapturedStmt>(AStmt);
10367   // 1.2.2 OpenMP Language Terminology
10368   // Structured block - An executable statement with a single entry at the
10369   // top and a single exit at the bottom.
10370   // The point of exit cannot be a branch out of the structured block.
10371   // longjmp() and throw() must not violate the entry/exit criteria.
10372   CS->getCapturedDecl()->setNothrow();
10373 
10374   setFunctionHasBranchProtectedScope();
10375 
10376   return OMPParallelMasterDirective::Create(
10377       Context, StartLoc, EndLoc, Clauses, AStmt,
10378       DSAStack->getTaskgroupReductionRef());
10379 }
10380 
10381 StmtResult
10382 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10383                                            Stmt *AStmt, SourceLocation StartLoc,
10384                                            SourceLocation EndLoc) {
10385   if (!AStmt)
10386     return StmtError();
10387 
10388   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10389   auto BaseStmt = AStmt;
10390   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10391     BaseStmt = CS->getCapturedStmt();
10392   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10393     auto S = C->children();
10394     if (S.begin() == S.end())
10395       return StmtError();
10396     // All associated statements must be '#pragma omp section' except for
10397     // the first one.
10398     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10399       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10400         if (SectionStmt)
10401           Diag(SectionStmt->getBeginLoc(),
10402                diag::err_omp_parallel_sections_substmt_not_section);
10403         return StmtError();
10404       }
10405       cast<OMPSectionDirective>(SectionStmt)
10406           ->setHasCancel(DSAStack->isCancelRegion());
10407     }
10408   } else {
10409     Diag(AStmt->getBeginLoc(),
10410          diag::err_omp_parallel_sections_not_compound_stmt);
10411     return StmtError();
10412   }
10413 
10414   setFunctionHasBranchProtectedScope();
10415 
10416   return OMPParallelSectionsDirective::Create(
10417       Context, StartLoc, EndLoc, Clauses, AStmt,
10418       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10419 }
10420 
10421 /// Find and diagnose mutually exclusive clause kinds.
10422 static bool checkMutuallyExclusiveClauses(
10423     Sema &S, ArrayRef<OMPClause *> Clauses,
10424     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10425   const OMPClause *PrevClause = nullptr;
10426   bool ErrorFound = false;
10427   for (const OMPClause *C : Clauses) {
10428     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10429       if (!PrevClause) {
10430         PrevClause = C;
10431       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10432         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10433             << getOpenMPClauseName(C->getClauseKind())
10434             << getOpenMPClauseName(PrevClause->getClauseKind());
10435         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10436             << getOpenMPClauseName(PrevClause->getClauseKind());
10437         ErrorFound = true;
10438       }
10439     }
10440   }
10441   return ErrorFound;
10442 }
10443 
10444 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10445                                           Stmt *AStmt, SourceLocation StartLoc,
10446                                           SourceLocation EndLoc) {
10447   if (!AStmt)
10448     return StmtError();
10449 
10450   // OpenMP 5.0, 2.10.1 task Construct
10451   // If a detach clause appears on the directive, then a mergeable clause cannot
10452   // appear on the same directive.
10453   if (checkMutuallyExclusiveClauses(*this, Clauses,
10454                                     {OMPC_detach, OMPC_mergeable}))
10455     return StmtError();
10456 
10457   auto *CS = cast<CapturedStmt>(AStmt);
10458   // 1.2.2 OpenMP Language Terminology
10459   // Structured block - An executable statement with a single entry at the
10460   // top and a single exit at the bottom.
10461   // The point of exit cannot be a branch out of the structured block.
10462   // longjmp() and throw() must not violate the entry/exit criteria.
10463   CS->getCapturedDecl()->setNothrow();
10464 
10465   setFunctionHasBranchProtectedScope();
10466 
10467   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10468                                   DSAStack->isCancelRegion());
10469 }
10470 
10471 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10472                                                SourceLocation EndLoc) {
10473   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10474 }
10475 
10476 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10477                                              SourceLocation EndLoc) {
10478   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10479 }
10480 
10481 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10482                                               SourceLocation StartLoc,
10483                                               SourceLocation EndLoc) {
10484   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
10485 }
10486 
10487 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10488                                                Stmt *AStmt,
10489                                                SourceLocation StartLoc,
10490                                                SourceLocation EndLoc) {
10491   if (!AStmt)
10492     return StmtError();
10493 
10494   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10495 
10496   setFunctionHasBranchProtectedScope();
10497 
10498   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10499                                        AStmt,
10500                                        DSAStack->getTaskgroupReductionRef());
10501 }
10502 
10503 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10504                                            SourceLocation StartLoc,
10505                                            SourceLocation EndLoc) {
10506   OMPFlushClause *FC = nullptr;
10507   OMPClause *OrderClause = nullptr;
10508   for (OMPClause *C : Clauses) {
10509     if (C->getClauseKind() == OMPC_flush)
10510       FC = cast<OMPFlushClause>(C);
10511     else
10512       OrderClause = C;
10513   }
10514   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10515   SourceLocation MemOrderLoc;
10516   for (const OMPClause *C : Clauses) {
10517     if (C->getClauseKind() == OMPC_acq_rel ||
10518         C->getClauseKind() == OMPC_acquire ||
10519         C->getClauseKind() == OMPC_release) {
10520       if (MemOrderKind != OMPC_unknown) {
10521         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10522             << getOpenMPDirectiveName(OMPD_flush) << 1
10523             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10524         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10525             << getOpenMPClauseName(MemOrderKind);
10526       } else {
10527         MemOrderKind = C->getClauseKind();
10528         MemOrderLoc = C->getBeginLoc();
10529       }
10530     }
10531   }
10532   if (FC && OrderClause) {
10533     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10534         << getOpenMPClauseName(OrderClause->getClauseKind());
10535     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10536         << getOpenMPClauseName(OrderClause->getClauseKind());
10537     return StmtError();
10538   }
10539   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10540 }
10541 
10542 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10543                                             SourceLocation StartLoc,
10544                                             SourceLocation EndLoc) {
10545   if (Clauses.empty()) {
10546     Diag(StartLoc, diag::err_omp_depobj_expected);
10547     return StmtError();
10548   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10549     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10550     return StmtError();
10551   }
10552   // Only depobj expression and another single clause is allowed.
10553   if (Clauses.size() > 2) {
10554     Diag(Clauses[2]->getBeginLoc(),
10555          diag::err_omp_depobj_single_clause_expected);
10556     return StmtError();
10557   } else if (Clauses.size() < 1) {
10558     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10559     return StmtError();
10560   }
10561   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10562 }
10563 
10564 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10565                                           SourceLocation StartLoc,
10566                                           SourceLocation EndLoc) {
10567   // Check that exactly one clause is specified.
10568   if (Clauses.size() != 1) {
10569     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10570          diag::err_omp_scan_single_clause_expected);
10571     return StmtError();
10572   }
10573   // Check that scan directive is used in the scopeof the OpenMP loop body.
10574   if (Scope *S = DSAStack->getCurScope()) {
10575     Scope *ParentS = S->getParent();
10576     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10577         !ParentS->getBreakParent()->isOpenMPLoopScope())
10578       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10579                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10580   }
10581   // Check that only one instance of scan directives is used in the same outer
10582   // region.
10583   if (DSAStack->doesParentHasScanDirective()) {
10584     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10585     Diag(DSAStack->getParentScanDirectiveLoc(),
10586          diag::note_omp_previous_directive)
10587         << "scan";
10588     return StmtError();
10589   }
10590   DSAStack->setParentHasScanDirective(StartLoc);
10591   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10592 }
10593 
10594 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10595                                              Stmt *AStmt,
10596                                              SourceLocation StartLoc,
10597                                              SourceLocation EndLoc) {
10598   const OMPClause *DependFound = nullptr;
10599   const OMPClause *DependSourceClause = nullptr;
10600   const OMPClause *DependSinkClause = nullptr;
10601   bool ErrorFound = false;
10602   const OMPThreadsClause *TC = nullptr;
10603   const OMPSIMDClause *SC = nullptr;
10604   for (const OMPClause *C : Clauses) {
10605     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10606       DependFound = C;
10607       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10608         if (DependSourceClause) {
10609           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10610               << getOpenMPDirectiveName(OMPD_ordered)
10611               << getOpenMPClauseName(OMPC_depend) << 2;
10612           ErrorFound = true;
10613         } else {
10614           DependSourceClause = C;
10615         }
10616         if (DependSinkClause) {
10617           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10618               << 0;
10619           ErrorFound = true;
10620         }
10621       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10622         if (DependSourceClause) {
10623           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10624               << 1;
10625           ErrorFound = true;
10626         }
10627         DependSinkClause = C;
10628       }
10629     } else if (C->getClauseKind() == OMPC_threads) {
10630       TC = cast<OMPThreadsClause>(C);
10631     } else if (C->getClauseKind() == OMPC_simd) {
10632       SC = cast<OMPSIMDClause>(C);
10633     }
10634   }
10635   if (!ErrorFound && !SC &&
10636       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10637     // OpenMP [2.8.1,simd Construct, Restrictions]
10638     // An ordered construct with the simd clause is the only OpenMP construct
10639     // that can appear in the simd region.
10640     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10641         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10642     ErrorFound = true;
10643   } else if (DependFound && (TC || SC)) {
10644     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10645         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10646     ErrorFound = true;
10647   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10648     Diag(DependFound->getBeginLoc(),
10649          diag::err_omp_ordered_directive_without_param);
10650     ErrorFound = true;
10651   } else if (TC || Clauses.empty()) {
10652     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10653       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10654       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10655           << (TC != nullptr);
10656       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10657       ErrorFound = true;
10658     }
10659   }
10660   if ((!AStmt && !DependFound) || ErrorFound)
10661     return StmtError();
10662 
10663   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10664   // During execution of an iteration of a worksharing-loop or a loop nest
10665   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10666   // must not execute more than one ordered region corresponding to an ordered
10667   // construct without a depend clause.
10668   if (!DependFound) {
10669     if (DSAStack->doesParentHasOrderedDirective()) {
10670       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10671       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10672            diag::note_omp_previous_directive)
10673           << "ordered";
10674       return StmtError();
10675     }
10676     DSAStack->setParentHasOrderedDirective(StartLoc);
10677   }
10678 
10679   if (AStmt) {
10680     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10681 
10682     setFunctionHasBranchProtectedScope();
10683   }
10684 
10685   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10686 }
10687 
10688 namespace {
10689 /// Helper class for checking expression in 'omp atomic [update]'
10690 /// construct.
10691 class OpenMPAtomicUpdateChecker {
10692   /// Error results for atomic update expressions.
10693   enum ExprAnalysisErrorCode {
10694     /// A statement is not an expression statement.
10695     NotAnExpression,
10696     /// Expression is not builtin binary or unary operation.
10697     NotABinaryOrUnaryExpression,
10698     /// Unary operation is not post-/pre- increment/decrement operation.
10699     NotAnUnaryIncDecExpression,
10700     /// An expression is not of scalar type.
10701     NotAScalarType,
10702     /// A binary operation is not an assignment operation.
10703     NotAnAssignmentOp,
10704     /// RHS part of the binary operation is not a binary expression.
10705     NotABinaryExpression,
10706     /// RHS part is not additive/multiplicative/shift/biwise binary
10707     /// expression.
10708     NotABinaryOperator,
10709     /// RHS binary operation does not have reference to the updated LHS
10710     /// part.
10711     NotAnUpdateExpression,
10712     /// No errors is found.
10713     NoError
10714   };
10715   /// Reference to Sema.
10716   Sema &SemaRef;
10717   /// A location for note diagnostics (when error is found).
10718   SourceLocation NoteLoc;
10719   /// 'x' lvalue part of the source atomic expression.
10720   Expr *X;
10721   /// 'expr' rvalue part of the source atomic expression.
10722   Expr *E;
10723   /// Helper expression of the form
10724   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10725   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10726   Expr *UpdateExpr;
10727   /// Is 'x' a LHS in a RHS part of full update expression. It is
10728   /// important for non-associative operations.
10729   bool IsXLHSInRHSPart;
10730   BinaryOperatorKind Op;
10731   SourceLocation OpLoc;
10732   /// true if the source expression is a postfix unary operation, false
10733   /// if it is a prefix unary operation.
10734   bool IsPostfixUpdate;
10735 
10736 public:
10737   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10738       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10739         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10740   /// Check specified statement that it is suitable for 'atomic update'
10741   /// constructs and extract 'x', 'expr' and Operation from the original
10742   /// expression. If DiagId and NoteId == 0, then only check is performed
10743   /// without error notification.
10744   /// \param DiagId Diagnostic which should be emitted if error is found.
10745   /// \param NoteId Diagnostic note for the main error message.
10746   /// \return true if statement is not an update expression, false otherwise.
10747   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10748   /// Return the 'x' lvalue part of the source atomic expression.
10749   Expr *getX() const { return X; }
10750   /// Return the 'expr' rvalue part of the source atomic expression.
10751   Expr *getExpr() const { return E; }
10752   /// Return the update expression used in calculation of the updated
10753   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10754   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10755   Expr *getUpdateExpr() const { return UpdateExpr; }
10756   /// Return true if 'x' is LHS in RHS part of full update expression,
10757   /// false otherwise.
10758   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10759 
10760   /// true if the source expression is a postfix unary operation, false
10761   /// if it is a prefix unary operation.
10762   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10763 
10764 private:
10765   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10766                             unsigned NoteId = 0);
10767 };
10768 
10769 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10770     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10771   ExprAnalysisErrorCode ErrorFound = NoError;
10772   SourceLocation ErrorLoc, NoteLoc;
10773   SourceRange ErrorRange, NoteRange;
10774   // Allowed constructs are:
10775   //  x = x binop expr;
10776   //  x = expr binop x;
10777   if (AtomicBinOp->getOpcode() == BO_Assign) {
10778     X = AtomicBinOp->getLHS();
10779     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10780             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10781       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10782           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10783           AtomicInnerBinOp->isBitwiseOp()) {
10784         Op = AtomicInnerBinOp->getOpcode();
10785         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10786         Expr *LHS = AtomicInnerBinOp->getLHS();
10787         Expr *RHS = AtomicInnerBinOp->getRHS();
10788         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10789         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10790                                           /*Canonical=*/true);
10791         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10792                                             /*Canonical=*/true);
10793         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10794                                             /*Canonical=*/true);
10795         if (XId == LHSId) {
10796           E = RHS;
10797           IsXLHSInRHSPart = true;
10798         } else if (XId == RHSId) {
10799           E = LHS;
10800           IsXLHSInRHSPart = false;
10801         } else {
10802           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10803           ErrorRange = AtomicInnerBinOp->getSourceRange();
10804           NoteLoc = X->getExprLoc();
10805           NoteRange = X->getSourceRange();
10806           ErrorFound = NotAnUpdateExpression;
10807         }
10808       } else {
10809         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10810         ErrorRange = AtomicInnerBinOp->getSourceRange();
10811         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10812         NoteRange = SourceRange(NoteLoc, NoteLoc);
10813         ErrorFound = NotABinaryOperator;
10814       }
10815     } else {
10816       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10817       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10818       ErrorFound = NotABinaryExpression;
10819     }
10820   } else {
10821     ErrorLoc = AtomicBinOp->getExprLoc();
10822     ErrorRange = AtomicBinOp->getSourceRange();
10823     NoteLoc = AtomicBinOp->getOperatorLoc();
10824     NoteRange = SourceRange(NoteLoc, NoteLoc);
10825     ErrorFound = NotAnAssignmentOp;
10826   }
10827   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10828     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10829     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10830     return true;
10831   }
10832   if (SemaRef.CurContext->isDependentContext())
10833     E = X = UpdateExpr = nullptr;
10834   return ErrorFound != NoError;
10835 }
10836 
10837 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10838                                                unsigned NoteId) {
10839   ExprAnalysisErrorCode ErrorFound = NoError;
10840   SourceLocation ErrorLoc, NoteLoc;
10841   SourceRange ErrorRange, NoteRange;
10842   // Allowed constructs are:
10843   //  x++;
10844   //  x--;
10845   //  ++x;
10846   //  --x;
10847   //  x binop= expr;
10848   //  x = x binop expr;
10849   //  x = expr binop x;
10850   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10851     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10852     if (AtomicBody->getType()->isScalarType() ||
10853         AtomicBody->isInstantiationDependent()) {
10854       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10855               AtomicBody->IgnoreParenImpCasts())) {
10856         // Check for Compound Assignment Operation
10857         Op = BinaryOperator::getOpForCompoundAssignment(
10858             AtomicCompAssignOp->getOpcode());
10859         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10860         E = AtomicCompAssignOp->getRHS();
10861         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10862         IsXLHSInRHSPart = true;
10863       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10864                      AtomicBody->IgnoreParenImpCasts())) {
10865         // Check for Binary Operation
10866         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10867           return true;
10868       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10869                      AtomicBody->IgnoreParenImpCasts())) {
10870         // Check for Unary Operation
10871         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10872           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10873           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10874           OpLoc = AtomicUnaryOp->getOperatorLoc();
10875           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10876           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10877           IsXLHSInRHSPart = true;
10878         } else {
10879           ErrorFound = NotAnUnaryIncDecExpression;
10880           ErrorLoc = AtomicUnaryOp->getExprLoc();
10881           ErrorRange = AtomicUnaryOp->getSourceRange();
10882           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10883           NoteRange = SourceRange(NoteLoc, NoteLoc);
10884         }
10885       } else if (!AtomicBody->isInstantiationDependent()) {
10886         ErrorFound = NotABinaryOrUnaryExpression;
10887         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10888         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10889       }
10890     } else {
10891       ErrorFound = NotAScalarType;
10892       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10893       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10894     }
10895   } else {
10896     ErrorFound = NotAnExpression;
10897     NoteLoc = ErrorLoc = S->getBeginLoc();
10898     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10899   }
10900   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10901     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10902     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10903     return true;
10904   }
10905   if (SemaRef.CurContext->isDependentContext())
10906     E = X = UpdateExpr = nullptr;
10907   if (ErrorFound == NoError && E && X) {
10908     // Build an update expression of form 'OpaqueValueExpr(x) binop
10909     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10910     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10911     auto *OVEX = new (SemaRef.getASTContext())
10912         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
10913     auto *OVEExpr = new (SemaRef.getASTContext())
10914         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
10915     ExprResult Update =
10916         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10917                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10918     if (Update.isInvalid())
10919       return true;
10920     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10921                                                Sema::AA_Casting);
10922     if (Update.isInvalid())
10923       return true;
10924     UpdateExpr = Update.get();
10925   }
10926   return ErrorFound != NoError;
10927 }
10928 
10929 /// Get the node id of the fixed point of an expression \a S.
10930 llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) {
10931   llvm::FoldingSetNodeID Id;
10932   S->IgnoreParenImpCasts()->Profile(Id, Context, true);
10933   return Id;
10934 }
10935 
10936 /// Check if two expressions are same.
10937 bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS,
10938                             const Expr *RHS) {
10939   return getNodeId(Context, LHS) == getNodeId(Context, RHS);
10940 }
10941 
10942 class OpenMPAtomicCompareChecker {
10943 public:
10944   /// All kinds of errors that can occur in `atomic compare`
10945   enum ErrorTy {
10946     /// Empty compound statement.
10947     NoStmt = 0,
10948     /// More than one statement in a compound statement.
10949     MoreThanOneStmt,
10950     /// Not an assignment binary operator.
10951     NotAnAssignment,
10952     /// Not a conditional operator.
10953     NotCondOp,
10954     /// Wrong false expr. According to the spec, 'x' should be at the false
10955     /// expression of a conditional expression.
10956     WrongFalseExpr,
10957     /// The condition of a conditional expression is not a binary operator.
10958     NotABinaryOp,
10959     /// Invalid binary operator (not <, >, or ==).
10960     InvalidBinaryOp,
10961     /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x).
10962     InvalidComparison,
10963     /// X is not a lvalue.
10964     XNotLValue,
10965     /// Not a scalar.
10966     NotScalar,
10967     /// Not an integer.
10968     NotInteger,
10969     /// No error.
10970     NoError,
10971   };
10972 
10973   struct ErrorInfoTy {
10974     ErrorTy Error;
10975     SourceLocation ErrorLoc;
10976     SourceRange ErrorRange;
10977     SourceLocation NoteLoc;
10978     SourceRange NoteRange;
10979   };
10980 
10981   OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {}
10982 
10983   /// Check if statement \a S is valid for <tt>atomic compare</tt>.
10984   bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
10985 
10986   Expr *getX() const { return X; }
10987   Expr *getE() const { return E; }
10988   Expr *getD() const { return D; }
10989   Expr *getCond() const { return C; }
10990   bool isXBinopExpr() const { return IsXBinopExpr; }
10991 
10992 private:
10993   /// Reference to ASTContext
10994   ASTContext &ContextRef;
10995   /// 'x' lvalue part of the source atomic expression.
10996   Expr *X = nullptr;
10997   /// 'expr' or 'e' rvalue part of the source atomic expression.
10998   Expr *E = nullptr;
10999   /// 'd' rvalue part of the source atomic expression.
11000   Expr *D = nullptr;
11001   /// 'cond' part of the source atomic expression. It is in one of the following
11002   /// forms:
11003   /// expr ordop x
11004   /// x ordop expr
11005   /// x == e
11006   /// e == x
11007   Expr *C = nullptr;
11008   /// True if the cond expr is in the form of 'x ordop expr'.
11009   bool IsXBinopExpr = true;
11010   /// The atomic compare operator.
11011   OMPAtomicCompareOp Op;
11012 
11013   /// Check if it is a valid conditional update statement (cond-update-stmt).
11014   bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo);
11015 
11016   /// Check if it is a valid conditional expression statement (cond-expr-stmt).
11017   bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
11018 
11019   /// Check if all captured values have right type.
11020   bool checkType(ErrorInfoTy &ErrorInfo) const;
11021 };
11022 
11023 bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S,
11024                                                      ErrorInfoTy &ErrorInfo) {
11025   auto *Then = S->getThen();
11026   if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
11027     if (CS->body_empty()) {
11028       ErrorInfo.Error = ErrorTy::NoStmt;
11029       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11030       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11031       return false;
11032     }
11033     if (CS->size() > 1) {
11034       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11035       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11036       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11037       return false;
11038     }
11039     Then = CS->body_front();
11040   }
11041 
11042   auto *BO = dyn_cast<BinaryOperator>(Then);
11043   if (!BO) {
11044     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11045     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
11046     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
11047     return false;
11048   }
11049   if (BO->getOpcode() != BO_Assign) {
11050     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11051     ErrorInfo.ErrorLoc = BO->getExprLoc();
11052     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11053     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11054     return false;
11055   }
11056 
11057   X = BO->getLHS();
11058 
11059   auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
11060   if (!Cond) {
11061     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11062     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
11063     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
11064     return false;
11065   }
11066 
11067   switch (Cond->getOpcode()) {
11068   case BO_EQ:
11069     Op = OMPAtomicCompareOp::EQ;
11070     break;
11071   case BO_LT:
11072     Op = OMPAtomicCompareOp::MIN;
11073     break;
11074   case BO_GT:
11075     Op = OMPAtomicCompareOp::MAX;
11076     break;
11077   default:
11078     ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
11079     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11080     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11081     return false;
11082   }
11083 
11084   if (Cond->getOpcode() == BO_EQ) {
11085     C = Cond;
11086     D = BO->getRHS();
11087     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11088       E = Cond->getRHS();
11089     } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11090       E = Cond->getLHS();
11091     } else {
11092       ErrorInfo.Error = ErrorTy::InvalidComparison;
11093       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11094       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11095       return false;
11096     }
11097   } else {
11098     E = BO->getRHS();
11099     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
11100         checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
11101       C = Cond;
11102     } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
11103                checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11104       C = Cond;
11105       IsXBinopExpr = false;
11106     } else {
11107       ErrorInfo.Error = ErrorTy::InvalidComparison;
11108       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11109       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11110       return false;
11111     }
11112   }
11113 
11114   return true;
11115 }
11116 
11117 bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S,
11118                                                    ErrorInfoTy &ErrorInfo) {
11119   auto *BO = dyn_cast<BinaryOperator>(S);
11120   if (!BO) {
11121     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11122     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
11123     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
11124     return false;
11125   }
11126   if (BO->getOpcode() != BO_Assign) {
11127     ErrorInfo.Error = ErrorTy::NotAnAssignment;
11128     ErrorInfo.ErrorLoc = BO->getExprLoc();
11129     ErrorInfo.NoteLoc = BO->getOperatorLoc();
11130     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
11131     return false;
11132   }
11133 
11134   X = BO->getLHS();
11135 
11136   auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts());
11137   if (!CO) {
11138     ErrorInfo.Error = ErrorTy::NotCondOp;
11139     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc();
11140     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange();
11141     return false;
11142   }
11143 
11144   if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) {
11145     ErrorInfo.Error = ErrorTy::WrongFalseExpr;
11146     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc();
11147     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11148         CO->getFalseExpr()->getSourceRange();
11149     return false;
11150   }
11151 
11152   auto *Cond = dyn_cast<BinaryOperator>(CO->getCond());
11153   if (!Cond) {
11154     ErrorInfo.Error = ErrorTy::NotABinaryOp;
11155     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
11156     ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
11157         CO->getCond()->getSourceRange();
11158     return false;
11159   }
11160 
11161   switch (Cond->getOpcode()) {
11162   case BO_EQ:
11163     Op = OMPAtomicCompareOp::EQ;
11164     break;
11165   case BO_LT:
11166     Op = OMPAtomicCompareOp::MIN;
11167     break;
11168   case BO_GT:
11169     Op = OMPAtomicCompareOp::MAX;
11170     break;
11171   default:
11172     ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
11173     ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11174     ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11175     return false;
11176   }
11177 
11178   if (Cond->getOpcode() == BO_EQ) {
11179     C = Cond;
11180     D = CO->getTrueExpr();
11181     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
11182       E = Cond->getRHS();
11183     } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11184       E = Cond->getLHS();
11185     } else {
11186       ErrorInfo.Error = ErrorTy::InvalidComparison;
11187       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11188       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11189       return false;
11190     }
11191   } else {
11192     E = CO->getTrueExpr();
11193     if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
11194         checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
11195       C = Cond;
11196     } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
11197                checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
11198       C = Cond;
11199       IsXBinopExpr = false;
11200     } else {
11201       ErrorInfo.Error = ErrorTy::InvalidComparison;
11202       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
11203       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
11204       return false;
11205     }
11206   }
11207 
11208   return true;
11209 }
11210 
11211 bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const {
11212   // 'x' and 'e' cannot be nullptr
11213   assert(X && E && "X and E cannot be nullptr");
11214 
11215   auto CheckValue = [&ErrorInfo](const Expr *E, OMPAtomicCompareOp Op,
11216                                  bool ShouldBeLValue) {
11217     if (ShouldBeLValue && !E->isLValue()) {
11218       ErrorInfo.Error = ErrorTy::XNotLValue;
11219       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11220       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11221       return false;
11222     }
11223 
11224     if (!E->isInstantiationDependent()) {
11225       QualType QTy = E->getType();
11226       if (!QTy->isScalarType()) {
11227         ErrorInfo.Error = ErrorTy::NotScalar;
11228         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11229         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11230         return false;
11231       }
11232 
11233       if (Op != OMPAtomicCompareOp::EQ && !QTy->isIntegerType()) {
11234         ErrorInfo.Error = ErrorTy::NotInteger;
11235         ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
11236         ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
11237         return false;
11238       }
11239     }
11240 
11241     return true;
11242   };
11243 
11244   if (!CheckValue(X, Op, true))
11245     return false;
11246 
11247   if (!CheckValue(E, Op, false))
11248     return false;
11249 
11250   if (D && !CheckValue(D, Op, false))
11251     return false;
11252 
11253   return true;
11254 }
11255 
11256 bool OpenMPAtomicCompareChecker::checkStmt(
11257     Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) {
11258   auto *CS = dyn_cast<CompoundStmt>(S);
11259   if (CS) {
11260     if (CS->body_empty()) {
11261       ErrorInfo.Error = ErrorTy::NoStmt;
11262       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11263       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11264       return false;
11265     }
11266 
11267     if (CS->size() != 1) {
11268       ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
11269       ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
11270       ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
11271       return false;
11272     }
11273     S = CS->body_front();
11274   }
11275 
11276   auto Res = false;
11277 
11278   if (auto *IS = dyn_cast<IfStmt>(S)) {
11279     // Check if the statement is in one of the following forms
11280     // (cond-update-stmt):
11281     // if (expr ordop x) { x = expr; }
11282     // if (x ordop expr) { x = expr; }
11283     // if (x == e) { x = d; }
11284     Res = checkCondUpdateStmt(IS, ErrorInfo);
11285   } else {
11286     // Check if the statement is in one of the following forms (cond-expr-stmt):
11287     // x = expr ordop x ? expr : x;
11288     // x = x ordop expr ? expr : x;
11289     // x = x == e ? d : x;
11290     Res = checkCondExprStmt(S, ErrorInfo);
11291   }
11292 
11293   if (!Res)
11294     return false;
11295 
11296   return checkType(ErrorInfo);
11297 }
11298 } // namespace
11299 
11300 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11301                                             Stmt *AStmt,
11302                                             SourceLocation StartLoc,
11303                                             SourceLocation EndLoc) {
11304   // Register location of the first atomic directive.
11305   DSAStack->addAtomicDirectiveLoc(StartLoc);
11306   if (!AStmt)
11307     return StmtError();
11308 
11309   // 1.2.2 OpenMP Language Terminology
11310   // Structured block - An executable statement with a single entry at the
11311   // top and a single exit at the bottom.
11312   // The point of exit cannot be a branch out of the structured block.
11313   // longjmp() and throw() must not violate the entry/exit criteria.
11314   OpenMPClauseKind AtomicKind = OMPC_unknown;
11315   SourceLocation AtomicKindLoc;
11316   OpenMPClauseKind MemOrderKind = OMPC_unknown;
11317   SourceLocation MemOrderLoc;
11318   for (const OMPClause *C : Clauses) {
11319     switch (C->getClauseKind()) {
11320     case OMPC_read:
11321     case OMPC_write:
11322     case OMPC_update:
11323     case OMPC_capture:
11324     case OMPC_compare: {
11325       if (AtomicKind != OMPC_unknown) {
11326         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
11327             << SourceRange(C->getBeginLoc(), C->getEndLoc());
11328         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
11329             << getOpenMPClauseName(AtomicKind);
11330       } else {
11331         AtomicKind = C->getClauseKind();
11332         AtomicKindLoc = C->getBeginLoc();
11333       }
11334       break;
11335     }
11336     case OMPC_seq_cst:
11337     case OMPC_acq_rel:
11338     case OMPC_acquire:
11339     case OMPC_release:
11340     case OMPC_relaxed: {
11341       if (MemOrderKind != OMPC_unknown) {
11342         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
11343             << getOpenMPDirectiveName(OMPD_atomic) << 0
11344             << SourceRange(C->getBeginLoc(), C->getEndLoc());
11345         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
11346             << getOpenMPClauseName(MemOrderKind);
11347       } else {
11348         MemOrderKind = C->getClauseKind();
11349         MemOrderLoc = C->getBeginLoc();
11350       }
11351       break;
11352     }
11353     // The following clauses are allowed, but we don't need to do anything here.
11354     case OMPC_hint:
11355       break;
11356     default:
11357       llvm_unreachable("unknown clause is encountered");
11358     }
11359   }
11360   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
11361   // If atomic-clause is read then memory-order-clause must not be acq_rel or
11362   // release.
11363   // If atomic-clause is write then memory-order-clause must not be acq_rel or
11364   // acquire.
11365   // If atomic-clause is update or not present then memory-order-clause must not
11366   // be acq_rel or acquire.
11367   if ((AtomicKind == OMPC_read &&
11368        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
11369       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
11370         AtomicKind == OMPC_unknown) &&
11371        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
11372     SourceLocation Loc = AtomicKindLoc;
11373     if (AtomicKind == OMPC_unknown)
11374       Loc = StartLoc;
11375     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
11376         << getOpenMPClauseName(AtomicKind)
11377         << (AtomicKind == OMPC_unknown ? 1 : 0)
11378         << getOpenMPClauseName(MemOrderKind);
11379     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
11380         << getOpenMPClauseName(MemOrderKind);
11381   }
11382 
11383   Stmt *Body = AStmt;
11384   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
11385     Body = EWC->getSubExpr();
11386 
11387   Expr *X = nullptr;
11388   Expr *V = nullptr;
11389   Expr *E = nullptr;
11390   Expr *UE = nullptr;
11391   bool IsXLHSInRHSPart = false;
11392   bool IsPostfixUpdate = false;
11393   // OpenMP [2.12.6, atomic Construct]
11394   // In the next expressions:
11395   // * x and v (as applicable) are both l-value expressions with scalar type.
11396   // * During the execution of an atomic region, multiple syntactic
11397   // occurrences of x must designate the same storage location.
11398   // * Neither of v and expr (as applicable) may access the storage location
11399   // designated by x.
11400   // * Neither of x and expr (as applicable) may access the storage location
11401   // designated by v.
11402   // * expr is an expression with scalar type.
11403   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
11404   // * binop, binop=, ++, and -- are not overloaded operators.
11405   // * The expression x binop expr must be numerically equivalent to x binop
11406   // (expr). This requirement is satisfied if the operators in expr have
11407   // precedence greater than binop, or by using parentheses around expr or
11408   // subexpressions of expr.
11409   // * The expression expr binop x must be numerically equivalent to (expr)
11410   // binop x. This requirement is satisfied if the operators in expr have
11411   // precedence equal to or greater than binop, or by using parentheses around
11412   // expr or subexpressions of expr.
11413   // * For forms that allow multiple occurrences of x, the number of times
11414   // that x is evaluated is unspecified.
11415   if (AtomicKind == OMPC_read) {
11416     enum {
11417       NotAnExpression,
11418       NotAnAssignmentOp,
11419       NotAScalarType,
11420       NotAnLValue,
11421       NoError
11422     } ErrorFound = NoError;
11423     SourceLocation ErrorLoc, NoteLoc;
11424     SourceRange ErrorRange, NoteRange;
11425     // If clause is read:
11426     //  v = x;
11427     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11428       const auto *AtomicBinOp =
11429           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11430       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11431         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11432         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
11433         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11434             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
11435           if (!X->isLValue() || !V->isLValue()) {
11436             const Expr *NotLValueExpr = X->isLValue() ? V : X;
11437             ErrorFound = NotAnLValue;
11438             ErrorLoc = AtomicBinOp->getExprLoc();
11439             ErrorRange = AtomicBinOp->getSourceRange();
11440             NoteLoc = NotLValueExpr->getExprLoc();
11441             NoteRange = NotLValueExpr->getSourceRange();
11442           }
11443         } else if (!X->isInstantiationDependent() ||
11444                    !V->isInstantiationDependent()) {
11445           const Expr *NotScalarExpr =
11446               (X->isInstantiationDependent() || X->getType()->isScalarType())
11447                   ? V
11448                   : X;
11449           ErrorFound = NotAScalarType;
11450           ErrorLoc = AtomicBinOp->getExprLoc();
11451           ErrorRange = AtomicBinOp->getSourceRange();
11452           NoteLoc = NotScalarExpr->getExprLoc();
11453           NoteRange = NotScalarExpr->getSourceRange();
11454         }
11455       } else if (!AtomicBody->isInstantiationDependent()) {
11456         ErrorFound = NotAnAssignmentOp;
11457         ErrorLoc = AtomicBody->getExprLoc();
11458         ErrorRange = AtomicBody->getSourceRange();
11459         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11460                               : AtomicBody->getExprLoc();
11461         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11462                                 : AtomicBody->getSourceRange();
11463       }
11464     } else {
11465       ErrorFound = NotAnExpression;
11466       NoteLoc = ErrorLoc = Body->getBeginLoc();
11467       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11468     }
11469     if (ErrorFound != NoError) {
11470       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
11471           << ErrorRange;
11472       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11473           << ErrorFound << NoteRange;
11474       return StmtError();
11475     }
11476     if (CurContext->isDependentContext())
11477       V = X = nullptr;
11478   } else if (AtomicKind == OMPC_write) {
11479     enum {
11480       NotAnExpression,
11481       NotAnAssignmentOp,
11482       NotAScalarType,
11483       NotAnLValue,
11484       NoError
11485     } ErrorFound = NoError;
11486     SourceLocation ErrorLoc, NoteLoc;
11487     SourceRange ErrorRange, NoteRange;
11488     // If clause is write:
11489     //  x = expr;
11490     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11491       const auto *AtomicBinOp =
11492           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11493       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11494         X = AtomicBinOp->getLHS();
11495         E = AtomicBinOp->getRHS();
11496         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11497             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
11498           if (!X->isLValue()) {
11499             ErrorFound = NotAnLValue;
11500             ErrorLoc = AtomicBinOp->getExprLoc();
11501             ErrorRange = AtomicBinOp->getSourceRange();
11502             NoteLoc = X->getExprLoc();
11503             NoteRange = X->getSourceRange();
11504           }
11505         } else if (!X->isInstantiationDependent() ||
11506                    !E->isInstantiationDependent()) {
11507           const Expr *NotScalarExpr =
11508               (X->isInstantiationDependent() || X->getType()->isScalarType())
11509                   ? E
11510                   : X;
11511           ErrorFound = NotAScalarType;
11512           ErrorLoc = AtomicBinOp->getExprLoc();
11513           ErrorRange = AtomicBinOp->getSourceRange();
11514           NoteLoc = NotScalarExpr->getExprLoc();
11515           NoteRange = NotScalarExpr->getSourceRange();
11516         }
11517       } else if (!AtomicBody->isInstantiationDependent()) {
11518         ErrorFound = NotAnAssignmentOp;
11519         ErrorLoc = AtomicBody->getExprLoc();
11520         ErrorRange = AtomicBody->getSourceRange();
11521         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11522                               : AtomicBody->getExprLoc();
11523         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11524                                 : AtomicBody->getSourceRange();
11525       }
11526     } else {
11527       ErrorFound = NotAnExpression;
11528       NoteLoc = ErrorLoc = Body->getBeginLoc();
11529       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11530     }
11531     if (ErrorFound != NoError) {
11532       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
11533           << ErrorRange;
11534       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11535           << ErrorFound << NoteRange;
11536       return StmtError();
11537     }
11538     if (CurContext->isDependentContext())
11539       E = X = nullptr;
11540   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
11541     // If clause is update:
11542     //  x++;
11543     //  x--;
11544     //  ++x;
11545     //  --x;
11546     //  x binop= expr;
11547     //  x = x binop expr;
11548     //  x = expr binop x;
11549     OpenMPAtomicUpdateChecker Checker(*this);
11550     if (Checker.checkStatement(
11551             Body,
11552             (AtomicKind == OMPC_update)
11553                 ? diag::err_omp_atomic_update_not_expression_statement
11554                 : diag::err_omp_atomic_not_expression_statement,
11555             diag::note_omp_atomic_update))
11556       return StmtError();
11557     if (!CurContext->isDependentContext()) {
11558       E = Checker.getExpr();
11559       X = Checker.getX();
11560       UE = Checker.getUpdateExpr();
11561       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11562     }
11563   } else if (AtomicKind == OMPC_capture) {
11564     enum {
11565       NotAnAssignmentOp,
11566       NotACompoundStatement,
11567       NotTwoSubstatements,
11568       NotASpecificExpression,
11569       NoError
11570     } ErrorFound = NoError;
11571     SourceLocation ErrorLoc, NoteLoc;
11572     SourceRange ErrorRange, NoteRange;
11573     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11574       // If clause is a capture:
11575       //  v = x++;
11576       //  v = x--;
11577       //  v = ++x;
11578       //  v = --x;
11579       //  v = x binop= expr;
11580       //  v = x = x binop expr;
11581       //  v = x = expr binop x;
11582       const auto *AtomicBinOp =
11583           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11584       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11585         V = AtomicBinOp->getLHS();
11586         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11587         OpenMPAtomicUpdateChecker Checker(*this);
11588         if (Checker.checkStatement(
11589                 Body, diag::err_omp_atomic_capture_not_expression_statement,
11590                 diag::note_omp_atomic_update))
11591           return StmtError();
11592         E = Checker.getExpr();
11593         X = Checker.getX();
11594         UE = Checker.getUpdateExpr();
11595         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11596         IsPostfixUpdate = Checker.isPostfixUpdate();
11597       } else if (!AtomicBody->isInstantiationDependent()) {
11598         ErrorLoc = AtomicBody->getExprLoc();
11599         ErrorRange = AtomicBody->getSourceRange();
11600         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11601                               : AtomicBody->getExprLoc();
11602         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11603                                 : AtomicBody->getSourceRange();
11604         ErrorFound = NotAnAssignmentOp;
11605       }
11606       if (ErrorFound != NoError) {
11607         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
11608             << ErrorRange;
11609         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11610         return StmtError();
11611       }
11612       if (CurContext->isDependentContext())
11613         UE = V = E = X = nullptr;
11614     } else {
11615       // If clause is a capture:
11616       //  { v = x; x = expr; }
11617       //  { v = x; x++; }
11618       //  { v = x; x--; }
11619       //  { v = x; ++x; }
11620       //  { v = x; --x; }
11621       //  { v = x; x binop= expr; }
11622       //  { v = x; x = x binop expr; }
11623       //  { v = x; x = expr binop x; }
11624       //  { x++; v = x; }
11625       //  { x--; v = x; }
11626       //  { ++x; v = x; }
11627       //  { --x; v = x; }
11628       //  { x binop= expr; v = x; }
11629       //  { x = x binop expr; v = x; }
11630       //  { x = expr binop x; v = x; }
11631       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
11632         // Check that this is { expr1; expr2; }
11633         if (CS->size() == 2) {
11634           Stmt *First = CS->body_front();
11635           Stmt *Second = CS->body_back();
11636           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
11637             First = EWC->getSubExpr()->IgnoreParenImpCasts();
11638           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
11639             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
11640           // Need to find what subexpression is 'v' and what is 'x'.
11641           OpenMPAtomicUpdateChecker Checker(*this);
11642           bool IsUpdateExprFound = !Checker.checkStatement(Second);
11643           BinaryOperator *BinOp = nullptr;
11644           if (IsUpdateExprFound) {
11645             BinOp = dyn_cast<BinaryOperator>(First);
11646             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11647           }
11648           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11649             //  { v = x; x++; }
11650             //  { v = x; x--; }
11651             //  { v = x; ++x; }
11652             //  { v = x; --x; }
11653             //  { v = x; x binop= expr; }
11654             //  { v = x; x = x binop expr; }
11655             //  { v = x; x = expr binop x; }
11656             // Check that the first expression has form v = x.
11657             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11658             llvm::FoldingSetNodeID XId, PossibleXId;
11659             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11660             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11661             IsUpdateExprFound = XId == PossibleXId;
11662             if (IsUpdateExprFound) {
11663               V = BinOp->getLHS();
11664               X = Checker.getX();
11665               E = Checker.getExpr();
11666               UE = Checker.getUpdateExpr();
11667               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11668               IsPostfixUpdate = true;
11669             }
11670           }
11671           if (!IsUpdateExprFound) {
11672             IsUpdateExprFound = !Checker.checkStatement(First);
11673             BinOp = nullptr;
11674             if (IsUpdateExprFound) {
11675               BinOp = dyn_cast<BinaryOperator>(Second);
11676               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11677             }
11678             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11679               //  { x++; v = x; }
11680               //  { x--; v = x; }
11681               //  { ++x; v = x; }
11682               //  { --x; v = x; }
11683               //  { x binop= expr; v = x; }
11684               //  { x = x binop expr; v = x; }
11685               //  { x = expr binop x; v = x; }
11686               // Check that the second expression has form v = x.
11687               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11688               llvm::FoldingSetNodeID XId, PossibleXId;
11689               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11690               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11691               IsUpdateExprFound = XId == PossibleXId;
11692               if (IsUpdateExprFound) {
11693                 V = BinOp->getLHS();
11694                 X = Checker.getX();
11695                 E = Checker.getExpr();
11696                 UE = Checker.getUpdateExpr();
11697                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11698                 IsPostfixUpdate = false;
11699               }
11700             }
11701           }
11702           if (!IsUpdateExprFound) {
11703             //  { v = x; x = expr; }
11704             auto *FirstExpr = dyn_cast<Expr>(First);
11705             auto *SecondExpr = dyn_cast<Expr>(Second);
11706             if (!FirstExpr || !SecondExpr ||
11707                 !(FirstExpr->isInstantiationDependent() ||
11708                   SecondExpr->isInstantiationDependent())) {
11709               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11710               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11711                 ErrorFound = NotAnAssignmentOp;
11712                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11713                                                 : First->getBeginLoc();
11714                 NoteRange = ErrorRange = FirstBinOp
11715                                              ? FirstBinOp->getSourceRange()
11716                                              : SourceRange(ErrorLoc, ErrorLoc);
11717               } else {
11718                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11719                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11720                   ErrorFound = NotAnAssignmentOp;
11721                   NoteLoc = ErrorLoc = SecondBinOp
11722                                            ? SecondBinOp->getOperatorLoc()
11723                                            : Second->getBeginLoc();
11724                   NoteRange = ErrorRange =
11725                       SecondBinOp ? SecondBinOp->getSourceRange()
11726                                   : SourceRange(ErrorLoc, ErrorLoc);
11727                 } else {
11728                   Expr *PossibleXRHSInFirst =
11729                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11730                   Expr *PossibleXLHSInSecond =
11731                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11732                   llvm::FoldingSetNodeID X1Id, X2Id;
11733                   PossibleXRHSInFirst->Profile(X1Id, Context,
11734                                                /*Canonical=*/true);
11735                   PossibleXLHSInSecond->Profile(X2Id, Context,
11736                                                 /*Canonical=*/true);
11737                   IsUpdateExprFound = X1Id == X2Id;
11738                   if (IsUpdateExprFound) {
11739                     V = FirstBinOp->getLHS();
11740                     X = SecondBinOp->getLHS();
11741                     E = SecondBinOp->getRHS();
11742                     UE = nullptr;
11743                     IsXLHSInRHSPart = false;
11744                     IsPostfixUpdate = true;
11745                   } else {
11746                     ErrorFound = NotASpecificExpression;
11747                     ErrorLoc = FirstBinOp->getExprLoc();
11748                     ErrorRange = FirstBinOp->getSourceRange();
11749                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11750                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11751                   }
11752                 }
11753               }
11754             }
11755           }
11756         } else {
11757           NoteLoc = ErrorLoc = Body->getBeginLoc();
11758           NoteRange = ErrorRange =
11759               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11760           ErrorFound = NotTwoSubstatements;
11761         }
11762       } else {
11763         NoteLoc = ErrorLoc = Body->getBeginLoc();
11764         NoteRange = ErrorRange =
11765             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11766         ErrorFound = NotACompoundStatement;
11767       }
11768     }
11769     if (ErrorFound != NoError) {
11770       Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11771           << ErrorRange;
11772       Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11773       return StmtError();
11774     }
11775     if (CurContext->isDependentContext())
11776       UE = V = E = X = nullptr;
11777   } else if (AtomicKind == OMPC_compare) {
11778     OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo;
11779     OpenMPAtomicCompareChecker Checker(*this);
11780     if (!Checker.checkStmt(Body, ErrorInfo)) {
11781       Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare)
11782           << ErrorInfo.ErrorRange;
11783       Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
11784           << ErrorInfo.Error << ErrorInfo.NoteRange;
11785       return StmtError();
11786     }
11787     // TODO: We don't set X, D, E, etc. here because in code gen we will emit
11788     // error directly.
11789   }
11790 
11791   setFunctionHasBranchProtectedScope();
11792 
11793   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11794                                     X, V, E, UE, IsXLHSInRHSPart,
11795                                     IsPostfixUpdate);
11796 }
11797 
11798 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11799                                             Stmt *AStmt,
11800                                             SourceLocation StartLoc,
11801                                             SourceLocation EndLoc) {
11802   if (!AStmt)
11803     return StmtError();
11804 
11805   auto *CS = cast<CapturedStmt>(AStmt);
11806   // 1.2.2 OpenMP Language Terminology
11807   // Structured block - An executable statement with a single entry at the
11808   // top and a single exit at the bottom.
11809   // The point of exit cannot be a branch out of the structured block.
11810   // longjmp() and throw() must not violate the entry/exit criteria.
11811   CS->getCapturedDecl()->setNothrow();
11812   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11813        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11814     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11815     // 1.2.2 OpenMP Language Terminology
11816     // Structured block - An executable statement with a single entry at the
11817     // top and a single exit at the bottom.
11818     // The point of exit cannot be a branch out of the structured block.
11819     // longjmp() and throw() must not violate the entry/exit criteria.
11820     CS->getCapturedDecl()->setNothrow();
11821   }
11822 
11823   // OpenMP [2.16, Nesting of Regions]
11824   // If specified, a teams construct must be contained within a target
11825   // construct. That target construct must contain no statements or directives
11826   // outside of the teams construct.
11827   if (DSAStack->hasInnerTeamsRegion()) {
11828     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11829     bool OMPTeamsFound = true;
11830     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11831       auto I = CS->body_begin();
11832       while (I != CS->body_end()) {
11833         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11834         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11835             OMPTeamsFound) {
11836 
11837           OMPTeamsFound = false;
11838           break;
11839         }
11840         ++I;
11841       }
11842       assert(I != CS->body_end() && "Not found statement");
11843       S = *I;
11844     } else {
11845       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11846       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11847     }
11848     if (!OMPTeamsFound) {
11849       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11850       Diag(DSAStack->getInnerTeamsRegionLoc(),
11851            diag::note_omp_nested_teams_construct_here);
11852       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11853           << isa<OMPExecutableDirective>(S);
11854       return StmtError();
11855     }
11856   }
11857 
11858   setFunctionHasBranchProtectedScope();
11859 
11860   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11861 }
11862 
11863 StmtResult
11864 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11865                                          Stmt *AStmt, SourceLocation StartLoc,
11866                                          SourceLocation EndLoc) {
11867   if (!AStmt)
11868     return StmtError();
11869 
11870   auto *CS = cast<CapturedStmt>(AStmt);
11871   // 1.2.2 OpenMP Language Terminology
11872   // Structured block - An executable statement with a single entry at the
11873   // top and a single exit at the bottom.
11874   // The point of exit cannot be a branch out of the structured block.
11875   // longjmp() and throw() must not violate the entry/exit criteria.
11876   CS->getCapturedDecl()->setNothrow();
11877   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11878        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11879     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11880     // 1.2.2 OpenMP Language Terminology
11881     // Structured block - An executable statement with a single entry at the
11882     // top and a single exit at the bottom.
11883     // The point of exit cannot be a branch out of the structured block.
11884     // longjmp() and throw() must not violate the entry/exit criteria.
11885     CS->getCapturedDecl()->setNothrow();
11886   }
11887 
11888   setFunctionHasBranchProtectedScope();
11889 
11890   return OMPTargetParallelDirective::Create(
11891       Context, StartLoc, EndLoc, Clauses, AStmt,
11892       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11893 }
11894 
11895 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11896     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11897     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11898   if (!AStmt)
11899     return StmtError();
11900 
11901   auto *CS = cast<CapturedStmt>(AStmt);
11902   // 1.2.2 OpenMP Language Terminology
11903   // Structured block - An executable statement with a single entry at the
11904   // top and a single exit at the bottom.
11905   // The point of exit cannot be a branch out of the structured block.
11906   // longjmp() and throw() must not violate the entry/exit criteria.
11907   CS->getCapturedDecl()->setNothrow();
11908   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11909        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11910     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11911     // 1.2.2 OpenMP Language Terminology
11912     // Structured block - An executable statement with a single entry at the
11913     // top and a single exit at the bottom.
11914     // The point of exit cannot be a branch out of the structured block.
11915     // longjmp() and throw() must not violate the entry/exit criteria.
11916     CS->getCapturedDecl()->setNothrow();
11917   }
11918 
11919   OMPLoopBasedDirective::HelperExprs B;
11920   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11921   // define the nested loops number.
11922   unsigned NestedLoopCount =
11923       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11924                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11925                       VarsWithImplicitDSA, B);
11926   if (NestedLoopCount == 0)
11927     return StmtError();
11928 
11929   assert((CurContext->isDependentContext() || B.builtAll()) &&
11930          "omp target parallel for loop exprs were not built");
11931 
11932   if (!CurContext->isDependentContext()) {
11933     // Finalize the clauses that need pre-built expressions for CodeGen.
11934     for (OMPClause *C : Clauses) {
11935       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11936         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11937                                      B.NumIterations, *this, CurScope,
11938                                      DSAStack))
11939           return StmtError();
11940     }
11941   }
11942 
11943   setFunctionHasBranchProtectedScope();
11944   return OMPTargetParallelForDirective::Create(
11945       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11946       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11947 }
11948 
11949 /// Check for existence of a map clause in the list of clauses.
11950 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11951                        const OpenMPClauseKind K) {
11952   return llvm::any_of(
11953       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11954 }
11955 
11956 template <typename... Params>
11957 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11958                        const Params... ClauseTypes) {
11959   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11960 }
11961 
11962 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11963                                                 Stmt *AStmt,
11964                                                 SourceLocation StartLoc,
11965                                                 SourceLocation EndLoc) {
11966   if (!AStmt)
11967     return StmtError();
11968 
11969   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11970 
11971   // OpenMP [2.12.2, target data Construct, Restrictions]
11972   // At least one map, use_device_addr or use_device_ptr clause must appear on
11973   // the directive.
11974   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11975       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11976     StringRef Expected;
11977     if (LangOpts.OpenMP < 50)
11978       Expected = "'map' or 'use_device_ptr'";
11979     else
11980       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11981     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11982         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11983     return StmtError();
11984   }
11985 
11986   setFunctionHasBranchProtectedScope();
11987 
11988   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11989                                         AStmt);
11990 }
11991 
11992 StmtResult
11993 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11994                                           SourceLocation StartLoc,
11995                                           SourceLocation EndLoc, Stmt *AStmt) {
11996   if (!AStmt)
11997     return StmtError();
11998 
11999   auto *CS = cast<CapturedStmt>(AStmt);
12000   // 1.2.2 OpenMP Language Terminology
12001   // Structured block - An executable statement with a single entry at the
12002   // top and a single exit at the bottom.
12003   // The point of exit cannot be a branch out of the structured block.
12004   // longjmp() and throw() must not violate the entry/exit criteria.
12005   CS->getCapturedDecl()->setNothrow();
12006   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
12007        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12008     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12009     // 1.2.2 OpenMP Language Terminology
12010     // Structured block - An executable statement with a single entry at the
12011     // top and a single exit at the bottom.
12012     // The point of exit cannot be a branch out of the structured block.
12013     // longjmp() and throw() must not violate the entry/exit criteria.
12014     CS->getCapturedDecl()->setNothrow();
12015   }
12016 
12017   // OpenMP [2.10.2, Restrictions, p. 99]
12018   // At least one map clause must appear on the directive.
12019   if (!hasClauses(Clauses, OMPC_map)) {
12020     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12021         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
12022     return StmtError();
12023   }
12024 
12025   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12026                                              AStmt);
12027 }
12028 
12029 StmtResult
12030 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
12031                                          SourceLocation StartLoc,
12032                                          SourceLocation EndLoc, Stmt *AStmt) {
12033   if (!AStmt)
12034     return StmtError();
12035 
12036   auto *CS = cast<CapturedStmt>(AStmt);
12037   // 1.2.2 OpenMP Language Terminology
12038   // Structured block - An executable statement with a single entry at the
12039   // top and a single exit at the bottom.
12040   // The point of exit cannot be a branch out of the structured block.
12041   // longjmp() and throw() must not violate the entry/exit criteria.
12042   CS->getCapturedDecl()->setNothrow();
12043   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
12044        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12045     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12046     // 1.2.2 OpenMP Language Terminology
12047     // Structured block - An executable statement with a single entry at the
12048     // top and a single exit at the bottom.
12049     // The point of exit cannot be a branch out of the structured block.
12050     // longjmp() and throw() must not violate the entry/exit criteria.
12051     CS->getCapturedDecl()->setNothrow();
12052   }
12053 
12054   // OpenMP [2.10.3, Restrictions, p. 102]
12055   // At least one map clause must appear on the directive.
12056   if (!hasClauses(Clauses, OMPC_map)) {
12057     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
12058         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
12059     return StmtError();
12060   }
12061 
12062   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
12063                                             AStmt);
12064 }
12065 
12066 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
12067                                                   SourceLocation StartLoc,
12068                                                   SourceLocation EndLoc,
12069                                                   Stmt *AStmt) {
12070   if (!AStmt)
12071     return StmtError();
12072 
12073   auto *CS = cast<CapturedStmt>(AStmt);
12074   // 1.2.2 OpenMP Language Terminology
12075   // Structured block - An executable statement with a single entry at the
12076   // top and a single exit at the bottom.
12077   // The point of exit cannot be a branch out of the structured block.
12078   // longjmp() and throw() must not violate the entry/exit criteria.
12079   CS->getCapturedDecl()->setNothrow();
12080   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
12081        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12082     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12083     // 1.2.2 OpenMP Language Terminology
12084     // Structured block - An executable statement with a single entry at the
12085     // top and a single exit at the bottom.
12086     // The point of exit cannot be a branch out of the structured block.
12087     // longjmp() and throw() must not violate the entry/exit criteria.
12088     CS->getCapturedDecl()->setNothrow();
12089   }
12090 
12091   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
12092     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
12093     return StmtError();
12094   }
12095   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
12096                                           AStmt);
12097 }
12098 
12099 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
12100                                            Stmt *AStmt, SourceLocation StartLoc,
12101                                            SourceLocation EndLoc) {
12102   if (!AStmt)
12103     return StmtError();
12104 
12105   auto *CS = cast<CapturedStmt>(AStmt);
12106   // 1.2.2 OpenMP Language Terminology
12107   // Structured block - An executable statement with a single entry at the
12108   // top and a single exit at the bottom.
12109   // The point of exit cannot be a branch out of the structured block.
12110   // longjmp() and throw() must not violate the entry/exit criteria.
12111   CS->getCapturedDecl()->setNothrow();
12112 
12113   setFunctionHasBranchProtectedScope();
12114 
12115   DSAStack->setParentTeamsRegionLoc(StartLoc);
12116 
12117   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
12118 }
12119 
12120 StmtResult
12121 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
12122                                             SourceLocation EndLoc,
12123                                             OpenMPDirectiveKind CancelRegion) {
12124   if (DSAStack->isParentNowaitRegion()) {
12125     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
12126     return StmtError();
12127   }
12128   if (DSAStack->isParentOrderedRegion()) {
12129     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
12130     return StmtError();
12131   }
12132   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
12133                                                CancelRegion);
12134 }
12135 
12136 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
12137                                             SourceLocation StartLoc,
12138                                             SourceLocation EndLoc,
12139                                             OpenMPDirectiveKind CancelRegion) {
12140   if (DSAStack->isParentNowaitRegion()) {
12141     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
12142     return StmtError();
12143   }
12144   if (DSAStack->isParentOrderedRegion()) {
12145     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
12146     return StmtError();
12147   }
12148   DSAStack->setParentCancelRegion(/*Cancel=*/true);
12149   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
12150                                     CancelRegion);
12151 }
12152 
12153 static bool checkReductionClauseWithNogroup(Sema &S,
12154                                             ArrayRef<OMPClause *> Clauses) {
12155   const OMPClause *ReductionClause = nullptr;
12156   const OMPClause *NogroupClause = nullptr;
12157   for (const OMPClause *C : Clauses) {
12158     if (C->getClauseKind() == OMPC_reduction) {
12159       ReductionClause = C;
12160       if (NogroupClause)
12161         break;
12162       continue;
12163     }
12164     if (C->getClauseKind() == OMPC_nogroup) {
12165       NogroupClause = C;
12166       if (ReductionClause)
12167         break;
12168       continue;
12169     }
12170   }
12171   if (ReductionClause && NogroupClause) {
12172     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
12173         << SourceRange(NogroupClause->getBeginLoc(),
12174                        NogroupClause->getEndLoc());
12175     return true;
12176   }
12177   return false;
12178 }
12179 
12180 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
12181     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12182     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12183   if (!AStmt)
12184     return StmtError();
12185 
12186   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12187   OMPLoopBasedDirective::HelperExprs B;
12188   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12189   // define the nested loops number.
12190   unsigned NestedLoopCount =
12191       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
12192                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12193                       VarsWithImplicitDSA, B);
12194   if (NestedLoopCount == 0)
12195     return StmtError();
12196 
12197   assert((CurContext->isDependentContext() || B.builtAll()) &&
12198          "omp for loop exprs were not built");
12199 
12200   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12201   // The grainsize clause and num_tasks clause are mutually exclusive and may
12202   // not appear on the same taskloop directive.
12203   if (checkMutuallyExclusiveClauses(*this, Clauses,
12204                                     {OMPC_grainsize, OMPC_num_tasks}))
12205     return StmtError();
12206   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12207   // If a reduction clause is present on the taskloop directive, the nogroup
12208   // clause must not be specified.
12209   if (checkReductionClauseWithNogroup(*this, Clauses))
12210     return StmtError();
12211 
12212   setFunctionHasBranchProtectedScope();
12213   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
12214                                       NestedLoopCount, Clauses, AStmt, B,
12215                                       DSAStack->isCancelRegion());
12216 }
12217 
12218 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
12219     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12220     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12221   if (!AStmt)
12222     return StmtError();
12223 
12224   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12225   OMPLoopBasedDirective::HelperExprs B;
12226   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12227   // define the nested loops number.
12228   unsigned NestedLoopCount =
12229       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
12230                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12231                       VarsWithImplicitDSA, B);
12232   if (NestedLoopCount == 0)
12233     return StmtError();
12234 
12235   assert((CurContext->isDependentContext() || B.builtAll()) &&
12236          "omp for loop exprs were not built");
12237 
12238   if (!CurContext->isDependentContext()) {
12239     // Finalize the clauses that need pre-built expressions for CodeGen.
12240     for (OMPClause *C : Clauses) {
12241       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12242         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12243                                      B.NumIterations, *this, CurScope,
12244                                      DSAStack))
12245           return StmtError();
12246     }
12247   }
12248 
12249   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12250   // The grainsize clause and num_tasks clause are mutually exclusive and may
12251   // not appear on the same taskloop directive.
12252   if (checkMutuallyExclusiveClauses(*this, Clauses,
12253                                     {OMPC_grainsize, OMPC_num_tasks}))
12254     return StmtError();
12255   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12256   // If a reduction clause is present on the taskloop directive, the nogroup
12257   // clause must not be specified.
12258   if (checkReductionClauseWithNogroup(*this, Clauses))
12259     return StmtError();
12260   if (checkSimdlenSafelenSpecified(*this, Clauses))
12261     return StmtError();
12262 
12263   setFunctionHasBranchProtectedScope();
12264   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
12265                                           NestedLoopCount, Clauses, AStmt, B);
12266 }
12267 
12268 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
12269     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12270     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12271   if (!AStmt)
12272     return StmtError();
12273 
12274   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12275   OMPLoopBasedDirective::HelperExprs B;
12276   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12277   // define the nested loops number.
12278   unsigned NestedLoopCount =
12279       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
12280                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12281                       VarsWithImplicitDSA, B);
12282   if (NestedLoopCount == 0)
12283     return StmtError();
12284 
12285   assert((CurContext->isDependentContext() || B.builtAll()) &&
12286          "omp for loop exprs were not built");
12287 
12288   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12289   // The grainsize clause and num_tasks clause are mutually exclusive and may
12290   // not appear on the same taskloop directive.
12291   if (checkMutuallyExclusiveClauses(*this, Clauses,
12292                                     {OMPC_grainsize, OMPC_num_tasks}))
12293     return StmtError();
12294   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12295   // If a reduction clause is present on the taskloop directive, the nogroup
12296   // clause must not be specified.
12297   if (checkReductionClauseWithNogroup(*this, Clauses))
12298     return StmtError();
12299 
12300   setFunctionHasBranchProtectedScope();
12301   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
12302                                             NestedLoopCount, Clauses, AStmt, B,
12303                                             DSAStack->isCancelRegion());
12304 }
12305 
12306 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
12307     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12308     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12309   if (!AStmt)
12310     return StmtError();
12311 
12312   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12313   OMPLoopBasedDirective::HelperExprs B;
12314   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12315   // define the nested loops number.
12316   unsigned NestedLoopCount =
12317       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
12318                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
12319                       VarsWithImplicitDSA, B);
12320   if (NestedLoopCount == 0)
12321     return StmtError();
12322 
12323   assert((CurContext->isDependentContext() || B.builtAll()) &&
12324          "omp for loop exprs were not built");
12325 
12326   if (!CurContext->isDependentContext()) {
12327     // Finalize the clauses that need pre-built expressions for CodeGen.
12328     for (OMPClause *C : Clauses) {
12329       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12330         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12331                                      B.NumIterations, *this, CurScope,
12332                                      DSAStack))
12333           return StmtError();
12334     }
12335   }
12336 
12337   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12338   // The grainsize clause and num_tasks clause are mutually exclusive and may
12339   // not appear on the same taskloop directive.
12340   if (checkMutuallyExclusiveClauses(*this, Clauses,
12341                                     {OMPC_grainsize, OMPC_num_tasks}))
12342     return StmtError();
12343   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12344   // If a reduction clause is present on the taskloop directive, the nogroup
12345   // clause must not be specified.
12346   if (checkReductionClauseWithNogroup(*this, Clauses))
12347     return StmtError();
12348   if (checkSimdlenSafelenSpecified(*this, Clauses))
12349     return StmtError();
12350 
12351   setFunctionHasBranchProtectedScope();
12352   return OMPMasterTaskLoopSimdDirective::Create(
12353       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12354 }
12355 
12356 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
12357     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12358     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12359   if (!AStmt)
12360     return StmtError();
12361 
12362   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12363   auto *CS = cast<CapturedStmt>(AStmt);
12364   // 1.2.2 OpenMP Language Terminology
12365   // Structured block - An executable statement with a single entry at the
12366   // top and a single exit at the bottom.
12367   // The point of exit cannot be a branch out of the structured block.
12368   // longjmp() and throw() must not violate the entry/exit criteria.
12369   CS->getCapturedDecl()->setNothrow();
12370   for (int ThisCaptureLevel =
12371            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
12372        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12373     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12374     // 1.2.2 OpenMP Language Terminology
12375     // Structured block - An executable statement with a single entry at the
12376     // top and a single exit at the bottom.
12377     // The point of exit cannot be a branch out of the structured block.
12378     // longjmp() and throw() must not violate the entry/exit criteria.
12379     CS->getCapturedDecl()->setNothrow();
12380   }
12381 
12382   OMPLoopBasedDirective::HelperExprs B;
12383   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12384   // define the nested loops number.
12385   unsigned NestedLoopCount = checkOpenMPLoop(
12386       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
12387       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
12388       VarsWithImplicitDSA, B);
12389   if (NestedLoopCount == 0)
12390     return StmtError();
12391 
12392   assert((CurContext->isDependentContext() || B.builtAll()) &&
12393          "omp for loop exprs were not built");
12394 
12395   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12396   // The grainsize clause and num_tasks clause are mutually exclusive and may
12397   // not appear on the same taskloop directive.
12398   if (checkMutuallyExclusiveClauses(*this, Clauses,
12399                                     {OMPC_grainsize, OMPC_num_tasks}))
12400     return StmtError();
12401   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12402   // If a reduction clause is present on the taskloop directive, the nogroup
12403   // clause must not be specified.
12404   if (checkReductionClauseWithNogroup(*this, Clauses))
12405     return StmtError();
12406 
12407   setFunctionHasBranchProtectedScope();
12408   return OMPParallelMasterTaskLoopDirective::Create(
12409       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12410       DSAStack->isCancelRegion());
12411 }
12412 
12413 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
12414     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12415     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12416   if (!AStmt)
12417     return StmtError();
12418 
12419   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12420   auto *CS = cast<CapturedStmt>(AStmt);
12421   // 1.2.2 OpenMP Language Terminology
12422   // Structured block - An executable statement with a single entry at the
12423   // top and a single exit at the bottom.
12424   // The point of exit cannot be a branch out of the structured block.
12425   // longjmp() and throw() must not violate the entry/exit criteria.
12426   CS->getCapturedDecl()->setNothrow();
12427   for (int ThisCaptureLevel =
12428            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
12429        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12430     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12431     // 1.2.2 OpenMP Language Terminology
12432     // Structured block - An executable statement with a single entry at the
12433     // top and a single exit at the bottom.
12434     // The point of exit cannot be a branch out of the structured block.
12435     // longjmp() and throw() must not violate the entry/exit criteria.
12436     CS->getCapturedDecl()->setNothrow();
12437   }
12438 
12439   OMPLoopBasedDirective::HelperExprs B;
12440   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12441   // define the nested loops number.
12442   unsigned NestedLoopCount = checkOpenMPLoop(
12443       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
12444       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
12445       VarsWithImplicitDSA, B);
12446   if (NestedLoopCount == 0)
12447     return StmtError();
12448 
12449   assert((CurContext->isDependentContext() || B.builtAll()) &&
12450          "omp for loop exprs were not built");
12451 
12452   if (!CurContext->isDependentContext()) {
12453     // Finalize the clauses that need pre-built expressions for CodeGen.
12454     for (OMPClause *C : Clauses) {
12455       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12456         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12457                                      B.NumIterations, *this, CurScope,
12458                                      DSAStack))
12459           return StmtError();
12460     }
12461   }
12462 
12463   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12464   // The grainsize clause and num_tasks clause are mutually exclusive and may
12465   // not appear on the same taskloop directive.
12466   if (checkMutuallyExclusiveClauses(*this, Clauses,
12467                                     {OMPC_grainsize, OMPC_num_tasks}))
12468     return StmtError();
12469   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12470   // If a reduction clause is present on the taskloop directive, the nogroup
12471   // clause must not be specified.
12472   if (checkReductionClauseWithNogroup(*this, Clauses))
12473     return StmtError();
12474   if (checkSimdlenSafelenSpecified(*this, Clauses))
12475     return StmtError();
12476 
12477   setFunctionHasBranchProtectedScope();
12478   return OMPParallelMasterTaskLoopSimdDirective::Create(
12479       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12480 }
12481 
12482 StmtResult Sema::ActOnOpenMPDistributeDirective(
12483     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12484     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12485   if (!AStmt)
12486     return StmtError();
12487 
12488   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12489   OMPLoopBasedDirective::HelperExprs B;
12490   // In presence of clause 'collapse' with number of loops, it will
12491   // define the nested loops number.
12492   unsigned NestedLoopCount =
12493       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
12494                       nullptr /*ordered not a clause on distribute*/, AStmt,
12495                       *this, *DSAStack, VarsWithImplicitDSA, B);
12496   if (NestedLoopCount == 0)
12497     return StmtError();
12498 
12499   assert((CurContext->isDependentContext() || B.builtAll()) &&
12500          "omp for loop exprs were not built");
12501 
12502   setFunctionHasBranchProtectedScope();
12503   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
12504                                         NestedLoopCount, Clauses, AStmt, B);
12505 }
12506 
12507 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
12508     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12509     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12510   if (!AStmt)
12511     return StmtError();
12512 
12513   auto *CS = cast<CapturedStmt>(AStmt);
12514   // 1.2.2 OpenMP Language Terminology
12515   // Structured block - An executable statement with a single entry at the
12516   // top and a single exit at the bottom.
12517   // The point of exit cannot be a branch out of the structured block.
12518   // longjmp() and throw() must not violate the entry/exit criteria.
12519   CS->getCapturedDecl()->setNothrow();
12520   for (int ThisCaptureLevel =
12521            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
12522        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12523     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12524     // 1.2.2 OpenMP Language Terminology
12525     // Structured block - An executable statement with a single entry at the
12526     // top and a single exit at the bottom.
12527     // The point of exit cannot be a branch out of the structured block.
12528     // longjmp() and throw() must not violate the entry/exit criteria.
12529     CS->getCapturedDecl()->setNothrow();
12530   }
12531 
12532   OMPLoopBasedDirective::HelperExprs B;
12533   // In presence of clause 'collapse' with number of loops, it will
12534   // define the nested loops number.
12535   unsigned NestedLoopCount = checkOpenMPLoop(
12536       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12537       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12538       VarsWithImplicitDSA, B);
12539   if (NestedLoopCount == 0)
12540     return StmtError();
12541 
12542   assert((CurContext->isDependentContext() || B.builtAll()) &&
12543          "omp for loop exprs were not built");
12544 
12545   setFunctionHasBranchProtectedScope();
12546   return OMPDistributeParallelForDirective::Create(
12547       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12548       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12549 }
12550 
12551 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
12552     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12553     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12554   if (!AStmt)
12555     return StmtError();
12556 
12557   auto *CS = cast<CapturedStmt>(AStmt);
12558   // 1.2.2 OpenMP Language Terminology
12559   // Structured block - An executable statement with a single entry at the
12560   // top and a single exit at the bottom.
12561   // The point of exit cannot be a branch out of the structured block.
12562   // longjmp() and throw() must not violate the entry/exit criteria.
12563   CS->getCapturedDecl()->setNothrow();
12564   for (int ThisCaptureLevel =
12565            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
12566        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12567     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12568     // 1.2.2 OpenMP Language Terminology
12569     // Structured block - An executable statement with a single entry at the
12570     // top and a single exit at the bottom.
12571     // The point of exit cannot be a branch out of the structured block.
12572     // longjmp() and throw() must not violate the entry/exit criteria.
12573     CS->getCapturedDecl()->setNothrow();
12574   }
12575 
12576   OMPLoopBasedDirective::HelperExprs B;
12577   // In presence of clause 'collapse' with number of loops, it will
12578   // define the nested loops number.
12579   unsigned NestedLoopCount = checkOpenMPLoop(
12580       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12581       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12582       VarsWithImplicitDSA, B);
12583   if (NestedLoopCount == 0)
12584     return StmtError();
12585 
12586   assert((CurContext->isDependentContext() || B.builtAll()) &&
12587          "omp for loop exprs were not built");
12588 
12589   if (!CurContext->isDependentContext()) {
12590     // Finalize the clauses that need pre-built expressions for CodeGen.
12591     for (OMPClause *C : Clauses) {
12592       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12593         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12594                                      B.NumIterations, *this, CurScope,
12595                                      DSAStack))
12596           return StmtError();
12597     }
12598   }
12599 
12600   if (checkSimdlenSafelenSpecified(*this, Clauses))
12601     return StmtError();
12602 
12603   setFunctionHasBranchProtectedScope();
12604   return OMPDistributeParallelForSimdDirective::Create(
12605       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12606 }
12607 
12608 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
12609     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12610     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12611   if (!AStmt)
12612     return StmtError();
12613 
12614   auto *CS = cast<CapturedStmt>(AStmt);
12615   // 1.2.2 OpenMP Language Terminology
12616   // Structured block - An executable statement with a single entry at the
12617   // top and a single exit at the bottom.
12618   // The point of exit cannot be a branch out of the structured block.
12619   // longjmp() and throw() must not violate the entry/exit criteria.
12620   CS->getCapturedDecl()->setNothrow();
12621   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
12622        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12623     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12624     // 1.2.2 OpenMP Language Terminology
12625     // Structured block - An executable statement with a single entry at the
12626     // top and a single exit at the bottom.
12627     // The point of exit cannot be a branch out of the structured block.
12628     // longjmp() and throw() must not violate the entry/exit criteria.
12629     CS->getCapturedDecl()->setNothrow();
12630   }
12631 
12632   OMPLoopBasedDirective::HelperExprs B;
12633   // In presence of clause 'collapse' with number of loops, it will
12634   // define the nested loops number.
12635   unsigned NestedLoopCount =
12636       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
12637                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12638                       *DSAStack, VarsWithImplicitDSA, B);
12639   if (NestedLoopCount == 0)
12640     return StmtError();
12641 
12642   assert((CurContext->isDependentContext() || B.builtAll()) &&
12643          "omp for loop exprs were not built");
12644 
12645   if (!CurContext->isDependentContext()) {
12646     // Finalize the clauses that need pre-built expressions for CodeGen.
12647     for (OMPClause *C : Clauses) {
12648       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12649         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12650                                      B.NumIterations, *this, CurScope,
12651                                      DSAStack))
12652           return StmtError();
12653     }
12654   }
12655 
12656   if (checkSimdlenSafelenSpecified(*this, Clauses))
12657     return StmtError();
12658 
12659   setFunctionHasBranchProtectedScope();
12660   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
12661                                             NestedLoopCount, Clauses, AStmt, B);
12662 }
12663 
12664 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
12665     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12666     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12667   if (!AStmt)
12668     return StmtError();
12669 
12670   auto *CS = cast<CapturedStmt>(AStmt);
12671   // 1.2.2 OpenMP Language Terminology
12672   // Structured block - An executable statement with a single entry at the
12673   // top and a single exit at the bottom.
12674   // The point of exit cannot be a branch out of the structured block.
12675   // longjmp() and throw() must not violate the entry/exit criteria.
12676   CS->getCapturedDecl()->setNothrow();
12677   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12678        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12679     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12680     // 1.2.2 OpenMP Language Terminology
12681     // Structured block - An executable statement with a single entry at the
12682     // top and a single exit at the bottom.
12683     // The point of exit cannot be a branch out of the structured block.
12684     // longjmp() and throw() must not violate the entry/exit criteria.
12685     CS->getCapturedDecl()->setNothrow();
12686   }
12687 
12688   OMPLoopBasedDirective::HelperExprs B;
12689   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12690   // define the nested loops number.
12691   unsigned NestedLoopCount = checkOpenMPLoop(
12692       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12693       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
12694       B);
12695   if (NestedLoopCount == 0)
12696     return StmtError();
12697 
12698   assert((CurContext->isDependentContext() || B.builtAll()) &&
12699          "omp target parallel for simd loop exprs were not built");
12700 
12701   if (!CurContext->isDependentContext()) {
12702     // Finalize the clauses that need pre-built expressions for CodeGen.
12703     for (OMPClause *C : Clauses) {
12704       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12705         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12706                                      B.NumIterations, *this, CurScope,
12707                                      DSAStack))
12708           return StmtError();
12709     }
12710   }
12711   if (checkSimdlenSafelenSpecified(*this, Clauses))
12712     return StmtError();
12713 
12714   setFunctionHasBranchProtectedScope();
12715   return OMPTargetParallelForSimdDirective::Create(
12716       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12717 }
12718 
12719 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12720     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12721     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12722   if (!AStmt)
12723     return StmtError();
12724 
12725   auto *CS = cast<CapturedStmt>(AStmt);
12726   // 1.2.2 OpenMP Language Terminology
12727   // Structured block - An executable statement with a single entry at the
12728   // top and a single exit at the bottom.
12729   // The point of exit cannot be a branch out of the structured block.
12730   // longjmp() and throw() must not violate the entry/exit criteria.
12731   CS->getCapturedDecl()->setNothrow();
12732   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12733        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12734     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12735     // 1.2.2 OpenMP Language Terminology
12736     // Structured block - An executable statement with a single entry at the
12737     // top and a single exit at the bottom.
12738     // The point of exit cannot be a branch out of the structured block.
12739     // longjmp() and throw() must not violate the entry/exit criteria.
12740     CS->getCapturedDecl()->setNothrow();
12741   }
12742 
12743   OMPLoopBasedDirective::HelperExprs B;
12744   // In presence of clause 'collapse' with number of loops, it will define the
12745   // nested loops number.
12746   unsigned NestedLoopCount =
12747       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12748                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12749                       VarsWithImplicitDSA, B);
12750   if (NestedLoopCount == 0)
12751     return StmtError();
12752 
12753   assert((CurContext->isDependentContext() || B.builtAll()) &&
12754          "omp target simd loop exprs were not built");
12755 
12756   if (!CurContext->isDependentContext()) {
12757     // Finalize the clauses that need pre-built expressions for CodeGen.
12758     for (OMPClause *C : Clauses) {
12759       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12760         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12761                                      B.NumIterations, *this, CurScope,
12762                                      DSAStack))
12763           return StmtError();
12764     }
12765   }
12766 
12767   if (checkSimdlenSafelenSpecified(*this, Clauses))
12768     return StmtError();
12769 
12770   setFunctionHasBranchProtectedScope();
12771   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12772                                         NestedLoopCount, Clauses, AStmt, B);
12773 }
12774 
12775 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12776     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12777     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12778   if (!AStmt)
12779     return StmtError();
12780 
12781   auto *CS = cast<CapturedStmt>(AStmt);
12782   // 1.2.2 OpenMP Language Terminology
12783   // Structured block - An executable statement with a single entry at the
12784   // top and a single exit at the bottom.
12785   // The point of exit cannot be a branch out of the structured block.
12786   // longjmp() and throw() must not violate the entry/exit criteria.
12787   CS->getCapturedDecl()->setNothrow();
12788   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12789        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12790     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12791     // 1.2.2 OpenMP Language Terminology
12792     // Structured block - An executable statement with a single entry at the
12793     // top and a single exit at the bottom.
12794     // The point of exit cannot be a branch out of the structured block.
12795     // longjmp() and throw() must not violate the entry/exit criteria.
12796     CS->getCapturedDecl()->setNothrow();
12797   }
12798 
12799   OMPLoopBasedDirective::HelperExprs B;
12800   // In presence of clause 'collapse' with number of loops, it will
12801   // define the nested loops number.
12802   unsigned NestedLoopCount =
12803       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12804                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12805                       *DSAStack, VarsWithImplicitDSA, B);
12806   if (NestedLoopCount == 0)
12807     return StmtError();
12808 
12809   assert((CurContext->isDependentContext() || B.builtAll()) &&
12810          "omp teams distribute loop exprs were not built");
12811 
12812   setFunctionHasBranchProtectedScope();
12813 
12814   DSAStack->setParentTeamsRegionLoc(StartLoc);
12815 
12816   return OMPTeamsDistributeDirective::Create(
12817       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12818 }
12819 
12820 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12821     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12822     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12823   if (!AStmt)
12824     return StmtError();
12825 
12826   auto *CS = cast<CapturedStmt>(AStmt);
12827   // 1.2.2 OpenMP Language Terminology
12828   // Structured block - An executable statement with a single entry at the
12829   // top and a single exit at the bottom.
12830   // The point of exit cannot be a branch out of the structured block.
12831   // longjmp() and throw() must not violate the entry/exit criteria.
12832   CS->getCapturedDecl()->setNothrow();
12833   for (int ThisCaptureLevel =
12834            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12835        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12836     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12837     // 1.2.2 OpenMP Language Terminology
12838     // Structured block - An executable statement with a single entry at the
12839     // top and a single exit at the bottom.
12840     // The point of exit cannot be a branch out of the structured block.
12841     // longjmp() and throw() must not violate the entry/exit criteria.
12842     CS->getCapturedDecl()->setNothrow();
12843   }
12844 
12845   OMPLoopBasedDirective::HelperExprs B;
12846   // In presence of clause 'collapse' with number of loops, it will
12847   // define the nested loops number.
12848   unsigned NestedLoopCount = checkOpenMPLoop(
12849       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12850       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12851       VarsWithImplicitDSA, B);
12852 
12853   if (NestedLoopCount == 0)
12854     return StmtError();
12855 
12856   assert((CurContext->isDependentContext() || B.builtAll()) &&
12857          "omp teams distribute simd loop exprs were not built");
12858 
12859   if (!CurContext->isDependentContext()) {
12860     // Finalize the clauses that need pre-built expressions for CodeGen.
12861     for (OMPClause *C : Clauses) {
12862       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12863         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12864                                      B.NumIterations, *this, CurScope,
12865                                      DSAStack))
12866           return StmtError();
12867     }
12868   }
12869 
12870   if (checkSimdlenSafelenSpecified(*this, Clauses))
12871     return StmtError();
12872 
12873   setFunctionHasBranchProtectedScope();
12874 
12875   DSAStack->setParentTeamsRegionLoc(StartLoc);
12876 
12877   return OMPTeamsDistributeSimdDirective::Create(
12878       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12879 }
12880 
12881 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12882     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12883     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12884   if (!AStmt)
12885     return StmtError();
12886 
12887   auto *CS = cast<CapturedStmt>(AStmt);
12888   // 1.2.2 OpenMP Language Terminology
12889   // Structured block - An executable statement with a single entry at the
12890   // top and a single exit at the bottom.
12891   // The point of exit cannot be a branch out of the structured block.
12892   // longjmp() and throw() must not violate the entry/exit criteria.
12893   CS->getCapturedDecl()->setNothrow();
12894 
12895   for (int ThisCaptureLevel =
12896            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12897        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12898     CS = cast<CapturedStmt>(CS->getCapturedStmt());
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 
12907   OMPLoopBasedDirective::HelperExprs B;
12908   // In presence of clause 'collapse' with number of loops, it will
12909   // define the nested loops number.
12910   unsigned NestedLoopCount = checkOpenMPLoop(
12911       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12912       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12913       VarsWithImplicitDSA, B);
12914 
12915   if (NestedLoopCount == 0)
12916     return StmtError();
12917 
12918   assert((CurContext->isDependentContext() || B.builtAll()) &&
12919          "omp for loop exprs were not built");
12920 
12921   if (!CurContext->isDependentContext()) {
12922     // Finalize the clauses that need pre-built expressions for CodeGen.
12923     for (OMPClause *C : Clauses) {
12924       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12925         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12926                                      B.NumIterations, *this, CurScope,
12927                                      DSAStack))
12928           return StmtError();
12929     }
12930   }
12931 
12932   if (checkSimdlenSafelenSpecified(*this, Clauses))
12933     return StmtError();
12934 
12935   setFunctionHasBranchProtectedScope();
12936 
12937   DSAStack->setParentTeamsRegionLoc(StartLoc);
12938 
12939   return OMPTeamsDistributeParallelForSimdDirective::Create(
12940       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12941 }
12942 
12943 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12944     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12945     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12946   if (!AStmt)
12947     return StmtError();
12948 
12949   auto *CS = cast<CapturedStmt>(AStmt);
12950   // 1.2.2 OpenMP Language Terminology
12951   // Structured block - An executable statement with a single entry at the
12952   // top and a single exit at the bottom.
12953   // The point of exit cannot be a branch out of the structured block.
12954   // longjmp() and throw() must not violate the entry/exit criteria.
12955   CS->getCapturedDecl()->setNothrow();
12956 
12957   for (int ThisCaptureLevel =
12958            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12959        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12960     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12961     // 1.2.2 OpenMP Language Terminology
12962     // Structured block - An executable statement with a single entry at the
12963     // top and a single exit at the bottom.
12964     // The point of exit cannot be a branch out of the structured block.
12965     // longjmp() and throw() must not violate the entry/exit criteria.
12966     CS->getCapturedDecl()->setNothrow();
12967   }
12968 
12969   OMPLoopBasedDirective::HelperExprs B;
12970   // In presence of clause 'collapse' with number of loops, it will
12971   // define the nested loops number.
12972   unsigned NestedLoopCount = checkOpenMPLoop(
12973       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12974       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12975       VarsWithImplicitDSA, B);
12976 
12977   if (NestedLoopCount == 0)
12978     return StmtError();
12979 
12980   assert((CurContext->isDependentContext() || B.builtAll()) &&
12981          "omp for loop exprs were not built");
12982 
12983   setFunctionHasBranchProtectedScope();
12984 
12985   DSAStack->setParentTeamsRegionLoc(StartLoc);
12986 
12987   return OMPTeamsDistributeParallelForDirective::Create(
12988       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12989       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12990 }
12991 
12992 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12993                                                  Stmt *AStmt,
12994                                                  SourceLocation StartLoc,
12995                                                  SourceLocation EndLoc) {
12996   if (!AStmt)
12997     return StmtError();
12998 
12999   auto *CS = cast<CapturedStmt>(AStmt);
13000   // 1.2.2 OpenMP Language Terminology
13001   // Structured block - An executable statement with a single entry at the
13002   // top and a single exit at the bottom.
13003   // The point of exit cannot be a branch out of the structured block.
13004   // longjmp() and throw() must not violate the entry/exit criteria.
13005   CS->getCapturedDecl()->setNothrow();
13006 
13007   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
13008        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13009     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13010     // 1.2.2 OpenMP Language Terminology
13011     // Structured block - An executable statement with a single entry at the
13012     // top and a single exit at the bottom.
13013     // The point of exit cannot be a branch out of the structured block.
13014     // longjmp() and throw() must not violate the entry/exit criteria.
13015     CS->getCapturedDecl()->setNothrow();
13016   }
13017   setFunctionHasBranchProtectedScope();
13018 
13019   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
13020                                          AStmt);
13021 }
13022 
13023 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
13024     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13025     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13026   if (!AStmt)
13027     return StmtError();
13028 
13029   auto *CS = cast<CapturedStmt>(AStmt);
13030   // 1.2.2 OpenMP Language Terminology
13031   // Structured block - An executable statement with a single entry at the
13032   // top and a single exit at the bottom.
13033   // The point of exit cannot be a branch out of the structured block.
13034   // longjmp() and throw() must not violate the entry/exit criteria.
13035   CS->getCapturedDecl()->setNothrow();
13036   for (int ThisCaptureLevel =
13037            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
13038        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13039     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13040     // 1.2.2 OpenMP Language Terminology
13041     // Structured block - An executable statement with a single entry at the
13042     // top and a single exit at the bottom.
13043     // The point of exit cannot be a branch out of the structured block.
13044     // longjmp() and throw() must not violate the entry/exit criteria.
13045     CS->getCapturedDecl()->setNothrow();
13046   }
13047 
13048   OMPLoopBasedDirective::HelperExprs B;
13049   // In presence of clause 'collapse' with number of loops, it will
13050   // define the nested loops number.
13051   unsigned NestedLoopCount = checkOpenMPLoop(
13052       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
13053       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13054       VarsWithImplicitDSA, B);
13055   if (NestedLoopCount == 0)
13056     return StmtError();
13057 
13058   assert((CurContext->isDependentContext() || B.builtAll()) &&
13059          "omp target teams distribute loop exprs were not built");
13060 
13061   setFunctionHasBranchProtectedScope();
13062   return OMPTargetTeamsDistributeDirective::Create(
13063       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13064 }
13065 
13066 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
13067     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13068     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13069   if (!AStmt)
13070     return StmtError();
13071 
13072   auto *CS = cast<CapturedStmt>(AStmt);
13073   // 1.2.2 OpenMP Language Terminology
13074   // Structured block - An executable statement with a single entry at the
13075   // top and a single exit at the bottom.
13076   // The point of exit cannot be a branch out of the structured block.
13077   // longjmp() and throw() must not violate the entry/exit criteria.
13078   CS->getCapturedDecl()->setNothrow();
13079   for (int ThisCaptureLevel =
13080            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
13081        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13082     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13083     // 1.2.2 OpenMP Language Terminology
13084     // Structured block - An executable statement with a single entry at the
13085     // top and a single exit at the bottom.
13086     // The point of exit cannot be a branch out of the structured block.
13087     // longjmp() and throw() must not violate the entry/exit criteria.
13088     CS->getCapturedDecl()->setNothrow();
13089   }
13090 
13091   OMPLoopBasedDirective::HelperExprs B;
13092   // In presence of clause 'collapse' with number of loops, it will
13093   // define the nested loops number.
13094   unsigned NestedLoopCount = checkOpenMPLoop(
13095       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
13096       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13097       VarsWithImplicitDSA, B);
13098   if (NestedLoopCount == 0)
13099     return StmtError();
13100 
13101   assert((CurContext->isDependentContext() || B.builtAll()) &&
13102          "omp target teams distribute parallel for loop exprs were not built");
13103 
13104   if (!CurContext->isDependentContext()) {
13105     // Finalize the clauses that need pre-built expressions for CodeGen.
13106     for (OMPClause *C : Clauses) {
13107       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13108         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13109                                      B.NumIterations, *this, CurScope,
13110                                      DSAStack))
13111           return StmtError();
13112     }
13113   }
13114 
13115   setFunctionHasBranchProtectedScope();
13116   return OMPTargetTeamsDistributeParallelForDirective::Create(
13117       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
13118       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
13119 }
13120 
13121 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
13122     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13123     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13124   if (!AStmt)
13125     return StmtError();
13126 
13127   auto *CS = cast<CapturedStmt>(AStmt);
13128   // 1.2.2 OpenMP Language Terminology
13129   // Structured block - An executable statement with a single entry at the
13130   // top and a single exit at the bottom.
13131   // The point of exit cannot be a branch out of the structured block.
13132   // longjmp() and throw() must not violate the entry/exit criteria.
13133   CS->getCapturedDecl()->setNothrow();
13134   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
13135            OMPD_target_teams_distribute_parallel_for_simd);
13136        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13137     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13138     // 1.2.2 OpenMP Language Terminology
13139     // Structured block - An executable statement with a single entry at the
13140     // top and a single exit at the bottom.
13141     // The point of exit cannot be a branch out of the structured block.
13142     // longjmp() and throw() must not violate the entry/exit criteria.
13143     CS->getCapturedDecl()->setNothrow();
13144   }
13145 
13146   OMPLoopBasedDirective::HelperExprs B;
13147   // In presence of clause 'collapse' with number of loops, it will
13148   // define the nested loops number.
13149   unsigned NestedLoopCount =
13150       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
13151                       getCollapseNumberExpr(Clauses),
13152                       nullptr /*ordered not a clause on distribute*/, CS, *this,
13153                       *DSAStack, VarsWithImplicitDSA, B);
13154   if (NestedLoopCount == 0)
13155     return StmtError();
13156 
13157   assert((CurContext->isDependentContext() || B.builtAll()) &&
13158          "omp target teams distribute parallel for simd loop exprs were not "
13159          "built");
13160 
13161   if (!CurContext->isDependentContext()) {
13162     // Finalize the clauses that need pre-built expressions for CodeGen.
13163     for (OMPClause *C : Clauses) {
13164       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13165         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13166                                      B.NumIterations, *this, CurScope,
13167                                      DSAStack))
13168           return StmtError();
13169     }
13170   }
13171 
13172   if (checkSimdlenSafelenSpecified(*this, Clauses))
13173     return StmtError();
13174 
13175   setFunctionHasBranchProtectedScope();
13176   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
13177       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13178 }
13179 
13180 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
13181     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
13182     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
13183   if (!AStmt)
13184     return StmtError();
13185 
13186   auto *CS = cast<CapturedStmt>(AStmt);
13187   // 1.2.2 OpenMP Language Terminology
13188   // Structured block - An executable statement with a single entry at the
13189   // top and a single exit at the bottom.
13190   // The point of exit cannot be a branch out of the structured block.
13191   // longjmp() and throw() must not violate the entry/exit criteria.
13192   CS->getCapturedDecl()->setNothrow();
13193   for (int ThisCaptureLevel =
13194            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
13195        ThisCaptureLevel > 1; --ThisCaptureLevel) {
13196     CS = cast<CapturedStmt>(CS->getCapturedStmt());
13197     // 1.2.2 OpenMP Language Terminology
13198     // Structured block - An executable statement with a single entry at the
13199     // top and a single exit at the bottom.
13200     // The point of exit cannot be a branch out of the structured block.
13201     // longjmp() and throw() must not violate the entry/exit criteria.
13202     CS->getCapturedDecl()->setNothrow();
13203   }
13204 
13205   OMPLoopBasedDirective::HelperExprs B;
13206   // In presence of clause 'collapse' with number of loops, it will
13207   // define the nested loops number.
13208   unsigned NestedLoopCount = checkOpenMPLoop(
13209       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
13210       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
13211       VarsWithImplicitDSA, B);
13212   if (NestedLoopCount == 0)
13213     return StmtError();
13214 
13215   assert((CurContext->isDependentContext() || B.builtAll()) &&
13216          "omp target teams distribute simd loop exprs were not built");
13217 
13218   if (!CurContext->isDependentContext()) {
13219     // Finalize the clauses that need pre-built expressions for CodeGen.
13220     for (OMPClause *C : Clauses) {
13221       if (auto *LC = dyn_cast<OMPLinearClause>(C))
13222         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
13223                                      B.NumIterations, *this, CurScope,
13224                                      DSAStack))
13225           return StmtError();
13226     }
13227   }
13228 
13229   if (checkSimdlenSafelenSpecified(*this, Clauses))
13230     return StmtError();
13231 
13232   setFunctionHasBranchProtectedScope();
13233   return OMPTargetTeamsDistributeSimdDirective::Create(
13234       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
13235 }
13236 
13237 bool Sema::checkTransformableLoopNest(
13238     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
13239     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
13240     Stmt *&Body,
13241     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
13242         &OriginalInits) {
13243   OriginalInits.emplace_back();
13244   bool Result = OMPLoopBasedDirective::doForAllLoops(
13245       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
13246       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
13247                                                         Stmt *CurStmt) {
13248         VarsWithInheritedDSAType TmpDSA;
13249         unsigned SingleNumLoops =
13250             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
13251                             TmpDSA, LoopHelpers[Cnt]);
13252         if (SingleNumLoops == 0)
13253           return true;
13254         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
13255         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
13256           OriginalInits.back().push_back(For->getInit());
13257           Body = For->getBody();
13258         } else {
13259           assert(isa<CXXForRangeStmt>(CurStmt) &&
13260                  "Expected canonical for or range-based for loops.");
13261           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
13262           OriginalInits.back().push_back(CXXFor->getBeginStmt());
13263           Body = CXXFor->getBody();
13264         }
13265         OriginalInits.emplace_back();
13266         return false;
13267       },
13268       [&OriginalInits](OMPLoopBasedDirective *Transform) {
13269         Stmt *DependentPreInits;
13270         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
13271           DependentPreInits = Dir->getPreInits();
13272         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
13273           DependentPreInits = Dir->getPreInits();
13274         else
13275           llvm_unreachable("Unhandled loop transformation");
13276         if (!DependentPreInits)
13277           return;
13278         for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
13279           OriginalInits.back().push_back(C);
13280       });
13281   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
13282   OriginalInits.pop_back();
13283   return Result;
13284 }
13285 
13286 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
13287                                           Stmt *AStmt, SourceLocation StartLoc,
13288                                           SourceLocation EndLoc) {
13289   auto SizesClauses =
13290       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
13291   if (SizesClauses.empty()) {
13292     // A missing 'sizes' clause is already reported by the parser.
13293     return StmtError();
13294   }
13295   const OMPSizesClause *SizesClause = *SizesClauses.begin();
13296   unsigned NumLoops = SizesClause->getNumSizes();
13297 
13298   // Empty statement should only be possible if there already was an error.
13299   if (!AStmt)
13300     return StmtError();
13301 
13302   // Verify and diagnose loop nest.
13303   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
13304   Stmt *Body = nullptr;
13305   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
13306       OriginalInits;
13307   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
13308                                   OriginalInits))
13309     return StmtError();
13310 
13311   // Delay tiling to when template is completely instantiated.
13312   if (CurContext->isDependentContext())
13313     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
13314                                     NumLoops, AStmt, nullptr, nullptr);
13315 
13316   SmallVector<Decl *, 4> PreInits;
13317 
13318   // Create iteration variables for the generated loops.
13319   SmallVector<VarDecl *, 4> FloorIndVars;
13320   SmallVector<VarDecl *, 4> TileIndVars;
13321   FloorIndVars.resize(NumLoops);
13322   TileIndVars.resize(NumLoops);
13323   for (unsigned I = 0; I < NumLoops; ++I) {
13324     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
13325 
13326     assert(LoopHelper.Counters.size() == 1 &&
13327            "Expect single-dimensional loop iteration space");
13328     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
13329     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
13330     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
13331     QualType CntTy = IterVarRef->getType();
13332 
13333     // Iteration variable for the floor (i.e. outer) loop.
13334     {
13335       std::string FloorCntName =
13336           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
13337       VarDecl *FloorCntDecl =
13338           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
13339       FloorIndVars[I] = FloorCntDecl;
13340     }
13341 
13342     // Iteration variable for the tile (i.e. inner) loop.
13343     {
13344       std::string TileCntName =
13345           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
13346 
13347       // Reuse the iteration variable created by checkOpenMPLoop. It is also
13348       // used by the expressions to derive the original iteration variable's
13349       // value from the logical iteration number.
13350       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
13351       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
13352       TileIndVars[I] = TileCntDecl;
13353     }
13354     for (auto &P : OriginalInits[I]) {
13355       if (auto *D = P.dyn_cast<Decl *>())
13356         PreInits.push_back(D);
13357       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
13358         PreInits.append(PI->decl_begin(), PI->decl_end());
13359     }
13360     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
13361       PreInits.append(PI->decl_begin(), PI->decl_end());
13362     // Gather declarations for the data members used as counters.
13363     for (Expr *CounterRef : LoopHelper.Counters) {
13364       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
13365       if (isa<OMPCapturedExprDecl>(CounterDecl))
13366         PreInits.push_back(CounterDecl);
13367     }
13368   }
13369 
13370   // Once the original iteration values are set, append the innermost body.
13371   Stmt *Inner = Body;
13372 
13373   // Create tile loops from the inside to the outside.
13374   for (int I = NumLoops - 1; I >= 0; --I) {
13375     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
13376     Expr *NumIterations = LoopHelper.NumIterations;
13377     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
13378     QualType CntTy = OrigCntVar->getType();
13379     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
13380     Scope *CurScope = getCurScope();
13381 
13382     // Commonly used variables.
13383     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
13384                                            OrigCntVar->getExprLoc());
13385     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
13386                                             OrigCntVar->getExprLoc());
13387 
13388     // For init-statement: auto .tile.iv = .floor.iv
13389     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
13390                          /*DirectInit=*/false);
13391     Decl *CounterDecl = TileIndVars[I];
13392     StmtResult InitStmt = new (Context)
13393         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
13394                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13395     if (!InitStmt.isUsable())
13396       return StmtError();
13397 
13398     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
13399     // NumIterations)
13400     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13401                                       BO_Add, FloorIV, DimTileSize);
13402     if (!EndOfTile.isUsable())
13403       return StmtError();
13404     ExprResult IsPartialTile =
13405         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
13406                    NumIterations, EndOfTile.get());
13407     if (!IsPartialTile.isUsable())
13408       return StmtError();
13409     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
13410         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
13411         IsPartialTile.get(), NumIterations, EndOfTile.get());
13412     if (!MinTileAndIterSpace.isUsable())
13413       return StmtError();
13414     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13415                                      BO_LT, TileIV, MinTileAndIterSpace.get());
13416     if (!CondExpr.isUsable())
13417       return StmtError();
13418 
13419     // For incr-statement: ++.tile.iv
13420     ExprResult IncrStmt =
13421         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
13422     if (!IncrStmt.isUsable())
13423       return StmtError();
13424 
13425     // Statements to set the original iteration variable's value from the
13426     // logical iteration number.
13427     // Generated for loop is:
13428     // Original_for_init;
13429     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
13430     // NumIterations); ++.tile.iv) {
13431     //   Original_Body;
13432     //   Original_counter_update;
13433     // }
13434     // FIXME: If the innermost body is an loop itself, inserting these
13435     // statements stops it being recognized  as a perfectly nested loop (e.g.
13436     // for applying tiling again). If this is the case, sink the expressions
13437     // further into the inner loop.
13438     SmallVector<Stmt *, 4> BodyParts;
13439     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13440     BodyParts.push_back(Inner);
13441     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
13442                                  Inner->getEndLoc());
13443     Inner = new (Context)
13444         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13445                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13446                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13447   }
13448 
13449   // Create floor loops from the inside to the outside.
13450   for (int I = NumLoops - 1; I >= 0; --I) {
13451     auto &LoopHelper = LoopHelpers[I];
13452     Expr *NumIterations = LoopHelper.NumIterations;
13453     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
13454     QualType CntTy = OrigCntVar->getType();
13455     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
13456     Scope *CurScope = getCurScope();
13457 
13458     // Commonly used variables.
13459     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
13460                                             OrigCntVar->getExprLoc());
13461 
13462     // For init-statement: auto .floor.iv = 0
13463     AddInitializerToDecl(
13464         FloorIndVars[I],
13465         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13466         /*DirectInit=*/false);
13467     Decl *CounterDecl = FloorIndVars[I];
13468     StmtResult InitStmt = new (Context)
13469         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
13470                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13471     if (!InitStmt.isUsable())
13472       return StmtError();
13473 
13474     // For cond-expression: .floor.iv < NumIterations
13475     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13476                                      BO_LT, FloorIV, NumIterations);
13477     if (!CondExpr.isUsable())
13478       return StmtError();
13479 
13480     // For incr-statement: .floor.iv += DimTileSize
13481     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
13482                                      BO_AddAssign, FloorIV, DimTileSize);
13483     if (!IncrStmt.isUsable())
13484       return StmtError();
13485 
13486     Inner = new (Context)
13487         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13488                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13489                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13490   }
13491 
13492   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
13493                                   AStmt, Inner,
13494                                   buildPreInits(Context, PreInits));
13495 }
13496 
13497 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
13498                                             Stmt *AStmt,
13499                                             SourceLocation StartLoc,
13500                                             SourceLocation EndLoc) {
13501   // Empty statement should only be possible if there already was an error.
13502   if (!AStmt)
13503     return StmtError();
13504 
13505   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
13506     return StmtError();
13507 
13508   const OMPFullClause *FullClause =
13509       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
13510   const OMPPartialClause *PartialClause =
13511       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
13512   assert(!(FullClause && PartialClause) &&
13513          "mutual exclusivity must have been checked before");
13514 
13515   constexpr unsigned NumLoops = 1;
13516   Stmt *Body = nullptr;
13517   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
13518       NumLoops);
13519   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
13520       OriginalInits;
13521   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
13522                                   Body, OriginalInits))
13523     return StmtError();
13524 
13525   unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
13526 
13527   // Delay unrolling to when template is completely instantiated.
13528   if (CurContext->isDependentContext())
13529     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13530                                       NumGeneratedLoops, nullptr, nullptr);
13531 
13532   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
13533 
13534   if (FullClause) {
13535     if (!VerifyPositiveIntegerConstantInClause(
13536              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
13537              /*SuppressExprDiags=*/true)
13538              .isUsable()) {
13539       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
13540       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
13541           << "#pragma omp unroll full";
13542       return StmtError();
13543     }
13544   }
13545 
13546   // The generated loop may only be passed to other loop-associated directive
13547   // when a partial clause is specified. Without the requirement it is
13548   // sufficient to generate loop unroll metadata at code-generation.
13549   if (NumGeneratedLoops == 0)
13550     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13551                                       NumGeneratedLoops, nullptr, nullptr);
13552 
13553   // Otherwise, we need to provide a de-sugared/transformed AST that can be
13554   // associated with another loop directive.
13555   //
13556   // The canonical loop analysis return by checkTransformableLoopNest assumes
13557   // the following structure to be the same loop without transformations or
13558   // directives applied: \code OriginalInits; LoopHelper.PreInits;
13559   // LoopHelper.Counters;
13560   // for (; IV < LoopHelper.NumIterations; ++IV) {
13561   //   LoopHelper.Updates;
13562   //   Body;
13563   // }
13564   // \endcode
13565   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
13566   // and referenced by LoopHelper.IterationVarRef.
13567   //
13568   // The unrolling directive transforms this into the following loop:
13569   // \code
13570   // OriginalInits;         \
13571   // LoopHelper.PreInits;    > NewPreInits
13572   // LoopHelper.Counters;   /
13573   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
13574   //   #pragma clang loop unroll_count(Factor)
13575   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
13576   //   {
13577   //     LoopHelper.Updates;
13578   //     Body;
13579   //   }
13580   // }
13581   // \endcode
13582   // where UIV is a new logical iteration counter. IV must be the same VarDecl
13583   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
13584   // references it. If the partially unrolled loop is associated with another
13585   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
13586   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
13587   // OpenMP canonical loop. The inner loop is not an associable canonical loop
13588   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
13589   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
13590   // property of the OMPLoopBasedDirective instead of statements in
13591   // CompoundStatement. This is to allow the loop to become a non-outermost loop
13592   // of a canonical loop nest where these PreInits are emitted before the
13593   // outermost directive.
13594 
13595   // Determine the PreInit declarations.
13596   SmallVector<Decl *, 4> PreInits;
13597   assert(OriginalInits.size() == 1 &&
13598          "Expecting a single-dimensional loop iteration space");
13599   for (auto &P : OriginalInits[0]) {
13600     if (auto *D = P.dyn_cast<Decl *>())
13601       PreInits.push_back(D);
13602     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
13603       PreInits.append(PI->decl_begin(), PI->decl_end());
13604   }
13605   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
13606     PreInits.append(PI->decl_begin(), PI->decl_end());
13607   // Gather declarations for the data members used as counters.
13608   for (Expr *CounterRef : LoopHelper.Counters) {
13609     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
13610     if (isa<OMPCapturedExprDecl>(CounterDecl))
13611       PreInits.push_back(CounterDecl);
13612   }
13613 
13614   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
13615   QualType IVTy = IterationVarRef->getType();
13616   assert(LoopHelper.Counters.size() == 1 &&
13617          "Expecting a single-dimensional loop iteration space");
13618   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
13619 
13620   // Determine the unroll factor.
13621   uint64_t Factor;
13622   SourceLocation FactorLoc;
13623   if (Expr *FactorVal = PartialClause->getFactor()) {
13624     Factor =
13625         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
13626     FactorLoc = FactorVal->getExprLoc();
13627   } else {
13628     // TODO: Use a better profitability model.
13629     Factor = 2;
13630   }
13631   assert(Factor > 0 && "Expected positive unroll factor");
13632   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
13633     return IntegerLiteral::Create(
13634         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
13635         FactorLoc);
13636   };
13637 
13638   // Iteration variable SourceLocations.
13639   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
13640   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
13641   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
13642 
13643   // Internal variable names.
13644   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
13645   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
13646   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
13647   std::string InnerTripCountName =
13648       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
13649 
13650   // Create the iteration variable for the unrolled loop.
13651   VarDecl *OuterIVDecl =
13652       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
13653   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
13654     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
13655   };
13656 
13657   // Iteration variable for the inner loop: Reuse the iteration variable created
13658   // by checkOpenMPLoop.
13659   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
13660   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
13661   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
13662     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
13663   };
13664 
13665   // Make a copy of the NumIterations expression for each use: By the AST
13666   // constraints, every expression object in a DeclContext must be unique.
13667   CaptureVars CopyTransformer(*this);
13668   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
13669     return AssertSuccess(
13670         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
13671   };
13672 
13673   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
13674   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
13675   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
13676   StmtResult InnerInit = new (Context)
13677       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13678   if (!InnerInit.isUsable())
13679     return StmtError();
13680 
13681   // Inner For cond-expression:
13682   // \code
13683   //   .unroll_inner.iv < .unrolled.iv + Factor &&
13684   //   .unroll_inner.iv < NumIterations
13685   // \endcode
13686   // This conjunction of two conditions allows ScalarEvolution to derive the
13687   // maximum trip count of the inner loop.
13688   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13689                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
13690   if (!EndOfTile.isUsable())
13691     return StmtError();
13692   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13693                                      BO_LE, MakeInnerRef(), EndOfTile.get());
13694   if (!InnerCond1.isUsable())
13695     return StmtError();
13696   ExprResult InnerCond2 =
13697       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
13698                  MakeNumIterations());
13699   if (!InnerCond2.isUsable())
13700     return StmtError();
13701   ExprResult InnerCond =
13702       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
13703                  InnerCond1.get(), InnerCond2.get());
13704   if (!InnerCond.isUsable())
13705     return StmtError();
13706 
13707   // Inner For incr-statement: ++.unroll_inner.iv
13708   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
13709                                       UO_PreInc, MakeInnerRef());
13710   if (!InnerIncr.isUsable())
13711     return StmtError();
13712 
13713   // Inner For statement.
13714   SmallVector<Stmt *> InnerBodyStmts;
13715   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13716   InnerBodyStmts.push_back(Body);
13717   CompoundStmt *InnerBody = CompoundStmt::Create(
13718       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
13719   ForStmt *InnerFor = new (Context)
13720       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
13721               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
13722               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13723 
13724   // Unroll metadata for the inner loop.
13725   // This needs to take into account the remainder portion of the unrolled loop,
13726   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
13727   // supports multiple loop exits. Instead, unroll using a factor equivalent to
13728   // the maximum trip count, which will also generate a remainder loop. Just
13729   // `unroll(enable)` (which could have been useful if the user has not
13730   // specified a concrete factor; even though the outer loop cannot be
13731   // influenced anymore, would avoid more code bloat than necessary) will refuse
13732   // the loop because "Won't unroll; remainder loop could not be generated when
13733   // assuming runtime trip count". Even if it did work, it must not choose a
13734   // larger unroll factor than the maximum loop length, or it would always just
13735   // execute the remainder loop.
13736   LoopHintAttr *UnrollHintAttr =
13737       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
13738                                    LoopHintAttr::Numeric, MakeFactorExpr());
13739   AttributedStmt *InnerUnrolled =
13740       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
13741 
13742   // Outer For init-statement: auto .unrolled.iv = 0
13743   AddInitializerToDecl(
13744       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13745       /*DirectInit=*/false);
13746   StmtResult OuterInit = new (Context)
13747       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13748   if (!OuterInit.isUsable())
13749     return StmtError();
13750 
13751   // Outer For cond-expression: .unrolled.iv < NumIterations
13752   ExprResult OuterConde =
13753       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
13754                  MakeNumIterations());
13755   if (!OuterConde.isUsable())
13756     return StmtError();
13757 
13758   // Outer For incr-statement: .unrolled.iv += Factor
13759   ExprResult OuterIncr =
13760       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
13761                  MakeOuterRef(), MakeFactorExpr());
13762   if (!OuterIncr.isUsable())
13763     return StmtError();
13764 
13765   // Outer For statement.
13766   ForStmt *OuterFor = new (Context)
13767       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
13768               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
13769               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13770 
13771   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13772                                     NumGeneratedLoops, OuterFor,
13773                                     buildPreInits(Context, PreInits));
13774 }
13775 
13776 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
13777                                              SourceLocation StartLoc,
13778                                              SourceLocation LParenLoc,
13779                                              SourceLocation EndLoc) {
13780   OMPClause *Res = nullptr;
13781   switch (Kind) {
13782   case OMPC_final:
13783     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
13784     break;
13785   case OMPC_num_threads:
13786     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
13787     break;
13788   case OMPC_safelen:
13789     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
13790     break;
13791   case OMPC_simdlen:
13792     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
13793     break;
13794   case OMPC_allocator:
13795     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
13796     break;
13797   case OMPC_collapse:
13798     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
13799     break;
13800   case OMPC_ordered:
13801     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
13802     break;
13803   case OMPC_num_teams:
13804     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
13805     break;
13806   case OMPC_thread_limit:
13807     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
13808     break;
13809   case OMPC_priority:
13810     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
13811     break;
13812   case OMPC_grainsize:
13813     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
13814     break;
13815   case OMPC_num_tasks:
13816     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
13817     break;
13818   case OMPC_hint:
13819     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
13820     break;
13821   case OMPC_depobj:
13822     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
13823     break;
13824   case OMPC_detach:
13825     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
13826     break;
13827   case OMPC_novariants:
13828     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
13829     break;
13830   case OMPC_nocontext:
13831     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
13832     break;
13833   case OMPC_filter:
13834     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
13835     break;
13836   case OMPC_partial:
13837     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
13838     break;
13839   case OMPC_align:
13840     Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
13841     break;
13842   case OMPC_device:
13843   case OMPC_if:
13844   case OMPC_default:
13845   case OMPC_proc_bind:
13846   case OMPC_schedule:
13847   case OMPC_private:
13848   case OMPC_firstprivate:
13849   case OMPC_lastprivate:
13850   case OMPC_shared:
13851   case OMPC_reduction:
13852   case OMPC_task_reduction:
13853   case OMPC_in_reduction:
13854   case OMPC_linear:
13855   case OMPC_aligned:
13856   case OMPC_copyin:
13857   case OMPC_copyprivate:
13858   case OMPC_nowait:
13859   case OMPC_untied:
13860   case OMPC_mergeable:
13861   case OMPC_threadprivate:
13862   case OMPC_sizes:
13863   case OMPC_allocate:
13864   case OMPC_flush:
13865   case OMPC_read:
13866   case OMPC_write:
13867   case OMPC_update:
13868   case OMPC_capture:
13869   case OMPC_compare:
13870   case OMPC_seq_cst:
13871   case OMPC_acq_rel:
13872   case OMPC_acquire:
13873   case OMPC_release:
13874   case OMPC_relaxed:
13875   case OMPC_depend:
13876   case OMPC_threads:
13877   case OMPC_simd:
13878   case OMPC_map:
13879   case OMPC_nogroup:
13880   case OMPC_dist_schedule:
13881   case OMPC_defaultmap:
13882   case OMPC_unknown:
13883   case OMPC_uniform:
13884   case OMPC_to:
13885   case OMPC_from:
13886   case OMPC_use_device_ptr:
13887   case OMPC_use_device_addr:
13888   case OMPC_is_device_ptr:
13889   case OMPC_unified_address:
13890   case OMPC_unified_shared_memory:
13891   case OMPC_reverse_offload:
13892   case OMPC_dynamic_allocators:
13893   case OMPC_atomic_default_mem_order:
13894   case OMPC_device_type:
13895   case OMPC_match:
13896   case OMPC_nontemporal:
13897   case OMPC_order:
13898   case OMPC_destroy:
13899   case OMPC_inclusive:
13900   case OMPC_exclusive:
13901   case OMPC_uses_allocators:
13902   case OMPC_affinity:
13903   case OMPC_when:
13904   case OMPC_bind:
13905   default:
13906     llvm_unreachable("Clause is not allowed.");
13907   }
13908   return Res;
13909 }
13910 
13911 // An OpenMP directive such as 'target parallel' has two captured regions:
13912 // for the 'target' and 'parallel' respectively.  This function returns
13913 // the region in which to capture expressions associated with a clause.
13914 // A return value of OMPD_unknown signifies that the expression should not
13915 // be captured.
13916 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
13917     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
13918     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
13919   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13920   switch (CKind) {
13921   case OMPC_if:
13922     switch (DKind) {
13923     case OMPD_target_parallel_for_simd:
13924       if (OpenMPVersion >= 50 &&
13925           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13926         CaptureRegion = OMPD_parallel;
13927         break;
13928       }
13929       LLVM_FALLTHROUGH;
13930     case OMPD_target_parallel:
13931     case OMPD_target_parallel_for:
13932       // If this clause applies to the nested 'parallel' region, capture within
13933       // the 'target' region, otherwise do not capture.
13934       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13935         CaptureRegion = OMPD_target;
13936       break;
13937     case OMPD_target_teams_distribute_parallel_for_simd:
13938       if (OpenMPVersion >= 50 &&
13939           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13940         CaptureRegion = OMPD_parallel;
13941         break;
13942       }
13943       LLVM_FALLTHROUGH;
13944     case OMPD_target_teams_distribute_parallel_for:
13945       // If this clause applies to the nested 'parallel' region, capture within
13946       // the 'teams' region, otherwise do not capture.
13947       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13948         CaptureRegion = OMPD_teams;
13949       break;
13950     case OMPD_teams_distribute_parallel_for_simd:
13951       if (OpenMPVersion >= 50 &&
13952           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13953         CaptureRegion = OMPD_parallel;
13954         break;
13955       }
13956       LLVM_FALLTHROUGH;
13957     case OMPD_teams_distribute_parallel_for:
13958       CaptureRegion = OMPD_teams;
13959       break;
13960     case OMPD_target_update:
13961     case OMPD_target_enter_data:
13962     case OMPD_target_exit_data:
13963       CaptureRegion = OMPD_task;
13964       break;
13965     case OMPD_parallel_master_taskloop:
13966       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
13967         CaptureRegion = OMPD_parallel;
13968       break;
13969     case OMPD_parallel_master_taskloop_simd:
13970       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
13971           NameModifier == OMPD_taskloop) {
13972         CaptureRegion = OMPD_parallel;
13973         break;
13974       }
13975       if (OpenMPVersion <= 45)
13976         break;
13977       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13978         CaptureRegion = OMPD_taskloop;
13979       break;
13980     case OMPD_parallel_for_simd:
13981       if (OpenMPVersion <= 45)
13982         break;
13983       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13984         CaptureRegion = OMPD_parallel;
13985       break;
13986     case OMPD_taskloop_simd:
13987     case OMPD_master_taskloop_simd:
13988       if (OpenMPVersion <= 45)
13989         break;
13990       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13991         CaptureRegion = OMPD_taskloop;
13992       break;
13993     case OMPD_distribute_parallel_for_simd:
13994       if (OpenMPVersion <= 45)
13995         break;
13996       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13997         CaptureRegion = OMPD_parallel;
13998       break;
13999     case OMPD_target_simd:
14000       if (OpenMPVersion >= 50 &&
14001           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
14002         CaptureRegion = OMPD_target;
14003       break;
14004     case OMPD_teams_distribute_simd:
14005     case OMPD_target_teams_distribute_simd:
14006       if (OpenMPVersion >= 50 &&
14007           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
14008         CaptureRegion = OMPD_teams;
14009       break;
14010     case OMPD_cancel:
14011     case OMPD_parallel:
14012     case OMPD_parallel_master:
14013     case OMPD_parallel_sections:
14014     case OMPD_parallel_for:
14015     case OMPD_target:
14016     case OMPD_target_teams:
14017     case OMPD_target_teams_distribute:
14018     case OMPD_distribute_parallel_for:
14019     case OMPD_task:
14020     case OMPD_taskloop:
14021     case OMPD_master_taskloop:
14022     case OMPD_target_data:
14023     case OMPD_simd:
14024     case OMPD_for_simd:
14025     case OMPD_distribute_simd:
14026       // Do not capture if-clause expressions.
14027       break;
14028     case OMPD_threadprivate:
14029     case OMPD_allocate:
14030     case OMPD_taskyield:
14031     case OMPD_barrier:
14032     case OMPD_taskwait:
14033     case OMPD_cancellation_point:
14034     case OMPD_flush:
14035     case OMPD_depobj:
14036     case OMPD_scan:
14037     case OMPD_declare_reduction:
14038     case OMPD_declare_mapper:
14039     case OMPD_declare_simd:
14040     case OMPD_declare_variant:
14041     case OMPD_begin_declare_variant:
14042     case OMPD_end_declare_variant:
14043     case OMPD_declare_target:
14044     case OMPD_end_declare_target:
14045     case OMPD_loop:
14046     case OMPD_teams:
14047     case OMPD_tile:
14048     case OMPD_unroll:
14049     case OMPD_for:
14050     case OMPD_sections:
14051     case OMPD_section:
14052     case OMPD_single:
14053     case OMPD_master:
14054     case OMPD_masked:
14055     case OMPD_critical:
14056     case OMPD_taskgroup:
14057     case OMPD_distribute:
14058     case OMPD_ordered:
14059     case OMPD_atomic:
14060     case OMPD_teams_distribute:
14061     case OMPD_requires:
14062     case OMPD_metadirective:
14063       llvm_unreachable("Unexpected OpenMP directive with if-clause");
14064     case OMPD_unknown:
14065     default:
14066       llvm_unreachable("Unknown OpenMP directive");
14067     }
14068     break;
14069   case OMPC_num_threads:
14070     switch (DKind) {
14071     case OMPD_target_parallel:
14072     case OMPD_target_parallel_for:
14073     case OMPD_target_parallel_for_simd:
14074       CaptureRegion = OMPD_target;
14075       break;
14076     case OMPD_teams_distribute_parallel_for:
14077     case OMPD_teams_distribute_parallel_for_simd:
14078     case OMPD_target_teams_distribute_parallel_for:
14079     case OMPD_target_teams_distribute_parallel_for_simd:
14080       CaptureRegion = OMPD_teams;
14081       break;
14082     case OMPD_parallel:
14083     case OMPD_parallel_master:
14084     case OMPD_parallel_sections:
14085     case OMPD_parallel_for:
14086     case OMPD_parallel_for_simd:
14087     case OMPD_distribute_parallel_for:
14088     case OMPD_distribute_parallel_for_simd:
14089     case OMPD_parallel_master_taskloop:
14090     case OMPD_parallel_master_taskloop_simd:
14091       // Do not capture num_threads-clause expressions.
14092       break;
14093     case OMPD_target_data:
14094     case OMPD_target_enter_data:
14095     case OMPD_target_exit_data:
14096     case OMPD_target_update:
14097     case OMPD_target:
14098     case OMPD_target_simd:
14099     case OMPD_target_teams:
14100     case OMPD_target_teams_distribute:
14101     case OMPD_target_teams_distribute_simd:
14102     case OMPD_cancel:
14103     case OMPD_task:
14104     case OMPD_taskloop:
14105     case OMPD_taskloop_simd:
14106     case OMPD_master_taskloop:
14107     case OMPD_master_taskloop_simd:
14108     case OMPD_threadprivate:
14109     case OMPD_allocate:
14110     case OMPD_taskyield:
14111     case OMPD_barrier:
14112     case OMPD_taskwait:
14113     case OMPD_cancellation_point:
14114     case OMPD_flush:
14115     case OMPD_depobj:
14116     case OMPD_scan:
14117     case OMPD_declare_reduction:
14118     case OMPD_declare_mapper:
14119     case OMPD_declare_simd:
14120     case OMPD_declare_variant:
14121     case OMPD_begin_declare_variant:
14122     case OMPD_end_declare_variant:
14123     case OMPD_declare_target:
14124     case OMPD_end_declare_target:
14125     case OMPD_loop:
14126     case OMPD_teams:
14127     case OMPD_simd:
14128     case OMPD_tile:
14129     case OMPD_unroll:
14130     case OMPD_for:
14131     case OMPD_for_simd:
14132     case OMPD_sections:
14133     case OMPD_section:
14134     case OMPD_single:
14135     case OMPD_master:
14136     case OMPD_masked:
14137     case OMPD_critical:
14138     case OMPD_taskgroup:
14139     case OMPD_distribute:
14140     case OMPD_ordered:
14141     case OMPD_atomic:
14142     case OMPD_distribute_simd:
14143     case OMPD_teams_distribute:
14144     case OMPD_teams_distribute_simd:
14145     case OMPD_requires:
14146     case OMPD_metadirective:
14147       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
14148     case OMPD_unknown:
14149     default:
14150       llvm_unreachable("Unknown OpenMP directive");
14151     }
14152     break;
14153   case OMPC_num_teams:
14154     switch (DKind) {
14155     case OMPD_target_teams:
14156     case OMPD_target_teams_distribute:
14157     case OMPD_target_teams_distribute_simd:
14158     case OMPD_target_teams_distribute_parallel_for:
14159     case OMPD_target_teams_distribute_parallel_for_simd:
14160       CaptureRegion = OMPD_target;
14161       break;
14162     case OMPD_teams_distribute_parallel_for:
14163     case OMPD_teams_distribute_parallel_for_simd:
14164     case OMPD_teams:
14165     case OMPD_teams_distribute:
14166     case OMPD_teams_distribute_simd:
14167       // Do not capture num_teams-clause expressions.
14168       break;
14169     case OMPD_distribute_parallel_for:
14170     case OMPD_distribute_parallel_for_simd:
14171     case OMPD_task:
14172     case OMPD_taskloop:
14173     case OMPD_taskloop_simd:
14174     case OMPD_master_taskloop:
14175     case OMPD_master_taskloop_simd:
14176     case OMPD_parallel_master_taskloop:
14177     case OMPD_parallel_master_taskloop_simd:
14178     case OMPD_target_data:
14179     case OMPD_target_enter_data:
14180     case OMPD_target_exit_data:
14181     case OMPD_target_update:
14182     case OMPD_cancel:
14183     case OMPD_parallel:
14184     case OMPD_parallel_master:
14185     case OMPD_parallel_sections:
14186     case OMPD_parallel_for:
14187     case OMPD_parallel_for_simd:
14188     case OMPD_target:
14189     case OMPD_target_simd:
14190     case OMPD_target_parallel:
14191     case OMPD_target_parallel_for:
14192     case OMPD_target_parallel_for_simd:
14193     case OMPD_threadprivate:
14194     case OMPD_allocate:
14195     case OMPD_taskyield:
14196     case OMPD_barrier:
14197     case OMPD_taskwait:
14198     case OMPD_cancellation_point:
14199     case OMPD_flush:
14200     case OMPD_depobj:
14201     case OMPD_scan:
14202     case OMPD_declare_reduction:
14203     case OMPD_declare_mapper:
14204     case OMPD_declare_simd:
14205     case OMPD_declare_variant:
14206     case OMPD_begin_declare_variant:
14207     case OMPD_end_declare_variant:
14208     case OMPD_declare_target:
14209     case OMPD_end_declare_target:
14210     case OMPD_loop:
14211     case OMPD_simd:
14212     case OMPD_tile:
14213     case OMPD_unroll:
14214     case OMPD_for:
14215     case OMPD_for_simd:
14216     case OMPD_sections:
14217     case OMPD_section:
14218     case OMPD_single:
14219     case OMPD_master:
14220     case OMPD_masked:
14221     case OMPD_critical:
14222     case OMPD_taskgroup:
14223     case OMPD_distribute:
14224     case OMPD_ordered:
14225     case OMPD_atomic:
14226     case OMPD_distribute_simd:
14227     case OMPD_requires:
14228     case OMPD_metadirective:
14229       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
14230     case OMPD_unknown:
14231     default:
14232       llvm_unreachable("Unknown OpenMP directive");
14233     }
14234     break;
14235   case OMPC_thread_limit:
14236     switch (DKind) {
14237     case OMPD_target_teams:
14238     case OMPD_target_teams_distribute:
14239     case OMPD_target_teams_distribute_simd:
14240     case OMPD_target_teams_distribute_parallel_for:
14241     case OMPD_target_teams_distribute_parallel_for_simd:
14242       CaptureRegion = OMPD_target;
14243       break;
14244     case OMPD_teams_distribute_parallel_for:
14245     case OMPD_teams_distribute_parallel_for_simd:
14246     case OMPD_teams:
14247     case OMPD_teams_distribute:
14248     case OMPD_teams_distribute_simd:
14249       // Do not capture thread_limit-clause expressions.
14250       break;
14251     case OMPD_distribute_parallel_for:
14252     case OMPD_distribute_parallel_for_simd:
14253     case OMPD_task:
14254     case OMPD_taskloop:
14255     case OMPD_taskloop_simd:
14256     case OMPD_master_taskloop:
14257     case OMPD_master_taskloop_simd:
14258     case OMPD_parallel_master_taskloop:
14259     case OMPD_parallel_master_taskloop_simd:
14260     case OMPD_target_data:
14261     case OMPD_target_enter_data:
14262     case OMPD_target_exit_data:
14263     case OMPD_target_update:
14264     case OMPD_cancel:
14265     case OMPD_parallel:
14266     case OMPD_parallel_master:
14267     case OMPD_parallel_sections:
14268     case OMPD_parallel_for:
14269     case OMPD_parallel_for_simd:
14270     case OMPD_target:
14271     case OMPD_target_simd:
14272     case OMPD_target_parallel:
14273     case OMPD_target_parallel_for:
14274     case OMPD_target_parallel_for_simd:
14275     case OMPD_threadprivate:
14276     case OMPD_allocate:
14277     case OMPD_taskyield:
14278     case OMPD_barrier:
14279     case OMPD_taskwait:
14280     case OMPD_cancellation_point:
14281     case OMPD_flush:
14282     case OMPD_depobj:
14283     case OMPD_scan:
14284     case OMPD_declare_reduction:
14285     case OMPD_declare_mapper:
14286     case OMPD_declare_simd:
14287     case OMPD_declare_variant:
14288     case OMPD_begin_declare_variant:
14289     case OMPD_end_declare_variant:
14290     case OMPD_declare_target:
14291     case OMPD_end_declare_target:
14292     case OMPD_loop:
14293     case OMPD_simd:
14294     case OMPD_tile:
14295     case OMPD_unroll:
14296     case OMPD_for:
14297     case OMPD_for_simd:
14298     case OMPD_sections:
14299     case OMPD_section:
14300     case OMPD_single:
14301     case OMPD_master:
14302     case OMPD_masked:
14303     case OMPD_critical:
14304     case OMPD_taskgroup:
14305     case OMPD_distribute:
14306     case OMPD_ordered:
14307     case OMPD_atomic:
14308     case OMPD_distribute_simd:
14309     case OMPD_requires:
14310     case OMPD_metadirective:
14311       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
14312     case OMPD_unknown:
14313     default:
14314       llvm_unreachable("Unknown OpenMP directive");
14315     }
14316     break;
14317   case OMPC_schedule:
14318     switch (DKind) {
14319     case OMPD_parallel_for:
14320     case OMPD_parallel_for_simd:
14321     case OMPD_distribute_parallel_for:
14322     case OMPD_distribute_parallel_for_simd:
14323     case OMPD_teams_distribute_parallel_for:
14324     case OMPD_teams_distribute_parallel_for_simd:
14325     case OMPD_target_parallel_for:
14326     case OMPD_target_parallel_for_simd:
14327     case OMPD_target_teams_distribute_parallel_for:
14328     case OMPD_target_teams_distribute_parallel_for_simd:
14329       CaptureRegion = OMPD_parallel;
14330       break;
14331     case OMPD_for:
14332     case OMPD_for_simd:
14333       // Do not capture schedule-clause expressions.
14334       break;
14335     case OMPD_task:
14336     case OMPD_taskloop:
14337     case OMPD_taskloop_simd:
14338     case OMPD_master_taskloop:
14339     case OMPD_master_taskloop_simd:
14340     case OMPD_parallel_master_taskloop:
14341     case OMPD_parallel_master_taskloop_simd:
14342     case OMPD_target_data:
14343     case OMPD_target_enter_data:
14344     case OMPD_target_exit_data:
14345     case OMPD_target_update:
14346     case OMPD_teams:
14347     case OMPD_teams_distribute:
14348     case OMPD_teams_distribute_simd:
14349     case OMPD_target_teams_distribute:
14350     case OMPD_target_teams_distribute_simd:
14351     case OMPD_target:
14352     case OMPD_target_simd:
14353     case OMPD_target_parallel:
14354     case OMPD_cancel:
14355     case OMPD_parallel:
14356     case OMPD_parallel_master:
14357     case OMPD_parallel_sections:
14358     case OMPD_threadprivate:
14359     case OMPD_allocate:
14360     case OMPD_taskyield:
14361     case OMPD_barrier:
14362     case OMPD_taskwait:
14363     case OMPD_cancellation_point:
14364     case OMPD_flush:
14365     case OMPD_depobj:
14366     case OMPD_scan:
14367     case OMPD_declare_reduction:
14368     case OMPD_declare_mapper:
14369     case OMPD_declare_simd:
14370     case OMPD_declare_variant:
14371     case OMPD_begin_declare_variant:
14372     case OMPD_end_declare_variant:
14373     case OMPD_declare_target:
14374     case OMPD_end_declare_target:
14375     case OMPD_loop:
14376     case OMPD_simd:
14377     case OMPD_tile:
14378     case OMPD_unroll:
14379     case OMPD_sections:
14380     case OMPD_section:
14381     case OMPD_single:
14382     case OMPD_master:
14383     case OMPD_masked:
14384     case OMPD_critical:
14385     case OMPD_taskgroup:
14386     case OMPD_distribute:
14387     case OMPD_ordered:
14388     case OMPD_atomic:
14389     case OMPD_distribute_simd:
14390     case OMPD_target_teams:
14391     case OMPD_requires:
14392     case OMPD_metadirective:
14393       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
14394     case OMPD_unknown:
14395     default:
14396       llvm_unreachable("Unknown OpenMP directive");
14397     }
14398     break;
14399   case OMPC_dist_schedule:
14400     switch (DKind) {
14401     case OMPD_teams_distribute_parallel_for:
14402     case OMPD_teams_distribute_parallel_for_simd:
14403     case OMPD_teams_distribute:
14404     case OMPD_teams_distribute_simd:
14405     case OMPD_target_teams_distribute_parallel_for:
14406     case OMPD_target_teams_distribute_parallel_for_simd:
14407     case OMPD_target_teams_distribute:
14408     case OMPD_target_teams_distribute_simd:
14409       CaptureRegion = OMPD_teams;
14410       break;
14411     case OMPD_distribute_parallel_for:
14412     case OMPD_distribute_parallel_for_simd:
14413     case OMPD_distribute:
14414     case OMPD_distribute_simd:
14415       // Do not capture dist_schedule-clause expressions.
14416       break;
14417     case OMPD_parallel_for:
14418     case OMPD_parallel_for_simd:
14419     case OMPD_target_parallel_for_simd:
14420     case OMPD_target_parallel_for:
14421     case OMPD_task:
14422     case OMPD_taskloop:
14423     case OMPD_taskloop_simd:
14424     case OMPD_master_taskloop:
14425     case OMPD_master_taskloop_simd:
14426     case OMPD_parallel_master_taskloop:
14427     case OMPD_parallel_master_taskloop_simd:
14428     case OMPD_target_data:
14429     case OMPD_target_enter_data:
14430     case OMPD_target_exit_data:
14431     case OMPD_target_update:
14432     case OMPD_teams:
14433     case OMPD_target:
14434     case OMPD_target_simd:
14435     case OMPD_target_parallel:
14436     case OMPD_cancel:
14437     case OMPD_parallel:
14438     case OMPD_parallel_master:
14439     case OMPD_parallel_sections:
14440     case OMPD_threadprivate:
14441     case OMPD_allocate:
14442     case OMPD_taskyield:
14443     case OMPD_barrier:
14444     case OMPD_taskwait:
14445     case OMPD_cancellation_point:
14446     case OMPD_flush:
14447     case OMPD_depobj:
14448     case OMPD_scan:
14449     case OMPD_declare_reduction:
14450     case OMPD_declare_mapper:
14451     case OMPD_declare_simd:
14452     case OMPD_declare_variant:
14453     case OMPD_begin_declare_variant:
14454     case OMPD_end_declare_variant:
14455     case OMPD_declare_target:
14456     case OMPD_end_declare_target:
14457     case OMPD_loop:
14458     case OMPD_simd:
14459     case OMPD_tile:
14460     case OMPD_unroll:
14461     case OMPD_for:
14462     case OMPD_for_simd:
14463     case OMPD_sections:
14464     case OMPD_section:
14465     case OMPD_single:
14466     case OMPD_master:
14467     case OMPD_masked:
14468     case OMPD_critical:
14469     case OMPD_taskgroup:
14470     case OMPD_ordered:
14471     case OMPD_atomic:
14472     case OMPD_target_teams:
14473     case OMPD_requires:
14474     case OMPD_metadirective:
14475       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
14476     case OMPD_unknown:
14477     default:
14478       llvm_unreachable("Unknown OpenMP directive");
14479     }
14480     break;
14481   case OMPC_device:
14482     switch (DKind) {
14483     case OMPD_target_update:
14484     case OMPD_target_enter_data:
14485     case OMPD_target_exit_data:
14486     case OMPD_target:
14487     case OMPD_target_simd:
14488     case OMPD_target_teams:
14489     case OMPD_target_parallel:
14490     case OMPD_target_teams_distribute:
14491     case OMPD_target_teams_distribute_simd:
14492     case OMPD_target_parallel_for:
14493     case OMPD_target_parallel_for_simd:
14494     case OMPD_target_teams_distribute_parallel_for:
14495     case OMPD_target_teams_distribute_parallel_for_simd:
14496     case OMPD_dispatch:
14497       CaptureRegion = OMPD_task;
14498       break;
14499     case OMPD_target_data:
14500     case OMPD_interop:
14501       // Do not capture device-clause expressions.
14502       break;
14503     case OMPD_teams_distribute_parallel_for:
14504     case OMPD_teams_distribute_parallel_for_simd:
14505     case OMPD_teams:
14506     case OMPD_teams_distribute:
14507     case OMPD_teams_distribute_simd:
14508     case OMPD_distribute_parallel_for:
14509     case OMPD_distribute_parallel_for_simd:
14510     case OMPD_task:
14511     case OMPD_taskloop:
14512     case OMPD_taskloop_simd:
14513     case OMPD_master_taskloop:
14514     case OMPD_master_taskloop_simd:
14515     case OMPD_parallel_master_taskloop:
14516     case OMPD_parallel_master_taskloop_simd:
14517     case OMPD_cancel:
14518     case OMPD_parallel:
14519     case OMPD_parallel_master:
14520     case OMPD_parallel_sections:
14521     case OMPD_parallel_for:
14522     case OMPD_parallel_for_simd:
14523     case OMPD_threadprivate:
14524     case OMPD_allocate:
14525     case OMPD_taskyield:
14526     case OMPD_barrier:
14527     case OMPD_taskwait:
14528     case OMPD_cancellation_point:
14529     case OMPD_flush:
14530     case OMPD_depobj:
14531     case OMPD_scan:
14532     case OMPD_declare_reduction:
14533     case OMPD_declare_mapper:
14534     case OMPD_declare_simd:
14535     case OMPD_declare_variant:
14536     case OMPD_begin_declare_variant:
14537     case OMPD_end_declare_variant:
14538     case OMPD_declare_target:
14539     case OMPD_end_declare_target:
14540     case OMPD_loop:
14541     case OMPD_simd:
14542     case OMPD_tile:
14543     case OMPD_unroll:
14544     case OMPD_for:
14545     case OMPD_for_simd:
14546     case OMPD_sections:
14547     case OMPD_section:
14548     case OMPD_single:
14549     case OMPD_master:
14550     case OMPD_masked:
14551     case OMPD_critical:
14552     case OMPD_taskgroup:
14553     case OMPD_distribute:
14554     case OMPD_ordered:
14555     case OMPD_atomic:
14556     case OMPD_distribute_simd:
14557     case OMPD_requires:
14558     case OMPD_metadirective:
14559       llvm_unreachable("Unexpected OpenMP directive with device-clause");
14560     case OMPD_unknown:
14561     default:
14562       llvm_unreachable("Unknown OpenMP directive");
14563     }
14564     break;
14565   case OMPC_grainsize:
14566   case OMPC_num_tasks:
14567   case OMPC_final:
14568   case OMPC_priority:
14569     switch (DKind) {
14570     case OMPD_task:
14571     case OMPD_taskloop:
14572     case OMPD_taskloop_simd:
14573     case OMPD_master_taskloop:
14574     case OMPD_master_taskloop_simd:
14575       break;
14576     case OMPD_parallel_master_taskloop:
14577     case OMPD_parallel_master_taskloop_simd:
14578       CaptureRegion = OMPD_parallel;
14579       break;
14580     case OMPD_target_update:
14581     case OMPD_target_enter_data:
14582     case OMPD_target_exit_data:
14583     case OMPD_target:
14584     case OMPD_target_simd:
14585     case OMPD_target_teams:
14586     case OMPD_target_parallel:
14587     case OMPD_target_teams_distribute:
14588     case OMPD_target_teams_distribute_simd:
14589     case OMPD_target_parallel_for:
14590     case OMPD_target_parallel_for_simd:
14591     case OMPD_target_teams_distribute_parallel_for:
14592     case OMPD_target_teams_distribute_parallel_for_simd:
14593     case OMPD_target_data:
14594     case OMPD_teams_distribute_parallel_for:
14595     case OMPD_teams_distribute_parallel_for_simd:
14596     case OMPD_teams:
14597     case OMPD_teams_distribute:
14598     case OMPD_teams_distribute_simd:
14599     case OMPD_distribute_parallel_for:
14600     case OMPD_distribute_parallel_for_simd:
14601     case OMPD_cancel:
14602     case OMPD_parallel:
14603     case OMPD_parallel_master:
14604     case OMPD_parallel_sections:
14605     case OMPD_parallel_for:
14606     case OMPD_parallel_for_simd:
14607     case OMPD_threadprivate:
14608     case OMPD_allocate:
14609     case OMPD_taskyield:
14610     case OMPD_barrier:
14611     case OMPD_taskwait:
14612     case OMPD_cancellation_point:
14613     case OMPD_flush:
14614     case OMPD_depobj:
14615     case OMPD_scan:
14616     case OMPD_declare_reduction:
14617     case OMPD_declare_mapper:
14618     case OMPD_declare_simd:
14619     case OMPD_declare_variant:
14620     case OMPD_begin_declare_variant:
14621     case OMPD_end_declare_variant:
14622     case OMPD_declare_target:
14623     case OMPD_end_declare_target:
14624     case OMPD_loop:
14625     case OMPD_simd:
14626     case OMPD_tile:
14627     case OMPD_unroll:
14628     case OMPD_for:
14629     case OMPD_for_simd:
14630     case OMPD_sections:
14631     case OMPD_section:
14632     case OMPD_single:
14633     case OMPD_master:
14634     case OMPD_masked:
14635     case OMPD_critical:
14636     case OMPD_taskgroup:
14637     case OMPD_distribute:
14638     case OMPD_ordered:
14639     case OMPD_atomic:
14640     case OMPD_distribute_simd:
14641     case OMPD_requires:
14642     case OMPD_metadirective:
14643       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
14644     case OMPD_unknown:
14645     default:
14646       llvm_unreachable("Unknown OpenMP directive");
14647     }
14648     break;
14649   case OMPC_novariants:
14650   case OMPC_nocontext:
14651     switch (DKind) {
14652     case OMPD_dispatch:
14653       CaptureRegion = OMPD_task;
14654       break;
14655     default:
14656       llvm_unreachable("Unexpected OpenMP directive");
14657     }
14658     break;
14659   case OMPC_filter:
14660     // Do not capture filter-clause expressions.
14661     break;
14662   case OMPC_when:
14663     if (DKind == OMPD_metadirective) {
14664       CaptureRegion = OMPD_metadirective;
14665     } else if (DKind == OMPD_unknown) {
14666       llvm_unreachable("Unknown OpenMP directive");
14667     } else {
14668       llvm_unreachable("Unexpected OpenMP directive with when clause");
14669     }
14670     break;
14671   case OMPC_firstprivate:
14672   case OMPC_lastprivate:
14673   case OMPC_reduction:
14674   case OMPC_task_reduction:
14675   case OMPC_in_reduction:
14676   case OMPC_linear:
14677   case OMPC_default:
14678   case OMPC_proc_bind:
14679   case OMPC_safelen:
14680   case OMPC_simdlen:
14681   case OMPC_sizes:
14682   case OMPC_allocator:
14683   case OMPC_collapse:
14684   case OMPC_private:
14685   case OMPC_shared:
14686   case OMPC_aligned:
14687   case OMPC_copyin:
14688   case OMPC_copyprivate:
14689   case OMPC_ordered:
14690   case OMPC_nowait:
14691   case OMPC_untied:
14692   case OMPC_mergeable:
14693   case OMPC_threadprivate:
14694   case OMPC_allocate:
14695   case OMPC_flush:
14696   case OMPC_depobj:
14697   case OMPC_read:
14698   case OMPC_write:
14699   case OMPC_update:
14700   case OMPC_capture:
14701   case OMPC_compare:
14702   case OMPC_seq_cst:
14703   case OMPC_acq_rel:
14704   case OMPC_acquire:
14705   case OMPC_release:
14706   case OMPC_relaxed:
14707   case OMPC_depend:
14708   case OMPC_threads:
14709   case OMPC_simd:
14710   case OMPC_map:
14711   case OMPC_nogroup:
14712   case OMPC_hint:
14713   case OMPC_defaultmap:
14714   case OMPC_unknown:
14715   case OMPC_uniform:
14716   case OMPC_to:
14717   case OMPC_from:
14718   case OMPC_use_device_ptr:
14719   case OMPC_use_device_addr:
14720   case OMPC_is_device_ptr:
14721   case OMPC_unified_address:
14722   case OMPC_unified_shared_memory:
14723   case OMPC_reverse_offload:
14724   case OMPC_dynamic_allocators:
14725   case OMPC_atomic_default_mem_order:
14726   case OMPC_device_type:
14727   case OMPC_match:
14728   case OMPC_nontemporal:
14729   case OMPC_order:
14730   case OMPC_destroy:
14731   case OMPC_detach:
14732   case OMPC_inclusive:
14733   case OMPC_exclusive:
14734   case OMPC_uses_allocators:
14735   case OMPC_affinity:
14736   case OMPC_bind:
14737   default:
14738     llvm_unreachable("Unexpected OpenMP clause.");
14739   }
14740   return CaptureRegion;
14741 }
14742 
14743 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
14744                                      Expr *Condition, SourceLocation StartLoc,
14745                                      SourceLocation LParenLoc,
14746                                      SourceLocation NameModifierLoc,
14747                                      SourceLocation ColonLoc,
14748                                      SourceLocation EndLoc) {
14749   Expr *ValExpr = Condition;
14750   Stmt *HelperValStmt = nullptr;
14751   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14752   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14753       !Condition->isInstantiationDependent() &&
14754       !Condition->containsUnexpandedParameterPack()) {
14755     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14756     if (Val.isInvalid())
14757       return nullptr;
14758 
14759     ValExpr = Val.get();
14760 
14761     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14762     CaptureRegion = getOpenMPCaptureRegionForClause(
14763         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
14764     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14765       ValExpr = MakeFullExpr(ValExpr).get();
14766       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14767       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14768       HelperValStmt = buildPreInits(Context, Captures);
14769     }
14770   }
14771 
14772   return new (Context)
14773       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
14774                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
14775 }
14776 
14777 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
14778                                         SourceLocation StartLoc,
14779                                         SourceLocation LParenLoc,
14780                                         SourceLocation EndLoc) {
14781   Expr *ValExpr = Condition;
14782   Stmt *HelperValStmt = nullptr;
14783   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14784   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14785       !Condition->isInstantiationDependent() &&
14786       !Condition->containsUnexpandedParameterPack()) {
14787     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14788     if (Val.isInvalid())
14789       return nullptr;
14790 
14791     ValExpr = MakeFullExpr(Val.get()).get();
14792 
14793     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14794     CaptureRegion =
14795         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
14796     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14797       ValExpr = MakeFullExpr(ValExpr).get();
14798       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14799       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14800       HelperValStmt = buildPreInits(Context, Captures);
14801     }
14802   }
14803 
14804   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
14805                                       StartLoc, LParenLoc, EndLoc);
14806 }
14807 
14808 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
14809                                                         Expr *Op) {
14810   if (!Op)
14811     return ExprError();
14812 
14813   class IntConvertDiagnoser : public ICEConvertDiagnoser {
14814   public:
14815     IntConvertDiagnoser()
14816         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
14817     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14818                                          QualType T) override {
14819       return S.Diag(Loc, diag::err_omp_not_integral) << T;
14820     }
14821     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
14822                                              QualType T) override {
14823       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
14824     }
14825     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
14826                                                QualType T,
14827                                                QualType ConvTy) override {
14828       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
14829     }
14830     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
14831                                            QualType ConvTy) override {
14832       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14833              << ConvTy->isEnumeralType() << ConvTy;
14834     }
14835     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
14836                                             QualType T) override {
14837       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
14838     }
14839     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
14840                                         QualType ConvTy) override {
14841       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14842              << ConvTy->isEnumeralType() << ConvTy;
14843     }
14844     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
14845                                              QualType) override {
14846       llvm_unreachable("conversion functions are permitted");
14847     }
14848   } ConvertDiagnoser;
14849   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
14850 }
14851 
14852 static bool
14853 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
14854                           bool StrictlyPositive, bool BuildCapture = false,
14855                           OpenMPDirectiveKind DKind = OMPD_unknown,
14856                           OpenMPDirectiveKind *CaptureRegion = nullptr,
14857                           Stmt **HelperValStmt = nullptr) {
14858   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
14859       !ValExpr->isInstantiationDependent()) {
14860     SourceLocation Loc = ValExpr->getExprLoc();
14861     ExprResult Value =
14862         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
14863     if (Value.isInvalid())
14864       return false;
14865 
14866     ValExpr = Value.get();
14867     // The expression must evaluate to a non-negative integer value.
14868     if (Optional<llvm::APSInt> Result =
14869             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
14870       if (Result->isSigned() &&
14871           !((!StrictlyPositive && Result->isNonNegative()) ||
14872             (StrictlyPositive && Result->isStrictlyPositive()))) {
14873         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
14874             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14875             << ValExpr->getSourceRange();
14876         return false;
14877       }
14878     }
14879     if (!BuildCapture)
14880       return true;
14881     *CaptureRegion =
14882         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
14883     if (*CaptureRegion != OMPD_unknown &&
14884         !SemaRef.CurContext->isDependentContext()) {
14885       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
14886       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14887       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
14888       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
14889     }
14890   }
14891   return true;
14892 }
14893 
14894 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
14895                                              SourceLocation StartLoc,
14896                                              SourceLocation LParenLoc,
14897                                              SourceLocation EndLoc) {
14898   Expr *ValExpr = NumThreads;
14899   Stmt *HelperValStmt = nullptr;
14900 
14901   // OpenMP [2.5, Restrictions]
14902   //  The num_threads expression must evaluate to a positive integer value.
14903   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
14904                                  /*StrictlyPositive=*/true))
14905     return nullptr;
14906 
14907   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14908   OpenMPDirectiveKind CaptureRegion =
14909       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
14910   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14911     ValExpr = MakeFullExpr(ValExpr).get();
14912     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14913     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14914     HelperValStmt = buildPreInits(Context, Captures);
14915   }
14916 
14917   return new (Context) OMPNumThreadsClause(
14918       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14919 }
14920 
14921 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
14922                                                        OpenMPClauseKind CKind,
14923                                                        bool StrictlyPositive,
14924                                                        bool SuppressExprDiags) {
14925   if (!E)
14926     return ExprError();
14927   if (E->isValueDependent() || E->isTypeDependent() ||
14928       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14929     return E;
14930 
14931   llvm::APSInt Result;
14932   ExprResult ICE;
14933   if (SuppressExprDiags) {
14934     // Use a custom diagnoser that suppresses 'note' diagnostics about the
14935     // expression.
14936     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
14937       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
14938       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
14939                                                  SourceLocation Loc) override {
14940         llvm_unreachable("Diagnostic suppressed");
14941       }
14942     } Diagnoser;
14943     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
14944   } else {
14945     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
14946   }
14947   if (ICE.isInvalid())
14948     return ExprError();
14949 
14950   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
14951       (!StrictlyPositive && !Result.isNonNegative())) {
14952     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
14953         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14954         << E->getSourceRange();
14955     return ExprError();
14956   }
14957   if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
14958     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
14959         << E->getSourceRange();
14960     return ExprError();
14961   }
14962   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
14963     DSAStack->setAssociatedLoops(Result.getExtValue());
14964   else if (CKind == OMPC_ordered)
14965     DSAStack->setAssociatedLoops(Result.getExtValue());
14966   return ICE;
14967 }
14968 
14969 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
14970                                           SourceLocation LParenLoc,
14971                                           SourceLocation EndLoc) {
14972   // OpenMP [2.8.1, simd construct, Description]
14973   // The parameter of the safelen clause must be a constant
14974   // positive integer expression.
14975   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
14976   if (Safelen.isInvalid())
14977     return nullptr;
14978   return new (Context)
14979       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
14980 }
14981 
14982 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
14983                                           SourceLocation LParenLoc,
14984                                           SourceLocation EndLoc) {
14985   // OpenMP [2.8.1, simd construct, Description]
14986   // The parameter of the simdlen clause must be a constant
14987   // positive integer expression.
14988   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
14989   if (Simdlen.isInvalid())
14990     return nullptr;
14991   return new (Context)
14992       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
14993 }
14994 
14995 /// Tries to find omp_allocator_handle_t type.
14996 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
14997                                     DSAStackTy *Stack) {
14998   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
14999   if (!OMPAllocatorHandleT.isNull())
15000     return true;
15001   // Build the predefined allocator expressions.
15002   bool ErrorFound = false;
15003   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
15004     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
15005     StringRef Allocator =
15006         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
15007     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
15008     auto *VD = dyn_cast_or_null<ValueDecl>(
15009         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
15010     if (!VD) {
15011       ErrorFound = true;
15012       break;
15013     }
15014     QualType AllocatorType =
15015         VD->getType().getNonLValueExprType(S.getASTContext());
15016     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
15017     if (!Res.isUsable()) {
15018       ErrorFound = true;
15019       break;
15020     }
15021     if (OMPAllocatorHandleT.isNull())
15022       OMPAllocatorHandleT = AllocatorType;
15023     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
15024       ErrorFound = true;
15025       break;
15026     }
15027     Stack->setAllocator(AllocatorKind, Res.get());
15028   }
15029   if (ErrorFound) {
15030     S.Diag(Loc, diag::err_omp_implied_type_not_found)
15031         << "omp_allocator_handle_t";
15032     return false;
15033   }
15034   OMPAllocatorHandleT.addConst();
15035   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
15036   return true;
15037 }
15038 
15039 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
15040                                             SourceLocation LParenLoc,
15041                                             SourceLocation EndLoc) {
15042   // OpenMP [2.11.3, allocate Directive, Description]
15043   // allocator is an expression of omp_allocator_handle_t type.
15044   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
15045     return nullptr;
15046 
15047   ExprResult Allocator = DefaultLvalueConversion(A);
15048   if (Allocator.isInvalid())
15049     return nullptr;
15050   Allocator = PerformImplicitConversion(Allocator.get(),
15051                                         DSAStack->getOMPAllocatorHandleT(),
15052                                         Sema::AA_Initializing,
15053                                         /*AllowExplicit=*/true);
15054   if (Allocator.isInvalid())
15055     return nullptr;
15056   return new (Context)
15057       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
15058 }
15059 
15060 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
15061                                            SourceLocation StartLoc,
15062                                            SourceLocation LParenLoc,
15063                                            SourceLocation EndLoc) {
15064   // OpenMP [2.7.1, loop construct, Description]
15065   // OpenMP [2.8.1, simd construct, Description]
15066   // OpenMP [2.9.6, distribute construct, Description]
15067   // The parameter of the collapse clause must be a constant
15068   // positive integer expression.
15069   ExprResult NumForLoopsResult =
15070       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
15071   if (NumForLoopsResult.isInvalid())
15072     return nullptr;
15073   return new (Context)
15074       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
15075 }
15076 
15077 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
15078                                           SourceLocation EndLoc,
15079                                           SourceLocation LParenLoc,
15080                                           Expr *NumForLoops) {
15081   // OpenMP [2.7.1, loop construct, Description]
15082   // OpenMP [2.8.1, simd construct, Description]
15083   // OpenMP [2.9.6, distribute construct, Description]
15084   // The parameter of the ordered clause must be a constant
15085   // positive integer expression if any.
15086   if (NumForLoops && LParenLoc.isValid()) {
15087     ExprResult NumForLoopsResult =
15088         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
15089     if (NumForLoopsResult.isInvalid())
15090       return nullptr;
15091     NumForLoops = NumForLoopsResult.get();
15092   } else {
15093     NumForLoops = nullptr;
15094   }
15095   auto *Clause = OMPOrderedClause::Create(
15096       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
15097       StartLoc, LParenLoc, EndLoc);
15098   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
15099   return Clause;
15100 }
15101 
15102 OMPClause *Sema::ActOnOpenMPSimpleClause(
15103     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
15104     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15105   OMPClause *Res = nullptr;
15106   switch (Kind) {
15107   case OMPC_default:
15108     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
15109                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15110     break;
15111   case OMPC_proc_bind:
15112     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
15113                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15114     break;
15115   case OMPC_atomic_default_mem_order:
15116     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
15117         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
15118         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15119     break;
15120   case OMPC_order:
15121     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
15122                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15123     break;
15124   case OMPC_update:
15125     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
15126                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15127     break;
15128   case OMPC_bind:
15129     Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
15130                                 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
15131     break;
15132   case OMPC_if:
15133   case OMPC_final:
15134   case OMPC_num_threads:
15135   case OMPC_safelen:
15136   case OMPC_simdlen:
15137   case OMPC_sizes:
15138   case OMPC_allocator:
15139   case OMPC_collapse:
15140   case OMPC_schedule:
15141   case OMPC_private:
15142   case OMPC_firstprivate:
15143   case OMPC_lastprivate:
15144   case OMPC_shared:
15145   case OMPC_reduction:
15146   case OMPC_task_reduction:
15147   case OMPC_in_reduction:
15148   case OMPC_linear:
15149   case OMPC_aligned:
15150   case OMPC_copyin:
15151   case OMPC_copyprivate:
15152   case OMPC_ordered:
15153   case OMPC_nowait:
15154   case OMPC_untied:
15155   case OMPC_mergeable:
15156   case OMPC_threadprivate:
15157   case OMPC_allocate:
15158   case OMPC_flush:
15159   case OMPC_depobj:
15160   case OMPC_read:
15161   case OMPC_write:
15162   case OMPC_capture:
15163   case OMPC_compare:
15164   case OMPC_seq_cst:
15165   case OMPC_acq_rel:
15166   case OMPC_acquire:
15167   case OMPC_release:
15168   case OMPC_relaxed:
15169   case OMPC_depend:
15170   case OMPC_device:
15171   case OMPC_threads:
15172   case OMPC_simd:
15173   case OMPC_map:
15174   case OMPC_num_teams:
15175   case OMPC_thread_limit:
15176   case OMPC_priority:
15177   case OMPC_grainsize:
15178   case OMPC_nogroup:
15179   case OMPC_num_tasks:
15180   case OMPC_hint:
15181   case OMPC_dist_schedule:
15182   case OMPC_defaultmap:
15183   case OMPC_unknown:
15184   case OMPC_uniform:
15185   case OMPC_to:
15186   case OMPC_from:
15187   case OMPC_use_device_ptr:
15188   case OMPC_use_device_addr:
15189   case OMPC_is_device_ptr:
15190   case OMPC_unified_address:
15191   case OMPC_unified_shared_memory:
15192   case OMPC_reverse_offload:
15193   case OMPC_dynamic_allocators:
15194   case OMPC_device_type:
15195   case OMPC_match:
15196   case OMPC_nontemporal:
15197   case OMPC_destroy:
15198   case OMPC_novariants:
15199   case OMPC_nocontext:
15200   case OMPC_detach:
15201   case OMPC_inclusive:
15202   case OMPC_exclusive:
15203   case OMPC_uses_allocators:
15204   case OMPC_affinity:
15205   case OMPC_when:
15206   default:
15207     llvm_unreachable("Clause is not allowed.");
15208   }
15209   return Res;
15210 }
15211 
15212 static std::string
15213 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
15214                         ArrayRef<unsigned> Exclude = llvm::None) {
15215   SmallString<256> Buffer;
15216   llvm::raw_svector_ostream Out(Buffer);
15217   unsigned Skipped = Exclude.size();
15218   auto S = Exclude.begin(), E = Exclude.end();
15219   for (unsigned I = First; I < Last; ++I) {
15220     if (std::find(S, E, I) != E) {
15221       --Skipped;
15222       continue;
15223     }
15224     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
15225     if (I + Skipped + 2 == Last)
15226       Out << " or ";
15227     else if (I + Skipped + 1 != Last)
15228       Out << ", ";
15229   }
15230   return std::string(Out.str());
15231 }
15232 
15233 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
15234                                           SourceLocation KindKwLoc,
15235                                           SourceLocation StartLoc,
15236                                           SourceLocation LParenLoc,
15237                                           SourceLocation EndLoc) {
15238   if (Kind == OMP_DEFAULT_unknown) {
15239     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
15240         << getListOfPossibleValues(OMPC_default, /*First=*/0,
15241                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
15242         << getOpenMPClauseName(OMPC_default);
15243     return nullptr;
15244   }
15245 
15246   switch (Kind) {
15247   case OMP_DEFAULT_none:
15248     DSAStack->setDefaultDSANone(KindKwLoc);
15249     break;
15250   case OMP_DEFAULT_shared:
15251     DSAStack->setDefaultDSAShared(KindKwLoc);
15252     break;
15253   case OMP_DEFAULT_firstprivate:
15254     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
15255     break;
15256   default:
15257     llvm_unreachable("DSA unexpected in OpenMP default clause");
15258   }
15259 
15260   return new (Context)
15261       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
15262 }
15263 
15264 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
15265                                            SourceLocation KindKwLoc,
15266                                            SourceLocation StartLoc,
15267                                            SourceLocation LParenLoc,
15268                                            SourceLocation EndLoc) {
15269   if (Kind == OMP_PROC_BIND_unknown) {
15270     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
15271         << getListOfPossibleValues(OMPC_proc_bind,
15272                                    /*First=*/unsigned(OMP_PROC_BIND_master),
15273                                    /*Last=*/
15274                                    unsigned(LangOpts.OpenMP > 50
15275                                                 ? OMP_PROC_BIND_primary
15276                                                 : OMP_PROC_BIND_spread) +
15277                                        1)
15278         << getOpenMPClauseName(OMPC_proc_bind);
15279     return nullptr;
15280   }
15281   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
15282     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
15283         << getListOfPossibleValues(OMPC_proc_bind,
15284                                    /*First=*/unsigned(OMP_PROC_BIND_master),
15285                                    /*Last=*/
15286                                    unsigned(OMP_PROC_BIND_spread) + 1)
15287         << getOpenMPClauseName(OMPC_proc_bind);
15288   return new (Context)
15289       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
15290 }
15291 
15292 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
15293     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
15294     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15295   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
15296     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
15297         << getListOfPossibleValues(
15298                OMPC_atomic_default_mem_order, /*First=*/0,
15299                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
15300         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
15301     return nullptr;
15302   }
15303   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
15304                                                       LParenLoc, EndLoc);
15305 }
15306 
15307 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
15308                                         SourceLocation KindKwLoc,
15309                                         SourceLocation StartLoc,
15310                                         SourceLocation LParenLoc,
15311                                         SourceLocation EndLoc) {
15312   if (Kind == OMPC_ORDER_unknown) {
15313     static_assert(OMPC_ORDER_unknown > 0,
15314                   "OMPC_ORDER_unknown not greater than 0");
15315     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
15316         << getListOfPossibleValues(OMPC_order, /*First=*/0,
15317                                    /*Last=*/OMPC_ORDER_unknown)
15318         << getOpenMPClauseName(OMPC_order);
15319     return nullptr;
15320   }
15321   return new (Context)
15322       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
15323 }
15324 
15325 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
15326                                          SourceLocation KindKwLoc,
15327                                          SourceLocation StartLoc,
15328                                          SourceLocation LParenLoc,
15329                                          SourceLocation EndLoc) {
15330   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
15331       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
15332     SmallVector<unsigned> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
15333                                     OMPC_DEPEND_depobj};
15334     if (LangOpts.OpenMP < 51)
15335       Except.push_back(OMPC_DEPEND_inoutset);
15336     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
15337         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
15338                                    /*Last=*/OMPC_DEPEND_unknown, Except)
15339         << getOpenMPClauseName(OMPC_update);
15340     return nullptr;
15341   }
15342   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
15343                                  EndLoc);
15344 }
15345 
15346 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
15347                                         SourceLocation StartLoc,
15348                                         SourceLocation LParenLoc,
15349                                         SourceLocation EndLoc) {
15350   for (Expr *SizeExpr : SizeExprs) {
15351     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
15352         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
15353     if (!NumForLoopsResult.isUsable())
15354       return nullptr;
15355   }
15356 
15357   DSAStack->setAssociatedLoops(SizeExprs.size());
15358   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15359                                 SizeExprs);
15360 }
15361 
15362 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
15363                                        SourceLocation EndLoc) {
15364   return OMPFullClause::Create(Context, StartLoc, EndLoc);
15365 }
15366 
15367 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
15368                                           SourceLocation StartLoc,
15369                                           SourceLocation LParenLoc,
15370                                           SourceLocation EndLoc) {
15371   if (FactorExpr) {
15372     // If an argument is specified, it must be a constant (or an unevaluated
15373     // template expression).
15374     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
15375         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
15376     if (FactorResult.isInvalid())
15377       return nullptr;
15378     FactorExpr = FactorResult.get();
15379   }
15380 
15381   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15382                                   FactorExpr);
15383 }
15384 
15385 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
15386                                         SourceLocation LParenLoc,
15387                                         SourceLocation EndLoc) {
15388   ExprResult AlignVal;
15389   AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
15390   if (AlignVal.isInvalid())
15391     return nullptr;
15392   return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
15393                                 EndLoc);
15394 }
15395 
15396 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
15397     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
15398     SourceLocation StartLoc, SourceLocation LParenLoc,
15399     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
15400     SourceLocation EndLoc) {
15401   OMPClause *Res = nullptr;
15402   switch (Kind) {
15403   case OMPC_schedule:
15404     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
15405     assert(Argument.size() == NumberOfElements &&
15406            ArgumentLoc.size() == NumberOfElements);
15407     Res = ActOnOpenMPScheduleClause(
15408         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
15409         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
15410         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
15411         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
15412         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
15413     break;
15414   case OMPC_if:
15415     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15416     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
15417                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
15418                               DelimLoc, EndLoc);
15419     break;
15420   case OMPC_dist_schedule:
15421     Res = ActOnOpenMPDistScheduleClause(
15422         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
15423         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
15424     break;
15425   case OMPC_defaultmap:
15426     enum { Modifier, DefaultmapKind };
15427     Res = ActOnOpenMPDefaultmapClause(
15428         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
15429         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
15430         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
15431         EndLoc);
15432     break;
15433   case OMPC_device:
15434     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15435     Res = ActOnOpenMPDeviceClause(
15436         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
15437         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
15438     break;
15439   case OMPC_final:
15440   case OMPC_num_threads:
15441   case OMPC_safelen:
15442   case OMPC_simdlen:
15443   case OMPC_sizes:
15444   case OMPC_allocator:
15445   case OMPC_collapse:
15446   case OMPC_default:
15447   case OMPC_proc_bind:
15448   case OMPC_private:
15449   case OMPC_firstprivate:
15450   case OMPC_lastprivate:
15451   case OMPC_shared:
15452   case OMPC_reduction:
15453   case OMPC_task_reduction:
15454   case OMPC_in_reduction:
15455   case OMPC_linear:
15456   case OMPC_aligned:
15457   case OMPC_copyin:
15458   case OMPC_copyprivate:
15459   case OMPC_ordered:
15460   case OMPC_nowait:
15461   case OMPC_untied:
15462   case OMPC_mergeable:
15463   case OMPC_threadprivate:
15464   case OMPC_allocate:
15465   case OMPC_flush:
15466   case OMPC_depobj:
15467   case OMPC_read:
15468   case OMPC_write:
15469   case OMPC_update:
15470   case OMPC_capture:
15471   case OMPC_compare:
15472   case OMPC_seq_cst:
15473   case OMPC_acq_rel:
15474   case OMPC_acquire:
15475   case OMPC_release:
15476   case OMPC_relaxed:
15477   case OMPC_depend:
15478   case OMPC_threads:
15479   case OMPC_simd:
15480   case OMPC_map:
15481   case OMPC_num_teams:
15482   case OMPC_thread_limit:
15483   case OMPC_priority:
15484   case OMPC_grainsize:
15485   case OMPC_nogroup:
15486   case OMPC_num_tasks:
15487   case OMPC_hint:
15488   case OMPC_unknown:
15489   case OMPC_uniform:
15490   case OMPC_to:
15491   case OMPC_from:
15492   case OMPC_use_device_ptr:
15493   case OMPC_use_device_addr:
15494   case OMPC_is_device_ptr:
15495   case OMPC_unified_address:
15496   case OMPC_unified_shared_memory:
15497   case OMPC_reverse_offload:
15498   case OMPC_dynamic_allocators:
15499   case OMPC_atomic_default_mem_order:
15500   case OMPC_device_type:
15501   case OMPC_match:
15502   case OMPC_nontemporal:
15503   case OMPC_order:
15504   case OMPC_destroy:
15505   case OMPC_novariants:
15506   case OMPC_nocontext:
15507   case OMPC_detach:
15508   case OMPC_inclusive:
15509   case OMPC_exclusive:
15510   case OMPC_uses_allocators:
15511   case OMPC_affinity:
15512   case OMPC_when:
15513   case OMPC_bind:
15514   default:
15515     llvm_unreachable("Clause is not allowed.");
15516   }
15517   return Res;
15518 }
15519 
15520 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
15521                                    OpenMPScheduleClauseModifier M2,
15522                                    SourceLocation M1Loc, SourceLocation M2Loc) {
15523   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
15524     SmallVector<unsigned, 2> Excluded;
15525     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
15526       Excluded.push_back(M2);
15527     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
15528       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
15529     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
15530       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
15531     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
15532         << getListOfPossibleValues(OMPC_schedule,
15533                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
15534                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15535                                    Excluded)
15536         << getOpenMPClauseName(OMPC_schedule);
15537     return true;
15538   }
15539   return false;
15540 }
15541 
15542 OMPClause *Sema::ActOnOpenMPScheduleClause(
15543     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
15544     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15545     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
15546     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
15547   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
15548       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
15549     return nullptr;
15550   // OpenMP, 2.7.1, Loop Construct, Restrictions
15551   // Either the monotonic modifier or the nonmonotonic modifier can be specified
15552   // but not both.
15553   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
15554       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
15555        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
15556       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
15557        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
15558     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
15559         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
15560         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
15561     return nullptr;
15562   }
15563   if (Kind == OMPC_SCHEDULE_unknown) {
15564     std::string Values;
15565     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
15566       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
15567       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15568                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15569                                        Exclude);
15570     } else {
15571       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15572                                        /*Last=*/OMPC_SCHEDULE_unknown);
15573     }
15574     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15575         << Values << getOpenMPClauseName(OMPC_schedule);
15576     return nullptr;
15577   }
15578   // OpenMP, 2.7.1, Loop Construct, Restrictions
15579   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
15580   // schedule(guided).
15581   // OpenMP 5.0 does not have this restriction.
15582   if (LangOpts.OpenMP < 50 &&
15583       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
15584        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
15585       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
15586     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
15587          diag::err_omp_schedule_nonmonotonic_static);
15588     return nullptr;
15589   }
15590   Expr *ValExpr = ChunkSize;
15591   Stmt *HelperValStmt = nullptr;
15592   if (ChunkSize) {
15593     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15594         !ChunkSize->isInstantiationDependent() &&
15595         !ChunkSize->containsUnexpandedParameterPack()) {
15596       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
15597       ExprResult Val =
15598           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
15599       if (Val.isInvalid())
15600         return nullptr;
15601 
15602       ValExpr = Val.get();
15603 
15604       // OpenMP [2.7.1, Restrictions]
15605       //  chunk_size must be a loop invariant integer expression with a positive
15606       //  value.
15607       if (Optional<llvm::APSInt> Result =
15608               ValExpr->getIntegerConstantExpr(Context)) {
15609         if (Result->isSigned() && !Result->isStrictlyPositive()) {
15610           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
15611               << "schedule" << 1 << ChunkSize->getSourceRange();
15612           return nullptr;
15613         }
15614       } else if (getOpenMPCaptureRegionForClause(
15615                      DSAStack->getCurrentDirective(), OMPC_schedule,
15616                      LangOpts.OpenMP) != OMPD_unknown &&
15617                  !CurContext->isDependentContext()) {
15618         ValExpr = MakeFullExpr(ValExpr).get();
15619         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15620         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15621         HelperValStmt = buildPreInits(Context, Captures);
15622       }
15623     }
15624   }
15625 
15626   return new (Context)
15627       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
15628                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
15629 }
15630 
15631 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
15632                                    SourceLocation StartLoc,
15633                                    SourceLocation EndLoc) {
15634   OMPClause *Res = nullptr;
15635   switch (Kind) {
15636   case OMPC_ordered:
15637     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
15638     break;
15639   case OMPC_nowait:
15640     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
15641     break;
15642   case OMPC_untied:
15643     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
15644     break;
15645   case OMPC_mergeable:
15646     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
15647     break;
15648   case OMPC_read:
15649     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
15650     break;
15651   case OMPC_write:
15652     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
15653     break;
15654   case OMPC_update:
15655     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
15656     break;
15657   case OMPC_capture:
15658     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
15659     break;
15660   case OMPC_compare:
15661     Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
15662     break;
15663   case OMPC_seq_cst:
15664     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
15665     break;
15666   case OMPC_acq_rel:
15667     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
15668     break;
15669   case OMPC_acquire:
15670     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
15671     break;
15672   case OMPC_release:
15673     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
15674     break;
15675   case OMPC_relaxed:
15676     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
15677     break;
15678   case OMPC_threads:
15679     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
15680     break;
15681   case OMPC_simd:
15682     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
15683     break;
15684   case OMPC_nogroup:
15685     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
15686     break;
15687   case OMPC_unified_address:
15688     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
15689     break;
15690   case OMPC_unified_shared_memory:
15691     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15692     break;
15693   case OMPC_reverse_offload:
15694     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
15695     break;
15696   case OMPC_dynamic_allocators:
15697     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
15698     break;
15699   case OMPC_destroy:
15700     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
15701                                    /*LParenLoc=*/SourceLocation(),
15702                                    /*VarLoc=*/SourceLocation(), EndLoc);
15703     break;
15704   case OMPC_full:
15705     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
15706     break;
15707   case OMPC_partial:
15708     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
15709     break;
15710   case OMPC_if:
15711   case OMPC_final:
15712   case OMPC_num_threads:
15713   case OMPC_safelen:
15714   case OMPC_simdlen:
15715   case OMPC_sizes:
15716   case OMPC_allocator:
15717   case OMPC_collapse:
15718   case OMPC_schedule:
15719   case OMPC_private:
15720   case OMPC_firstprivate:
15721   case OMPC_lastprivate:
15722   case OMPC_shared:
15723   case OMPC_reduction:
15724   case OMPC_task_reduction:
15725   case OMPC_in_reduction:
15726   case OMPC_linear:
15727   case OMPC_aligned:
15728   case OMPC_copyin:
15729   case OMPC_copyprivate:
15730   case OMPC_default:
15731   case OMPC_proc_bind:
15732   case OMPC_threadprivate:
15733   case OMPC_allocate:
15734   case OMPC_flush:
15735   case OMPC_depobj:
15736   case OMPC_depend:
15737   case OMPC_device:
15738   case OMPC_map:
15739   case OMPC_num_teams:
15740   case OMPC_thread_limit:
15741   case OMPC_priority:
15742   case OMPC_grainsize:
15743   case OMPC_num_tasks:
15744   case OMPC_hint:
15745   case OMPC_dist_schedule:
15746   case OMPC_defaultmap:
15747   case OMPC_unknown:
15748   case OMPC_uniform:
15749   case OMPC_to:
15750   case OMPC_from:
15751   case OMPC_use_device_ptr:
15752   case OMPC_use_device_addr:
15753   case OMPC_is_device_ptr:
15754   case OMPC_atomic_default_mem_order:
15755   case OMPC_device_type:
15756   case OMPC_match:
15757   case OMPC_nontemporal:
15758   case OMPC_order:
15759   case OMPC_novariants:
15760   case OMPC_nocontext:
15761   case OMPC_detach:
15762   case OMPC_inclusive:
15763   case OMPC_exclusive:
15764   case OMPC_uses_allocators:
15765   case OMPC_affinity:
15766   case OMPC_when:
15767   default:
15768     llvm_unreachable("Clause is not allowed.");
15769   }
15770   return Res;
15771 }
15772 
15773 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
15774                                          SourceLocation EndLoc) {
15775   DSAStack->setNowaitRegion();
15776   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
15777 }
15778 
15779 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
15780                                          SourceLocation EndLoc) {
15781   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
15782 }
15783 
15784 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
15785                                             SourceLocation EndLoc) {
15786   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
15787 }
15788 
15789 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
15790                                        SourceLocation EndLoc) {
15791   return new (Context) OMPReadClause(StartLoc, EndLoc);
15792 }
15793 
15794 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
15795                                         SourceLocation EndLoc) {
15796   return new (Context) OMPWriteClause(StartLoc, EndLoc);
15797 }
15798 
15799 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
15800                                          SourceLocation EndLoc) {
15801   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
15802 }
15803 
15804 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
15805                                           SourceLocation EndLoc) {
15806   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
15807 }
15808 
15809 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc,
15810                                           SourceLocation EndLoc) {
15811   return new (Context) OMPCompareClause(StartLoc, EndLoc);
15812 }
15813 
15814 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
15815                                          SourceLocation EndLoc) {
15816   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
15817 }
15818 
15819 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
15820                                          SourceLocation EndLoc) {
15821   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
15822 }
15823 
15824 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
15825                                           SourceLocation EndLoc) {
15826   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
15827 }
15828 
15829 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
15830                                           SourceLocation EndLoc) {
15831   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
15832 }
15833 
15834 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
15835                                           SourceLocation EndLoc) {
15836   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
15837 }
15838 
15839 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
15840                                           SourceLocation EndLoc) {
15841   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
15842 }
15843 
15844 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
15845                                        SourceLocation EndLoc) {
15846   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
15847 }
15848 
15849 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
15850                                           SourceLocation EndLoc) {
15851   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
15852 }
15853 
15854 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
15855                                                  SourceLocation EndLoc) {
15856   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
15857 }
15858 
15859 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
15860                                                       SourceLocation EndLoc) {
15861   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15862 }
15863 
15864 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
15865                                                  SourceLocation EndLoc) {
15866   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
15867 }
15868 
15869 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
15870                                                     SourceLocation EndLoc) {
15871   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
15872 }
15873 
15874 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
15875                                              SourceLocation StartLoc,
15876                                              SourceLocation EndLoc) {
15877 
15878   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15879   // At least one action-clause must appear on a directive.
15880   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
15881     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
15882     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
15883         << Expected << getOpenMPDirectiveName(OMPD_interop);
15884     return StmtError();
15885   }
15886 
15887   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15888   // A depend clause can only appear on the directive if a targetsync
15889   // interop-type is present or the interop-var was initialized with
15890   // the targetsync interop-type.
15891 
15892   // If there is any 'init' clause diagnose if there is no 'init' clause with
15893   // interop-type of 'targetsync'. Cases involving other directives cannot be
15894   // diagnosed.
15895   const OMPDependClause *DependClause = nullptr;
15896   bool HasInitClause = false;
15897   bool IsTargetSync = false;
15898   for (const OMPClause *C : Clauses) {
15899     if (IsTargetSync)
15900       break;
15901     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
15902       HasInitClause = true;
15903       if (InitClause->getIsTargetSync())
15904         IsTargetSync = true;
15905     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
15906       DependClause = DC;
15907     }
15908   }
15909   if (DependClause && HasInitClause && !IsTargetSync) {
15910     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
15911     return StmtError();
15912   }
15913 
15914   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15915   // Each interop-var may be specified for at most one action-clause of each
15916   // interop construct.
15917   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
15918   for (const OMPClause *C : Clauses) {
15919     OpenMPClauseKind ClauseKind = C->getClauseKind();
15920     const DeclRefExpr *DRE = nullptr;
15921     SourceLocation VarLoc;
15922 
15923     if (ClauseKind == OMPC_init) {
15924       const auto *IC = cast<OMPInitClause>(C);
15925       VarLoc = IC->getVarLoc();
15926       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
15927     } else if (ClauseKind == OMPC_use) {
15928       const auto *UC = cast<OMPUseClause>(C);
15929       VarLoc = UC->getVarLoc();
15930       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
15931     } else if (ClauseKind == OMPC_destroy) {
15932       const auto *DC = cast<OMPDestroyClause>(C);
15933       VarLoc = DC->getVarLoc();
15934       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
15935     }
15936 
15937     if (!DRE)
15938       continue;
15939 
15940     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
15941       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
15942         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
15943         return StmtError();
15944       }
15945     }
15946   }
15947 
15948   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
15949 }
15950 
15951 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
15952                                    SourceLocation VarLoc,
15953                                    OpenMPClauseKind Kind) {
15954   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
15955       InteropVarExpr->isInstantiationDependent() ||
15956       InteropVarExpr->containsUnexpandedParameterPack())
15957     return true;
15958 
15959   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
15960   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
15961     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
15962     return false;
15963   }
15964 
15965   // Interop variable should be of type omp_interop_t.
15966   bool HasError = false;
15967   QualType InteropType;
15968   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
15969                       VarLoc, Sema::LookupOrdinaryName);
15970   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
15971     NamedDecl *ND = Result.getFoundDecl();
15972     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
15973       InteropType = QualType(TD->getTypeForDecl(), 0);
15974     } else {
15975       HasError = true;
15976     }
15977   } else {
15978     HasError = true;
15979   }
15980 
15981   if (HasError) {
15982     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
15983         << "omp_interop_t";
15984     return false;
15985   }
15986 
15987   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
15988   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
15989     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
15990     return false;
15991   }
15992 
15993   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15994   // The interop-var passed to init or destroy must be non-const.
15995   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
15996       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
15997     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
15998         << /*non-const*/ 1;
15999     return false;
16000   }
16001   return true;
16002 }
16003 
16004 OMPClause *
16005 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
16006                             bool IsTarget, bool IsTargetSync,
16007                             SourceLocation StartLoc, SourceLocation LParenLoc,
16008                             SourceLocation VarLoc, SourceLocation EndLoc) {
16009 
16010   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
16011     return nullptr;
16012 
16013   // Check prefer_type values.  These foreign-runtime-id values are either
16014   // string literals or constant integral expressions.
16015   for (const Expr *E : PrefExprs) {
16016     if (E->isValueDependent() || E->isTypeDependent() ||
16017         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
16018       continue;
16019     if (E->isIntegerConstantExpr(Context))
16020       continue;
16021     if (isa<StringLiteral>(E))
16022       continue;
16023     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
16024     return nullptr;
16025   }
16026 
16027   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
16028                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
16029                                EndLoc);
16030 }
16031 
16032 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
16033                                       SourceLocation LParenLoc,
16034                                       SourceLocation VarLoc,
16035                                       SourceLocation EndLoc) {
16036 
16037   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
16038     return nullptr;
16039 
16040   return new (Context)
16041       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
16042 }
16043 
16044 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
16045                                           SourceLocation StartLoc,
16046                                           SourceLocation LParenLoc,
16047                                           SourceLocation VarLoc,
16048                                           SourceLocation EndLoc) {
16049   if (InteropVar &&
16050       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
16051     return nullptr;
16052 
16053   return new (Context)
16054       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
16055 }
16056 
16057 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
16058                                              SourceLocation StartLoc,
16059                                              SourceLocation LParenLoc,
16060                                              SourceLocation EndLoc) {
16061   Expr *ValExpr = Condition;
16062   Stmt *HelperValStmt = nullptr;
16063   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
16064   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
16065       !Condition->isInstantiationDependent() &&
16066       !Condition->containsUnexpandedParameterPack()) {
16067     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
16068     if (Val.isInvalid())
16069       return nullptr;
16070 
16071     ValExpr = MakeFullExpr(Val.get()).get();
16072 
16073     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16074     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
16075                                                     LangOpts.OpenMP);
16076     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16077       ValExpr = MakeFullExpr(ValExpr).get();
16078       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16079       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16080       HelperValStmt = buildPreInits(Context, Captures);
16081     }
16082   }
16083 
16084   return new (Context) OMPNovariantsClause(
16085       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
16086 }
16087 
16088 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
16089                                             SourceLocation StartLoc,
16090                                             SourceLocation LParenLoc,
16091                                             SourceLocation EndLoc) {
16092   Expr *ValExpr = Condition;
16093   Stmt *HelperValStmt = nullptr;
16094   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
16095   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
16096       !Condition->isInstantiationDependent() &&
16097       !Condition->containsUnexpandedParameterPack()) {
16098     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
16099     if (Val.isInvalid())
16100       return nullptr;
16101 
16102     ValExpr = MakeFullExpr(Val.get()).get();
16103 
16104     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16105     CaptureRegion =
16106         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
16107     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16108       ValExpr = MakeFullExpr(ValExpr).get();
16109       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16110       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16111       HelperValStmt = buildPreInits(Context, Captures);
16112     }
16113   }
16114 
16115   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
16116                                           StartLoc, LParenLoc, EndLoc);
16117 }
16118 
16119 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
16120                                          SourceLocation StartLoc,
16121                                          SourceLocation LParenLoc,
16122                                          SourceLocation EndLoc) {
16123   Expr *ValExpr = ThreadID;
16124   Stmt *HelperValStmt = nullptr;
16125 
16126   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16127   OpenMPDirectiveKind CaptureRegion =
16128       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
16129   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16130     ValExpr = MakeFullExpr(ValExpr).get();
16131     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16132     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16133     HelperValStmt = buildPreInits(Context, Captures);
16134   }
16135 
16136   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
16137                                        StartLoc, LParenLoc, EndLoc);
16138 }
16139 
16140 OMPClause *Sema::ActOnOpenMPVarListClause(
16141     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
16142     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
16143     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
16144     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
16145     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16146     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
16147     SourceLocation ExtraModifierLoc,
16148     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
16149     ArrayRef<SourceLocation> MotionModifiersLoc) {
16150   SourceLocation StartLoc = Locs.StartLoc;
16151   SourceLocation LParenLoc = Locs.LParenLoc;
16152   SourceLocation EndLoc = Locs.EndLoc;
16153   OMPClause *Res = nullptr;
16154   switch (Kind) {
16155   case OMPC_private:
16156     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16157     break;
16158   case OMPC_firstprivate:
16159     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16160     break;
16161   case OMPC_lastprivate:
16162     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
16163            "Unexpected lastprivate modifier.");
16164     Res = ActOnOpenMPLastprivateClause(
16165         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
16166         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
16167     break;
16168   case OMPC_shared:
16169     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
16170     break;
16171   case OMPC_reduction:
16172     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
16173            "Unexpected lastprivate modifier.");
16174     Res = ActOnOpenMPReductionClause(
16175         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
16176         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
16177         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
16178     break;
16179   case OMPC_task_reduction:
16180     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
16181                                          EndLoc, ReductionOrMapperIdScopeSpec,
16182                                          ReductionOrMapperId);
16183     break;
16184   case OMPC_in_reduction:
16185     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
16186                                        EndLoc, ReductionOrMapperIdScopeSpec,
16187                                        ReductionOrMapperId);
16188     break;
16189   case OMPC_linear:
16190     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
16191            "Unexpected linear modifier.");
16192     Res = ActOnOpenMPLinearClause(
16193         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
16194         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
16195         ColonLoc, EndLoc);
16196     break;
16197   case OMPC_aligned:
16198     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
16199                                    LParenLoc, ColonLoc, EndLoc);
16200     break;
16201   case OMPC_copyin:
16202     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
16203     break;
16204   case OMPC_copyprivate:
16205     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
16206     break;
16207   case OMPC_flush:
16208     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
16209     break;
16210   case OMPC_depend:
16211     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
16212            "Unexpected depend modifier.");
16213     Res = ActOnOpenMPDependClause(
16214         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
16215         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
16216     break;
16217   case OMPC_map:
16218     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
16219            "Unexpected map modifier.");
16220     Res = ActOnOpenMPMapClause(
16221         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
16222         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
16223         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
16224     break;
16225   case OMPC_to:
16226     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
16227                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
16228                               ColonLoc, VarList, Locs);
16229     break;
16230   case OMPC_from:
16231     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
16232                                 ReductionOrMapperIdScopeSpec,
16233                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
16234     break;
16235   case OMPC_use_device_ptr:
16236     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
16237     break;
16238   case OMPC_use_device_addr:
16239     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
16240     break;
16241   case OMPC_is_device_ptr:
16242     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
16243     break;
16244   case OMPC_allocate:
16245     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
16246                                     LParenLoc, ColonLoc, EndLoc);
16247     break;
16248   case OMPC_nontemporal:
16249     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
16250     break;
16251   case OMPC_inclusive:
16252     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
16253     break;
16254   case OMPC_exclusive:
16255     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
16256     break;
16257   case OMPC_affinity:
16258     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
16259                                     DepModOrTailExpr, VarList);
16260     break;
16261   case OMPC_if:
16262   case OMPC_depobj:
16263   case OMPC_final:
16264   case OMPC_num_threads:
16265   case OMPC_safelen:
16266   case OMPC_simdlen:
16267   case OMPC_sizes:
16268   case OMPC_allocator:
16269   case OMPC_collapse:
16270   case OMPC_default:
16271   case OMPC_proc_bind:
16272   case OMPC_schedule:
16273   case OMPC_ordered:
16274   case OMPC_nowait:
16275   case OMPC_untied:
16276   case OMPC_mergeable:
16277   case OMPC_threadprivate:
16278   case OMPC_read:
16279   case OMPC_write:
16280   case OMPC_update:
16281   case OMPC_capture:
16282   case OMPC_compare:
16283   case OMPC_seq_cst:
16284   case OMPC_acq_rel:
16285   case OMPC_acquire:
16286   case OMPC_release:
16287   case OMPC_relaxed:
16288   case OMPC_device:
16289   case OMPC_threads:
16290   case OMPC_simd:
16291   case OMPC_num_teams:
16292   case OMPC_thread_limit:
16293   case OMPC_priority:
16294   case OMPC_grainsize:
16295   case OMPC_nogroup:
16296   case OMPC_num_tasks:
16297   case OMPC_hint:
16298   case OMPC_dist_schedule:
16299   case OMPC_defaultmap:
16300   case OMPC_unknown:
16301   case OMPC_uniform:
16302   case OMPC_unified_address:
16303   case OMPC_unified_shared_memory:
16304   case OMPC_reverse_offload:
16305   case OMPC_dynamic_allocators:
16306   case OMPC_atomic_default_mem_order:
16307   case OMPC_device_type:
16308   case OMPC_match:
16309   case OMPC_order:
16310   case OMPC_destroy:
16311   case OMPC_novariants:
16312   case OMPC_nocontext:
16313   case OMPC_detach:
16314   case OMPC_uses_allocators:
16315   case OMPC_when:
16316   case OMPC_bind:
16317   default:
16318     llvm_unreachable("Clause is not allowed.");
16319   }
16320   return Res;
16321 }
16322 
16323 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
16324                                        ExprObjectKind OK, SourceLocation Loc) {
16325   ExprResult Res = BuildDeclRefExpr(
16326       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
16327   if (!Res.isUsable())
16328     return ExprError();
16329   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
16330     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
16331     if (!Res.isUsable())
16332       return ExprError();
16333   }
16334   if (VK != VK_LValue && Res.get()->isGLValue()) {
16335     Res = DefaultLvalueConversion(Res.get());
16336     if (!Res.isUsable())
16337       return ExprError();
16338   }
16339   return Res;
16340 }
16341 
16342 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
16343                                           SourceLocation StartLoc,
16344                                           SourceLocation LParenLoc,
16345                                           SourceLocation EndLoc) {
16346   SmallVector<Expr *, 8> Vars;
16347   SmallVector<Expr *, 8> PrivateCopies;
16348   for (Expr *RefExpr : VarList) {
16349     assert(RefExpr && "NULL expr in OpenMP private clause.");
16350     SourceLocation ELoc;
16351     SourceRange ERange;
16352     Expr *SimpleRefExpr = RefExpr;
16353     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16354     if (Res.second) {
16355       // It will be analyzed later.
16356       Vars.push_back(RefExpr);
16357       PrivateCopies.push_back(nullptr);
16358     }
16359     ValueDecl *D = Res.first;
16360     if (!D)
16361       continue;
16362 
16363     QualType Type = D->getType();
16364     auto *VD = dyn_cast<VarDecl>(D);
16365 
16366     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16367     //  A variable that appears in a private clause must not have an incomplete
16368     //  type or a reference type.
16369     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
16370       continue;
16371     Type = Type.getNonReferenceType();
16372 
16373     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16374     // A variable that is privatized must not have a const-qualified type
16375     // unless it is of class type with a mutable member. This restriction does
16376     // not apply to the firstprivate clause.
16377     //
16378     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
16379     // A variable that appears in a private clause must not have a
16380     // const-qualified type unless it is of class type with a mutable member.
16381     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
16382       continue;
16383 
16384     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16385     // in a Construct]
16386     //  Variables with the predetermined data-sharing attributes may not be
16387     //  listed in data-sharing attributes clauses, except for the cases
16388     //  listed below. For these exceptions only, listing a predetermined
16389     //  variable in a data-sharing attribute clause is allowed and overrides
16390     //  the variable's predetermined data-sharing attributes.
16391     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16392     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
16393       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16394                                           << getOpenMPClauseName(OMPC_private);
16395       reportOriginalDsa(*this, DSAStack, D, DVar);
16396       continue;
16397     }
16398 
16399     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16400     // Variably modified types are not supported for tasks.
16401     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
16402         isOpenMPTaskingDirective(CurrDir)) {
16403       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16404           << getOpenMPClauseName(OMPC_private) << Type
16405           << getOpenMPDirectiveName(CurrDir);
16406       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16407                                VarDecl::DeclarationOnly;
16408       Diag(D->getLocation(),
16409            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16410           << D;
16411       continue;
16412     }
16413 
16414     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16415     // A list item cannot appear in both a map clause and a data-sharing
16416     // attribute clause on the same construct
16417     //
16418     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16419     // A list item cannot appear in both a map clause and a data-sharing
16420     // attribute clause on the same construct unless the construct is a
16421     // combined construct.
16422     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
16423         CurrDir == OMPD_target) {
16424       OpenMPClauseKind ConflictKind;
16425       if (DSAStack->checkMappableExprComponentListsForDecl(
16426               VD, /*CurrentRegionOnly=*/true,
16427               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
16428                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
16429                 ConflictKind = WhereFoundClauseKind;
16430                 return true;
16431               })) {
16432         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16433             << getOpenMPClauseName(OMPC_private)
16434             << getOpenMPClauseName(ConflictKind)
16435             << getOpenMPDirectiveName(CurrDir);
16436         reportOriginalDsa(*this, DSAStack, D, DVar);
16437         continue;
16438       }
16439     }
16440 
16441     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
16442     //  A variable of class type (or array thereof) that appears in a private
16443     //  clause requires an accessible, unambiguous default constructor for the
16444     //  class type.
16445     // Generate helper private variable and initialize it with the default
16446     // value. The address of the original variable is replaced by the address of
16447     // the new private variable in CodeGen. This new variable is not added to
16448     // IdResolver, so the code in the OpenMP region uses original variable for
16449     // proper diagnostics.
16450     Type = Type.getUnqualifiedType();
16451     VarDecl *VDPrivate =
16452         buildVarDecl(*this, ELoc, Type, D->getName(),
16453                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16454                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16455     ActOnUninitializedDecl(VDPrivate);
16456     if (VDPrivate->isInvalidDecl())
16457       continue;
16458     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16459         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16460 
16461     DeclRefExpr *Ref = nullptr;
16462     if (!VD && !CurContext->isDependentContext())
16463       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16464     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
16465     Vars.push_back((VD || CurContext->isDependentContext())
16466                        ? RefExpr->IgnoreParens()
16467                        : Ref);
16468     PrivateCopies.push_back(VDPrivateRefExpr);
16469   }
16470 
16471   if (Vars.empty())
16472     return nullptr;
16473 
16474   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
16475                                   PrivateCopies);
16476 }
16477 
16478 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
16479                                                SourceLocation StartLoc,
16480                                                SourceLocation LParenLoc,
16481                                                SourceLocation EndLoc) {
16482   SmallVector<Expr *, 8> Vars;
16483   SmallVector<Expr *, 8> PrivateCopies;
16484   SmallVector<Expr *, 8> Inits;
16485   SmallVector<Decl *, 4> ExprCaptures;
16486   bool IsImplicitClause =
16487       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
16488   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
16489 
16490   for (Expr *RefExpr : VarList) {
16491     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
16492     SourceLocation ELoc;
16493     SourceRange ERange;
16494     Expr *SimpleRefExpr = RefExpr;
16495     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16496     if (Res.second) {
16497       // It will be analyzed later.
16498       Vars.push_back(RefExpr);
16499       PrivateCopies.push_back(nullptr);
16500       Inits.push_back(nullptr);
16501     }
16502     ValueDecl *D = Res.first;
16503     if (!D)
16504       continue;
16505 
16506     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
16507     QualType Type = D->getType();
16508     auto *VD = dyn_cast<VarDecl>(D);
16509 
16510     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16511     //  A variable that appears in a private clause must not have an incomplete
16512     //  type or a reference type.
16513     if (RequireCompleteType(ELoc, Type,
16514                             diag::err_omp_firstprivate_incomplete_type))
16515       continue;
16516     Type = Type.getNonReferenceType();
16517 
16518     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
16519     //  A variable of class type (or array thereof) that appears in a private
16520     //  clause requires an accessible, unambiguous copy constructor for the
16521     //  class type.
16522     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
16523 
16524     // If an implicit firstprivate variable found it was checked already.
16525     DSAStackTy::DSAVarData TopDVar;
16526     if (!IsImplicitClause) {
16527       DSAStackTy::DSAVarData DVar =
16528           DSAStack->getTopDSA(D, /*FromParent=*/false);
16529       TopDVar = DVar;
16530       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16531       bool IsConstant = ElemType.isConstant(Context);
16532       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
16533       //  A list item that specifies a given variable may not appear in more
16534       // than one clause on the same directive, except that a variable may be
16535       //  specified in both firstprivate and lastprivate clauses.
16536       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16537       // A list item may appear in a firstprivate or lastprivate clause but not
16538       // both.
16539       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
16540           (isOpenMPDistributeDirective(CurrDir) ||
16541            DVar.CKind != OMPC_lastprivate) &&
16542           DVar.RefExpr) {
16543         Diag(ELoc, diag::err_omp_wrong_dsa)
16544             << getOpenMPClauseName(DVar.CKind)
16545             << getOpenMPClauseName(OMPC_firstprivate);
16546         reportOriginalDsa(*this, DSAStack, D, DVar);
16547         continue;
16548       }
16549 
16550       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16551       // in a Construct]
16552       //  Variables with the predetermined data-sharing attributes may not be
16553       //  listed in data-sharing attributes clauses, except for the cases
16554       //  listed below. For these exceptions only, listing a predetermined
16555       //  variable in a data-sharing attribute clause is allowed and overrides
16556       //  the variable's predetermined data-sharing attributes.
16557       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16558       // in a Construct, C/C++, p.2]
16559       //  Variables with const-qualified type having no mutable member may be
16560       //  listed in a firstprivate clause, even if they are static data members.
16561       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
16562           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
16563         Diag(ELoc, diag::err_omp_wrong_dsa)
16564             << getOpenMPClauseName(DVar.CKind)
16565             << getOpenMPClauseName(OMPC_firstprivate);
16566         reportOriginalDsa(*this, DSAStack, D, DVar);
16567         continue;
16568       }
16569 
16570       // OpenMP [2.9.3.4, Restrictions, p.2]
16571       //  A list item that is private within a parallel region must not appear
16572       //  in a firstprivate clause on a worksharing construct if any of the
16573       //  worksharing regions arising from the worksharing construct ever bind
16574       //  to any of the parallel regions arising from the parallel construct.
16575       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16576       // A list item that is private within a teams region must not appear in a
16577       // firstprivate clause on a distribute construct if any of the distribute
16578       // regions arising from the distribute construct ever bind to any of the
16579       // teams regions arising from the teams construct.
16580       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16581       // A list item that appears in a reduction clause of a teams construct
16582       // must not appear in a firstprivate clause on a distribute construct if
16583       // any of the distribute regions arising from the distribute construct
16584       // ever bind to any of the teams regions arising from the teams construct.
16585       if ((isOpenMPWorksharingDirective(CurrDir) ||
16586            isOpenMPDistributeDirective(CurrDir)) &&
16587           !isOpenMPParallelDirective(CurrDir) &&
16588           !isOpenMPTeamsDirective(CurrDir)) {
16589         DVar = DSAStack->getImplicitDSA(D, true);
16590         if (DVar.CKind != OMPC_shared &&
16591             (isOpenMPParallelDirective(DVar.DKind) ||
16592              isOpenMPTeamsDirective(DVar.DKind) ||
16593              DVar.DKind == OMPD_unknown)) {
16594           Diag(ELoc, diag::err_omp_required_access)
16595               << getOpenMPClauseName(OMPC_firstprivate)
16596               << getOpenMPClauseName(OMPC_shared);
16597           reportOriginalDsa(*this, DSAStack, D, DVar);
16598           continue;
16599         }
16600       }
16601       // OpenMP [2.9.3.4, Restrictions, p.3]
16602       //  A list item that appears in a reduction clause of a parallel construct
16603       //  must not appear in a firstprivate clause on a worksharing or task
16604       //  construct if any of the worksharing or task regions arising from the
16605       //  worksharing or task construct ever bind to any of the parallel regions
16606       //  arising from the parallel construct.
16607       // OpenMP [2.9.3.4, Restrictions, p.4]
16608       //  A list item that appears in a reduction clause in worksharing
16609       //  construct must not appear in a firstprivate clause in a task construct
16610       //  encountered during execution of any of the worksharing regions arising
16611       //  from the worksharing construct.
16612       if (isOpenMPTaskingDirective(CurrDir)) {
16613         DVar = DSAStack->hasInnermostDSA(
16614             D,
16615             [](OpenMPClauseKind C, bool AppliedToPointee) {
16616               return C == OMPC_reduction && !AppliedToPointee;
16617             },
16618             [](OpenMPDirectiveKind K) {
16619               return isOpenMPParallelDirective(K) ||
16620                      isOpenMPWorksharingDirective(K) ||
16621                      isOpenMPTeamsDirective(K);
16622             },
16623             /*FromParent=*/true);
16624         if (DVar.CKind == OMPC_reduction &&
16625             (isOpenMPParallelDirective(DVar.DKind) ||
16626              isOpenMPWorksharingDirective(DVar.DKind) ||
16627              isOpenMPTeamsDirective(DVar.DKind))) {
16628           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
16629               << getOpenMPDirectiveName(DVar.DKind);
16630           reportOriginalDsa(*this, DSAStack, D, DVar);
16631           continue;
16632         }
16633       }
16634 
16635       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16636       // A list item cannot appear in both a map clause and a data-sharing
16637       // attribute clause on the same construct
16638       //
16639       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16640       // A list item cannot appear in both a map clause and a data-sharing
16641       // attribute clause on the same construct unless the construct is a
16642       // combined construct.
16643       if ((LangOpts.OpenMP <= 45 &&
16644            isOpenMPTargetExecutionDirective(CurrDir)) ||
16645           CurrDir == OMPD_target) {
16646         OpenMPClauseKind ConflictKind;
16647         if (DSAStack->checkMappableExprComponentListsForDecl(
16648                 VD, /*CurrentRegionOnly=*/true,
16649                 [&ConflictKind](
16650                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
16651                     OpenMPClauseKind WhereFoundClauseKind) {
16652                   ConflictKind = WhereFoundClauseKind;
16653                   return true;
16654                 })) {
16655           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16656               << getOpenMPClauseName(OMPC_firstprivate)
16657               << getOpenMPClauseName(ConflictKind)
16658               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16659           reportOriginalDsa(*this, DSAStack, D, DVar);
16660           continue;
16661         }
16662       }
16663     }
16664 
16665     // Variably modified types are not supported for tasks.
16666     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
16667         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
16668       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16669           << getOpenMPClauseName(OMPC_firstprivate) << Type
16670           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16671       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16672                                VarDecl::DeclarationOnly;
16673       Diag(D->getLocation(),
16674            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16675           << D;
16676       continue;
16677     }
16678 
16679     Type = Type.getUnqualifiedType();
16680     VarDecl *VDPrivate =
16681         buildVarDecl(*this, ELoc, Type, D->getName(),
16682                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16683                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16684     // Generate helper private variable and initialize it with the value of the
16685     // original variable. The address of the original variable is replaced by
16686     // the address of the new private variable in the CodeGen. This new variable
16687     // is not added to IdResolver, so the code in the OpenMP region uses
16688     // original variable for proper diagnostics and variable capturing.
16689     Expr *VDInitRefExpr = nullptr;
16690     // For arrays generate initializer for single element and replace it by the
16691     // original array element in CodeGen.
16692     if (Type->isArrayType()) {
16693       VarDecl *VDInit =
16694           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
16695       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
16696       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
16697       ElemType = ElemType.getUnqualifiedType();
16698       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
16699                                          ".firstprivate.temp");
16700       InitializedEntity Entity =
16701           InitializedEntity::InitializeVariable(VDInitTemp);
16702       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
16703 
16704       InitializationSequence InitSeq(*this, Entity, Kind, Init);
16705       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
16706       if (Result.isInvalid())
16707         VDPrivate->setInvalidDecl();
16708       else
16709         VDPrivate->setInit(Result.getAs<Expr>());
16710       // Remove temp variable declaration.
16711       Context.Deallocate(VDInitTemp);
16712     } else {
16713       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
16714                                      ".firstprivate.temp");
16715       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
16716                                        RefExpr->getExprLoc());
16717       AddInitializerToDecl(VDPrivate,
16718                            DefaultLvalueConversion(VDInitRefExpr).get(),
16719                            /*DirectInit=*/false);
16720     }
16721     if (VDPrivate->isInvalidDecl()) {
16722       if (IsImplicitClause) {
16723         Diag(RefExpr->getExprLoc(),
16724              diag::note_omp_task_predetermined_firstprivate_here);
16725       }
16726       continue;
16727     }
16728     CurContext->addDecl(VDPrivate);
16729     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16730         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
16731         RefExpr->getExprLoc());
16732     DeclRefExpr *Ref = nullptr;
16733     if (!VD && !CurContext->isDependentContext()) {
16734       if (TopDVar.CKind == OMPC_lastprivate) {
16735         Ref = TopDVar.PrivateCopy;
16736       } else {
16737         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16738         if (!isOpenMPCapturedDecl(D))
16739           ExprCaptures.push_back(Ref->getDecl());
16740       }
16741     }
16742     if (!IsImplicitClause)
16743       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16744     Vars.push_back((VD || CurContext->isDependentContext())
16745                        ? RefExpr->IgnoreParens()
16746                        : Ref);
16747     PrivateCopies.push_back(VDPrivateRefExpr);
16748     Inits.push_back(VDInitRefExpr);
16749   }
16750 
16751   if (Vars.empty())
16752     return nullptr;
16753 
16754   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16755                                        Vars, PrivateCopies, Inits,
16756                                        buildPreInits(Context, ExprCaptures));
16757 }
16758 
16759 OMPClause *Sema::ActOnOpenMPLastprivateClause(
16760     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
16761     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
16762     SourceLocation LParenLoc, SourceLocation EndLoc) {
16763   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
16764     assert(ColonLoc.isValid() && "Colon location must be valid.");
16765     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
16766         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
16767                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
16768         << getOpenMPClauseName(OMPC_lastprivate);
16769     return nullptr;
16770   }
16771 
16772   SmallVector<Expr *, 8> Vars;
16773   SmallVector<Expr *, 8> SrcExprs;
16774   SmallVector<Expr *, 8> DstExprs;
16775   SmallVector<Expr *, 8> AssignmentOps;
16776   SmallVector<Decl *, 4> ExprCaptures;
16777   SmallVector<Expr *, 4> ExprPostUpdates;
16778   for (Expr *RefExpr : VarList) {
16779     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16780     SourceLocation ELoc;
16781     SourceRange ERange;
16782     Expr *SimpleRefExpr = RefExpr;
16783     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16784     if (Res.second) {
16785       // It will be analyzed later.
16786       Vars.push_back(RefExpr);
16787       SrcExprs.push_back(nullptr);
16788       DstExprs.push_back(nullptr);
16789       AssignmentOps.push_back(nullptr);
16790     }
16791     ValueDecl *D = Res.first;
16792     if (!D)
16793       continue;
16794 
16795     QualType Type = D->getType();
16796     auto *VD = dyn_cast<VarDecl>(D);
16797 
16798     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
16799     //  A variable that appears in a lastprivate clause must not have an
16800     //  incomplete type or a reference type.
16801     if (RequireCompleteType(ELoc, Type,
16802                             diag::err_omp_lastprivate_incomplete_type))
16803       continue;
16804     Type = Type.getNonReferenceType();
16805 
16806     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16807     // A variable that is privatized must not have a const-qualified type
16808     // unless it is of class type with a mutable member. This restriction does
16809     // not apply to the firstprivate clause.
16810     //
16811     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
16812     // A variable that appears in a lastprivate clause must not have a
16813     // const-qualified type unless it is of class type with a mutable member.
16814     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
16815       continue;
16816 
16817     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
16818     // A list item that appears in a lastprivate clause with the conditional
16819     // modifier must be a scalar variable.
16820     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
16821       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
16822       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16823                                VarDecl::DeclarationOnly;
16824       Diag(D->getLocation(),
16825            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16826           << D;
16827       continue;
16828     }
16829 
16830     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16831     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16832     // in a Construct]
16833     //  Variables with the predetermined data-sharing attributes may not be
16834     //  listed in data-sharing attributes clauses, except for the cases
16835     //  listed below.
16836     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16837     // A list item may appear in a firstprivate or lastprivate clause but not
16838     // both.
16839     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16840     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
16841         (isOpenMPDistributeDirective(CurrDir) ||
16842          DVar.CKind != OMPC_firstprivate) &&
16843         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
16844       Diag(ELoc, diag::err_omp_wrong_dsa)
16845           << getOpenMPClauseName(DVar.CKind)
16846           << getOpenMPClauseName(OMPC_lastprivate);
16847       reportOriginalDsa(*this, DSAStack, D, DVar);
16848       continue;
16849     }
16850 
16851     // OpenMP [2.14.3.5, Restrictions, p.2]
16852     // A list item that is private within a parallel region, or that appears in
16853     // the reduction clause of a parallel construct, must not appear in a
16854     // lastprivate clause on a worksharing construct if any of the corresponding
16855     // worksharing regions ever binds to any of the corresponding parallel
16856     // regions.
16857     DSAStackTy::DSAVarData TopDVar = DVar;
16858     if (isOpenMPWorksharingDirective(CurrDir) &&
16859         !isOpenMPParallelDirective(CurrDir) &&
16860         !isOpenMPTeamsDirective(CurrDir)) {
16861       DVar = DSAStack->getImplicitDSA(D, true);
16862       if (DVar.CKind != OMPC_shared) {
16863         Diag(ELoc, diag::err_omp_required_access)
16864             << getOpenMPClauseName(OMPC_lastprivate)
16865             << getOpenMPClauseName(OMPC_shared);
16866         reportOriginalDsa(*this, DSAStack, D, DVar);
16867         continue;
16868       }
16869     }
16870 
16871     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
16872     //  A variable of class type (or array thereof) that appears in a
16873     //  lastprivate clause requires an accessible, unambiguous default
16874     //  constructor for the class type, unless the list item is also specified
16875     //  in a firstprivate clause.
16876     //  A variable of class type (or array thereof) that appears in a
16877     //  lastprivate clause requires an accessible, unambiguous copy assignment
16878     //  operator for the class type.
16879     Type = Context.getBaseElementType(Type).getNonReferenceType();
16880     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
16881                                   Type.getUnqualifiedType(), ".lastprivate.src",
16882                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16883     DeclRefExpr *PseudoSrcExpr =
16884         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
16885     VarDecl *DstVD =
16886         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
16887                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16888     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16889     // For arrays generate assignment operation for single element and replace
16890     // it by the original array element in CodeGen.
16891     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
16892                                          PseudoDstExpr, PseudoSrcExpr);
16893     if (AssignmentOp.isInvalid())
16894       continue;
16895     AssignmentOp =
16896         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16897     if (AssignmentOp.isInvalid())
16898       continue;
16899 
16900     DeclRefExpr *Ref = nullptr;
16901     if (!VD && !CurContext->isDependentContext()) {
16902       if (TopDVar.CKind == OMPC_firstprivate) {
16903         Ref = TopDVar.PrivateCopy;
16904       } else {
16905         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16906         if (!isOpenMPCapturedDecl(D))
16907           ExprCaptures.push_back(Ref->getDecl());
16908       }
16909       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
16910           (!isOpenMPCapturedDecl(D) &&
16911            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
16912         ExprResult RefRes = DefaultLvalueConversion(Ref);
16913         if (!RefRes.isUsable())
16914           continue;
16915         ExprResult PostUpdateRes =
16916             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16917                        RefRes.get());
16918         if (!PostUpdateRes.isUsable())
16919           continue;
16920         ExprPostUpdates.push_back(
16921             IgnoredValueConversions(PostUpdateRes.get()).get());
16922       }
16923     }
16924     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
16925     Vars.push_back((VD || CurContext->isDependentContext())
16926                        ? RefExpr->IgnoreParens()
16927                        : Ref);
16928     SrcExprs.push_back(PseudoSrcExpr);
16929     DstExprs.push_back(PseudoDstExpr);
16930     AssignmentOps.push_back(AssignmentOp.get());
16931   }
16932 
16933   if (Vars.empty())
16934     return nullptr;
16935 
16936   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16937                                       Vars, SrcExprs, DstExprs, AssignmentOps,
16938                                       LPKind, LPKindLoc, ColonLoc,
16939                                       buildPreInits(Context, ExprCaptures),
16940                                       buildPostUpdate(*this, ExprPostUpdates));
16941 }
16942 
16943 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
16944                                          SourceLocation StartLoc,
16945                                          SourceLocation LParenLoc,
16946                                          SourceLocation EndLoc) {
16947   SmallVector<Expr *, 8> Vars;
16948   for (Expr *RefExpr : VarList) {
16949     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16950     SourceLocation ELoc;
16951     SourceRange ERange;
16952     Expr *SimpleRefExpr = RefExpr;
16953     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16954     if (Res.second) {
16955       // It will be analyzed later.
16956       Vars.push_back(RefExpr);
16957     }
16958     ValueDecl *D = Res.first;
16959     if (!D)
16960       continue;
16961 
16962     auto *VD = dyn_cast<VarDecl>(D);
16963     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16964     // in a Construct]
16965     //  Variables with the predetermined data-sharing attributes may not be
16966     //  listed in data-sharing attributes clauses, except for the cases
16967     //  listed below. For these exceptions only, listing a predetermined
16968     //  variable in a data-sharing attribute clause is allowed and overrides
16969     //  the variable's predetermined data-sharing attributes.
16970     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16971     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
16972         DVar.RefExpr) {
16973       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16974                                           << getOpenMPClauseName(OMPC_shared);
16975       reportOriginalDsa(*this, DSAStack, D, DVar);
16976       continue;
16977     }
16978 
16979     DeclRefExpr *Ref = nullptr;
16980     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
16981       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16982     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
16983     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
16984                        ? RefExpr->IgnoreParens()
16985                        : Ref);
16986   }
16987 
16988   if (Vars.empty())
16989     return nullptr;
16990 
16991   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
16992 }
16993 
16994 namespace {
16995 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
16996   DSAStackTy *Stack;
16997 
16998 public:
16999   bool VisitDeclRefExpr(DeclRefExpr *E) {
17000     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
17001       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
17002       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
17003         return false;
17004       if (DVar.CKind != OMPC_unknown)
17005         return true;
17006       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
17007           VD,
17008           [](OpenMPClauseKind C, bool AppliedToPointee) {
17009             return isOpenMPPrivate(C) && !AppliedToPointee;
17010           },
17011           [](OpenMPDirectiveKind) { return true; },
17012           /*FromParent=*/true);
17013       return DVarPrivate.CKind != OMPC_unknown;
17014     }
17015     return false;
17016   }
17017   bool VisitStmt(Stmt *S) {
17018     for (Stmt *Child : S->children()) {
17019       if (Child && Visit(Child))
17020         return true;
17021     }
17022     return false;
17023   }
17024   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
17025 };
17026 } // namespace
17027 
17028 namespace {
17029 // Transform MemberExpression for specified FieldDecl of current class to
17030 // DeclRefExpr to specified OMPCapturedExprDecl.
17031 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
17032   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
17033   ValueDecl *Field = nullptr;
17034   DeclRefExpr *CapturedExpr = nullptr;
17035 
17036 public:
17037   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
17038       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
17039 
17040   ExprResult TransformMemberExpr(MemberExpr *E) {
17041     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
17042         E->getMemberDecl() == Field) {
17043       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
17044       return CapturedExpr;
17045     }
17046     return BaseTransform::TransformMemberExpr(E);
17047   }
17048   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
17049 };
17050 } // namespace
17051 
17052 template <typename T, typename U>
17053 static T filterLookupForUDReductionAndMapper(
17054     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
17055   for (U &Set : Lookups) {
17056     for (auto *D : Set) {
17057       if (T Res = Gen(cast<ValueDecl>(D)))
17058         return Res;
17059     }
17060   }
17061   return T();
17062 }
17063 
17064 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
17065   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
17066 
17067   for (auto RD : D->redecls()) {
17068     // Don't bother with extra checks if we already know this one isn't visible.
17069     if (RD == D)
17070       continue;
17071 
17072     auto ND = cast<NamedDecl>(RD);
17073     if (LookupResult::isVisible(SemaRef, ND))
17074       return ND;
17075   }
17076 
17077   return nullptr;
17078 }
17079 
17080 static void
17081 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
17082                         SourceLocation Loc, QualType Ty,
17083                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
17084   // Find all of the associated namespaces and classes based on the
17085   // arguments we have.
17086   Sema::AssociatedNamespaceSet AssociatedNamespaces;
17087   Sema::AssociatedClassSet AssociatedClasses;
17088   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
17089   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
17090                                              AssociatedClasses);
17091 
17092   // C++ [basic.lookup.argdep]p3:
17093   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
17094   //   and let Y be the lookup set produced by argument dependent
17095   //   lookup (defined as follows). If X contains [...] then Y is
17096   //   empty. Otherwise Y is the set of declarations found in the
17097   //   namespaces associated with the argument types as described
17098   //   below. The set of declarations found by the lookup of the name
17099   //   is the union of X and Y.
17100   //
17101   // Here, we compute Y and add its members to the overloaded
17102   // candidate set.
17103   for (auto *NS : AssociatedNamespaces) {
17104     //   When considering an associated namespace, the lookup is the
17105     //   same as the lookup performed when the associated namespace is
17106     //   used as a qualifier (3.4.3.2) except that:
17107     //
17108     //     -- Any using-directives in the associated namespace are
17109     //        ignored.
17110     //
17111     //     -- Any namespace-scope friend functions declared in
17112     //        associated classes are visible within their respective
17113     //        namespaces even if they are not visible during an ordinary
17114     //        lookup (11.4).
17115     DeclContext::lookup_result R = NS->lookup(Id.getName());
17116     for (auto *D : R) {
17117       auto *Underlying = D;
17118       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
17119         Underlying = USD->getTargetDecl();
17120 
17121       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
17122           !isa<OMPDeclareMapperDecl>(Underlying))
17123         continue;
17124 
17125       if (!SemaRef.isVisible(D)) {
17126         D = findAcceptableDecl(SemaRef, D);
17127         if (!D)
17128           continue;
17129         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
17130           Underlying = USD->getTargetDecl();
17131       }
17132       Lookups.emplace_back();
17133       Lookups.back().addDecl(Underlying);
17134     }
17135   }
17136 }
17137 
17138 static ExprResult
17139 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
17140                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
17141                          const DeclarationNameInfo &ReductionId, QualType Ty,
17142                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
17143   if (ReductionIdScopeSpec.isInvalid())
17144     return ExprError();
17145   SmallVector<UnresolvedSet<8>, 4> Lookups;
17146   if (S) {
17147     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
17148     Lookup.suppressDiagnostics();
17149     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
17150       NamedDecl *D = Lookup.getRepresentativeDecl();
17151       do {
17152         S = S->getParent();
17153       } while (S && !S->isDeclScope(D));
17154       if (S)
17155         S = S->getParent();
17156       Lookups.emplace_back();
17157       Lookups.back().append(Lookup.begin(), Lookup.end());
17158       Lookup.clear();
17159     }
17160   } else if (auto *ULE =
17161                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
17162     Lookups.push_back(UnresolvedSet<8>());
17163     Decl *PrevD = nullptr;
17164     for (NamedDecl *D : ULE->decls()) {
17165       if (D == PrevD)
17166         Lookups.push_back(UnresolvedSet<8>());
17167       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
17168         Lookups.back().addDecl(DRD);
17169       PrevD = D;
17170     }
17171   }
17172   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
17173       Ty->isInstantiationDependentType() ||
17174       Ty->containsUnexpandedParameterPack() ||
17175       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
17176         return !D->isInvalidDecl() &&
17177                (D->getType()->isDependentType() ||
17178                 D->getType()->isInstantiationDependentType() ||
17179                 D->getType()->containsUnexpandedParameterPack());
17180       })) {
17181     UnresolvedSet<8> ResSet;
17182     for (const UnresolvedSet<8> &Set : Lookups) {
17183       if (Set.empty())
17184         continue;
17185       ResSet.append(Set.begin(), Set.end());
17186       // The last item marks the end of all declarations at the specified scope.
17187       ResSet.addDecl(Set[Set.size() - 1]);
17188     }
17189     return UnresolvedLookupExpr::Create(
17190         SemaRef.Context, /*NamingClass=*/nullptr,
17191         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
17192         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
17193   }
17194   // Lookup inside the classes.
17195   // C++ [over.match.oper]p3:
17196   //   For a unary operator @ with an operand of a type whose
17197   //   cv-unqualified version is T1, and for a binary operator @ with
17198   //   a left operand of a type whose cv-unqualified version is T1 and
17199   //   a right operand of a type whose cv-unqualified version is T2,
17200   //   three sets of candidate functions, designated member
17201   //   candidates, non-member candidates and built-in candidates, are
17202   //   constructed as follows:
17203   //     -- If T1 is a complete class type or a class currently being
17204   //        defined, the set of member candidates is the result of the
17205   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
17206   //        the set of member candidates is empty.
17207   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
17208   Lookup.suppressDiagnostics();
17209   if (const auto *TyRec = Ty->getAs<RecordType>()) {
17210     // Complete the type if it can be completed.
17211     // If the type is neither complete nor being defined, bail out now.
17212     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
17213         TyRec->getDecl()->getDefinition()) {
17214       Lookup.clear();
17215       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
17216       if (Lookup.empty()) {
17217         Lookups.emplace_back();
17218         Lookups.back().append(Lookup.begin(), Lookup.end());
17219       }
17220     }
17221   }
17222   // Perform ADL.
17223   if (SemaRef.getLangOpts().CPlusPlus)
17224     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
17225   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17226           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
17227             if (!D->isInvalidDecl() &&
17228                 SemaRef.Context.hasSameType(D->getType(), Ty))
17229               return D;
17230             return nullptr;
17231           }))
17232     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
17233                                     VK_LValue, Loc);
17234   if (SemaRef.getLangOpts().CPlusPlus) {
17235     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17236             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
17237               if (!D->isInvalidDecl() &&
17238                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
17239                   !Ty.isMoreQualifiedThan(D->getType()))
17240                 return D;
17241               return nullptr;
17242             })) {
17243       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
17244                          /*DetectVirtual=*/false);
17245       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
17246         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
17247                 VD->getType().getUnqualifiedType()))) {
17248           if (SemaRef.CheckBaseClassAccess(
17249                   Loc, VD->getType(), Ty, Paths.front(),
17250                   /*DiagID=*/0) != Sema::AR_inaccessible) {
17251             SemaRef.BuildBasePathArray(Paths, BasePath);
17252             return SemaRef.BuildDeclRefExpr(
17253                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
17254           }
17255         }
17256       }
17257     }
17258   }
17259   if (ReductionIdScopeSpec.isSet()) {
17260     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
17261         << Ty << Range;
17262     return ExprError();
17263   }
17264   return ExprEmpty();
17265 }
17266 
17267 namespace {
17268 /// Data for the reduction-based clauses.
17269 struct ReductionData {
17270   /// List of original reduction items.
17271   SmallVector<Expr *, 8> Vars;
17272   /// List of private copies of the reduction items.
17273   SmallVector<Expr *, 8> Privates;
17274   /// LHS expressions for the reduction_op expressions.
17275   SmallVector<Expr *, 8> LHSs;
17276   /// RHS expressions for the reduction_op expressions.
17277   SmallVector<Expr *, 8> RHSs;
17278   /// Reduction operation expression.
17279   SmallVector<Expr *, 8> ReductionOps;
17280   /// inscan copy operation expressions.
17281   SmallVector<Expr *, 8> InscanCopyOps;
17282   /// inscan copy temp array expressions for prefix sums.
17283   SmallVector<Expr *, 8> InscanCopyArrayTemps;
17284   /// inscan copy temp array element expressions for prefix sums.
17285   SmallVector<Expr *, 8> InscanCopyArrayElems;
17286   /// Taskgroup descriptors for the corresponding reduction items in
17287   /// in_reduction clauses.
17288   SmallVector<Expr *, 8> TaskgroupDescriptors;
17289   /// List of captures for clause.
17290   SmallVector<Decl *, 4> ExprCaptures;
17291   /// List of postupdate expressions.
17292   SmallVector<Expr *, 4> ExprPostUpdates;
17293   /// Reduction modifier.
17294   unsigned RedModifier = 0;
17295   ReductionData() = delete;
17296   /// Reserves required memory for the reduction data.
17297   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
17298     Vars.reserve(Size);
17299     Privates.reserve(Size);
17300     LHSs.reserve(Size);
17301     RHSs.reserve(Size);
17302     ReductionOps.reserve(Size);
17303     if (RedModifier == OMPC_REDUCTION_inscan) {
17304       InscanCopyOps.reserve(Size);
17305       InscanCopyArrayTemps.reserve(Size);
17306       InscanCopyArrayElems.reserve(Size);
17307     }
17308     TaskgroupDescriptors.reserve(Size);
17309     ExprCaptures.reserve(Size);
17310     ExprPostUpdates.reserve(Size);
17311   }
17312   /// Stores reduction item and reduction operation only (required for dependent
17313   /// reduction item).
17314   void push(Expr *Item, Expr *ReductionOp) {
17315     Vars.emplace_back(Item);
17316     Privates.emplace_back(nullptr);
17317     LHSs.emplace_back(nullptr);
17318     RHSs.emplace_back(nullptr);
17319     ReductionOps.emplace_back(ReductionOp);
17320     TaskgroupDescriptors.emplace_back(nullptr);
17321     if (RedModifier == OMPC_REDUCTION_inscan) {
17322       InscanCopyOps.push_back(nullptr);
17323       InscanCopyArrayTemps.push_back(nullptr);
17324       InscanCopyArrayElems.push_back(nullptr);
17325     }
17326   }
17327   /// Stores reduction data.
17328   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
17329             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
17330             Expr *CopyArrayElem) {
17331     Vars.emplace_back(Item);
17332     Privates.emplace_back(Private);
17333     LHSs.emplace_back(LHS);
17334     RHSs.emplace_back(RHS);
17335     ReductionOps.emplace_back(ReductionOp);
17336     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
17337     if (RedModifier == OMPC_REDUCTION_inscan) {
17338       InscanCopyOps.push_back(CopyOp);
17339       InscanCopyArrayTemps.push_back(CopyArrayTemp);
17340       InscanCopyArrayElems.push_back(CopyArrayElem);
17341     } else {
17342       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
17343              CopyArrayElem == nullptr &&
17344              "Copy operation must be used for inscan reductions only.");
17345     }
17346   }
17347 };
17348 } // namespace
17349 
17350 static bool checkOMPArraySectionConstantForReduction(
17351     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
17352     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
17353   const Expr *Length = OASE->getLength();
17354   if (Length == nullptr) {
17355     // For array sections of the form [1:] or [:], we would need to analyze
17356     // the lower bound...
17357     if (OASE->getColonLocFirst().isValid())
17358       return false;
17359 
17360     // This is an array subscript which has implicit length 1!
17361     SingleElement = true;
17362     ArraySizes.push_back(llvm::APSInt::get(1));
17363   } else {
17364     Expr::EvalResult Result;
17365     if (!Length->EvaluateAsInt(Result, Context))
17366       return false;
17367 
17368     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
17369     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
17370     ArraySizes.push_back(ConstantLengthValue);
17371   }
17372 
17373   // Get the base of this array section and walk up from there.
17374   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
17375 
17376   // We require length = 1 for all array sections except the right-most to
17377   // guarantee that the memory region is contiguous and has no holes in it.
17378   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
17379     Length = TempOASE->getLength();
17380     if (Length == nullptr) {
17381       // For array sections of the form [1:] or [:], we would need to analyze
17382       // the lower bound...
17383       if (OASE->getColonLocFirst().isValid())
17384         return false;
17385 
17386       // This is an array subscript which has implicit length 1!
17387       ArraySizes.push_back(llvm::APSInt::get(1));
17388     } else {
17389       Expr::EvalResult Result;
17390       if (!Length->EvaluateAsInt(Result, Context))
17391         return false;
17392 
17393       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
17394       if (ConstantLengthValue.getSExtValue() != 1)
17395         return false;
17396 
17397       ArraySizes.push_back(ConstantLengthValue);
17398     }
17399     Base = TempOASE->getBase()->IgnoreParenImpCasts();
17400   }
17401 
17402   // If we have a single element, we don't need to add the implicit lengths.
17403   if (!SingleElement) {
17404     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
17405       // Has implicit length 1!
17406       ArraySizes.push_back(llvm::APSInt::get(1));
17407       Base = TempASE->getBase()->IgnoreParenImpCasts();
17408     }
17409   }
17410 
17411   // This array section can be privatized as a single value or as a constant
17412   // sized array.
17413   return true;
17414 }
17415 
17416 static BinaryOperatorKind
17417 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
17418   if (BOK == BO_Add)
17419     return BO_AddAssign;
17420   if (BOK == BO_Mul)
17421     return BO_MulAssign;
17422   if (BOK == BO_And)
17423     return BO_AndAssign;
17424   if (BOK == BO_Or)
17425     return BO_OrAssign;
17426   if (BOK == BO_Xor)
17427     return BO_XorAssign;
17428   return BOK;
17429 }
17430 
17431 static bool actOnOMPReductionKindClause(
17432     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
17433     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17434     SourceLocation ColonLoc, SourceLocation EndLoc,
17435     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17436     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
17437   DeclarationName DN = ReductionId.getName();
17438   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
17439   BinaryOperatorKind BOK = BO_Comma;
17440 
17441   ASTContext &Context = S.Context;
17442   // OpenMP [2.14.3.6, reduction clause]
17443   // C
17444   // reduction-identifier is either an identifier or one of the following
17445   // operators: +, -, *,  &, |, ^, && and ||
17446   // C++
17447   // reduction-identifier is either an id-expression or one of the following
17448   // operators: +, -, *, &, |, ^, && and ||
17449   switch (OOK) {
17450   case OO_Plus:
17451   case OO_Minus:
17452     BOK = BO_Add;
17453     break;
17454   case OO_Star:
17455     BOK = BO_Mul;
17456     break;
17457   case OO_Amp:
17458     BOK = BO_And;
17459     break;
17460   case OO_Pipe:
17461     BOK = BO_Or;
17462     break;
17463   case OO_Caret:
17464     BOK = BO_Xor;
17465     break;
17466   case OO_AmpAmp:
17467     BOK = BO_LAnd;
17468     break;
17469   case OO_PipePipe:
17470     BOK = BO_LOr;
17471     break;
17472   case OO_New:
17473   case OO_Delete:
17474   case OO_Array_New:
17475   case OO_Array_Delete:
17476   case OO_Slash:
17477   case OO_Percent:
17478   case OO_Tilde:
17479   case OO_Exclaim:
17480   case OO_Equal:
17481   case OO_Less:
17482   case OO_Greater:
17483   case OO_LessEqual:
17484   case OO_GreaterEqual:
17485   case OO_PlusEqual:
17486   case OO_MinusEqual:
17487   case OO_StarEqual:
17488   case OO_SlashEqual:
17489   case OO_PercentEqual:
17490   case OO_CaretEqual:
17491   case OO_AmpEqual:
17492   case OO_PipeEqual:
17493   case OO_LessLess:
17494   case OO_GreaterGreater:
17495   case OO_LessLessEqual:
17496   case OO_GreaterGreaterEqual:
17497   case OO_EqualEqual:
17498   case OO_ExclaimEqual:
17499   case OO_Spaceship:
17500   case OO_PlusPlus:
17501   case OO_MinusMinus:
17502   case OO_Comma:
17503   case OO_ArrowStar:
17504   case OO_Arrow:
17505   case OO_Call:
17506   case OO_Subscript:
17507   case OO_Conditional:
17508   case OO_Coawait:
17509   case NUM_OVERLOADED_OPERATORS:
17510     llvm_unreachable("Unexpected reduction identifier");
17511   case OO_None:
17512     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
17513       if (II->isStr("max"))
17514         BOK = BO_GT;
17515       else if (II->isStr("min"))
17516         BOK = BO_LT;
17517     }
17518     break;
17519   }
17520   SourceRange ReductionIdRange;
17521   if (ReductionIdScopeSpec.isValid())
17522     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
17523   else
17524     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
17525   ReductionIdRange.setEnd(ReductionId.getEndLoc());
17526 
17527   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
17528   bool FirstIter = true;
17529   for (Expr *RefExpr : VarList) {
17530     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
17531     // OpenMP [2.1, C/C++]
17532     //  A list item is a variable or array section, subject to the restrictions
17533     //  specified in Section 2.4 on page 42 and in each of the sections
17534     // describing clauses and directives for which a list appears.
17535     // OpenMP  [2.14.3.3, Restrictions, p.1]
17536     //  A variable that is part of another variable (as an array or
17537     //  structure element) cannot appear in a private clause.
17538     if (!FirstIter && IR != ER)
17539       ++IR;
17540     FirstIter = false;
17541     SourceLocation ELoc;
17542     SourceRange ERange;
17543     Expr *SimpleRefExpr = RefExpr;
17544     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
17545                               /*AllowArraySection=*/true);
17546     if (Res.second) {
17547       // Try to find 'declare reduction' corresponding construct before using
17548       // builtin/overloaded operators.
17549       QualType Type = Context.DependentTy;
17550       CXXCastPath BasePath;
17551       ExprResult DeclareReductionRef = buildDeclareReductionRef(
17552           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17553           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17554       Expr *ReductionOp = nullptr;
17555       if (S.CurContext->isDependentContext() &&
17556           (DeclareReductionRef.isUnset() ||
17557            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
17558         ReductionOp = DeclareReductionRef.get();
17559       // It will be analyzed later.
17560       RD.push(RefExpr, ReductionOp);
17561     }
17562     ValueDecl *D = Res.first;
17563     if (!D)
17564       continue;
17565 
17566     Expr *TaskgroupDescriptor = nullptr;
17567     QualType Type;
17568     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
17569     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
17570     if (ASE) {
17571       Type = ASE->getType().getNonReferenceType();
17572     } else if (OASE) {
17573       QualType BaseType =
17574           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17575       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17576         Type = ATy->getElementType();
17577       else
17578         Type = BaseType->getPointeeType();
17579       Type = Type.getNonReferenceType();
17580     } else {
17581       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
17582     }
17583     auto *VD = dyn_cast<VarDecl>(D);
17584 
17585     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17586     //  A variable that appears in a private clause must not have an incomplete
17587     //  type or a reference type.
17588     if (S.RequireCompleteType(ELoc, D->getType(),
17589                               diag::err_omp_reduction_incomplete_type))
17590       continue;
17591     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17592     // A list item that appears in a reduction clause must not be
17593     // const-qualified.
17594     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
17595                                   /*AcceptIfMutable*/ false, ASE || OASE))
17596       continue;
17597 
17598     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
17599     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
17600     //  If a list-item is a reference type then it must bind to the same object
17601     //  for all threads of the team.
17602     if (!ASE && !OASE) {
17603       if (VD) {
17604         VarDecl *VDDef = VD->getDefinition();
17605         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
17606           DSARefChecker Check(Stack);
17607           if (Check.Visit(VDDef->getInit())) {
17608             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
17609                 << getOpenMPClauseName(ClauseKind) << ERange;
17610             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
17611             continue;
17612           }
17613         }
17614       }
17615 
17616       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
17617       // in a Construct]
17618       //  Variables with the predetermined data-sharing attributes may not be
17619       //  listed in data-sharing attributes clauses, except for the cases
17620       //  listed below. For these exceptions only, listing a predetermined
17621       //  variable in a data-sharing attribute clause is allowed and overrides
17622       //  the variable's predetermined data-sharing attributes.
17623       // OpenMP [2.14.3.6, Restrictions, p.3]
17624       //  Any number of reduction clauses can be specified on the directive,
17625       //  but a list item can appear only once in the reduction clauses for that
17626       //  directive.
17627       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17628       if (DVar.CKind == OMPC_reduction) {
17629         S.Diag(ELoc, diag::err_omp_once_referenced)
17630             << getOpenMPClauseName(ClauseKind);
17631         if (DVar.RefExpr)
17632           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
17633         continue;
17634       }
17635       if (DVar.CKind != OMPC_unknown) {
17636         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17637             << getOpenMPClauseName(DVar.CKind)
17638             << getOpenMPClauseName(OMPC_reduction);
17639         reportOriginalDsa(S, Stack, D, DVar);
17640         continue;
17641       }
17642 
17643       // OpenMP [2.14.3.6, Restrictions, p.1]
17644       //  A list item that appears in a reduction clause of a worksharing
17645       //  construct must be shared in the parallel regions to which any of the
17646       //  worksharing regions arising from the worksharing construct bind.
17647       if (isOpenMPWorksharingDirective(CurrDir) &&
17648           !isOpenMPParallelDirective(CurrDir) &&
17649           !isOpenMPTeamsDirective(CurrDir)) {
17650         DVar = Stack->getImplicitDSA(D, true);
17651         if (DVar.CKind != OMPC_shared) {
17652           S.Diag(ELoc, diag::err_omp_required_access)
17653               << getOpenMPClauseName(OMPC_reduction)
17654               << getOpenMPClauseName(OMPC_shared);
17655           reportOriginalDsa(S, Stack, D, DVar);
17656           continue;
17657         }
17658       }
17659     } else {
17660       // Threadprivates cannot be shared between threads, so dignose if the base
17661       // is a threadprivate variable.
17662       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17663       if (DVar.CKind == OMPC_threadprivate) {
17664         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17665             << getOpenMPClauseName(DVar.CKind)
17666             << getOpenMPClauseName(OMPC_reduction);
17667         reportOriginalDsa(S, Stack, D, DVar);
17668         continue;
17669       }
17670     }
17671 
17672     // Try to find 'declare reduction' corresponding construct before using
17673     // builtin/overloaded operators.
17674     CXXCastPath BasePath;
17675     ExprResult DeclareReductionRef = buildDeclareReductionRef(
17676         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17677         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17678     if (DeclareReductionRef.isInvalid())
17679       continue;
17680     if (S.CurContext->isDependentContext() &&
17681         (DeclareReductionRef.isUnset() ||
17682          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
17683       RD.push(RefExpr, DeclareReductionRef.get());
17684       continue;
17685     }
17686     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
17687       // Not allowed reduction identifier is found.
17688       S.Diag(ReductionId.getBeginLoc(),
17689              diag::err_omp_unknown_reduction_identifier)
17690           << Type << ReductionIdRange;
17691       continue;
17692     }
17693 
17694     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17695     // The type of a list item that appears in a reduction clause must be valid
17696     // for the reduction-identifier. For a max or min reduction in C, the type
17697     // of the list item must be an allowed arithmetic data type: char, int,
17698     // float, double, or _Bool, possibly modified with long, short, signed, or
17699     // unsigned. For a max or min reduction in C++, the type of the list item
17700     // must be an allowed arithmetic data type: char, wchar_t, int, float,
17701     // double, or bool, possibly modified with long, short, signed, or unsigned.
17702     if (DeclareReductionRef.isUnset()) {
17703       if ((BOK == BO_GT || BOK == BO_LT) &&
17704           !(Type->isScalarType() ||
17705             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
17706         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
17707             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
17708         if (!ASE && !OASE) {
17709           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17710                                    VarDecl::DeclarationOnly;
17711           S.Diag(D->getLocation(),
17712                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17713               << D;
17714         }
17715         continue;
17716       }
17717       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
17718           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
17719         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
17720             << getOpenMPClauseName(ClauseKind);
17721         if (!ASE && !OASE) {
17722           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17723                                    VarDecl::DeclarationOnly;
17724           S.Diag(D->getLocation(),
17725                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17726               << D;
17727         }
17728         continue;
17729       }
17730     }
17731 
17732     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
17733     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
17734                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17735     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
17736                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17737     QualType PrivateTy = Type;
17738 
17739     // Try if we can determine constant lengths for all array sections and avoid
17740     // the VLA.
17741     bool ConstantLengthOASE = false;
17742     if (OASE) {
17743       bool SingleElement;
17744       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
17745       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
17746           Context, OASE, SingleElement, ArraySizes);
17747 
17748       // If we don't have a single element, we must emit a constant array type.
17749       if (ConstantLengthOASE && !SingleElement) {
17750         for (llvm::APSInt &Size : ArraySizes)
17751           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
17752                                                    ArrayType::Normal,
17753                                                    /*IndexTypeQuals=*/0);
17754       }
17755     }
17756 
17757     if ((OASE && !ConstantLengthOASE) ||
17758         (!OASE && !ASE &&
17759          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
17760       if (!Context.getTargetInfo().isVLASupported()) {
17761         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
17762           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17763           S.Diag(ELoc, diag::note_vla_unsupported);
17764           continue;
17765         } else {
17766           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17767           S.targetDiag(ELoc, diag::note_vla_unsupported);
17768         }
17769       }
17770       // For arrays/array sections only:
17771       // Create pseudo array type for private copy. The size for this array will
17772       // be generated during codegen.
17773       // For array subscripts or single variables Private Ty is the same as Type
17774       // (type of the variable or single array element).
17775       PrivateTy = Context.getVariableArrayType(
17776           Type,
17777           new (Context)
17778               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
17779           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
17780     } else if (!ASE && !OASE &&
17781                Context.getAsArrayType(D->getType().getNonReferenceType())) {
17782       PrivateTy = D->getType().getNonReferenceType();
17783     }
17784     // Private copy.
17785     VarDecl *PrivateVD =
17786         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17787                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17788                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17789     // Add initializer for private variable.
17790     Expr *Init = nullptr;
17791     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
17792     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
17793     if (DeclareReductionRef.isUsable()) {
17794       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
17795       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
17796       if (DRD->getInitializer()) {
17797         Init = DRDRef;
17798         RHSVD->setInit(DRDRef);
17799         RHSVD->setInitStyle(VarDecl::CallInit);
17800       }
17801     } else {
17802       switch (BOK) {
17803       case BO_Add:
17804       case BO_Xor:
17805       case BO_Or:
17806       case BO_LOr:
17807         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
17808         if (Type->isScalarType() || Type->isAnyComplexType())
17809           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
17810         break;
17811       case BO_Mul:
17812       case BO_LAnd:
17813         if (Type->isScalarType() || Type->isAnyComplexType()) {
17814           // '*' and '&&' reduction ops - initializer is '1'.
17815           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
17816         }
17817         break;
17818       case BO_And: {
17819         // '&' reduction op - initializer is '~0'.
17820         QualType OrigType = Type;
17821         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
17822           Type = ComplexTy->getElementType();
17823         if (Type->isRealFloatingType()) {
17824           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
17825               Context.getFloatTypeSemantics(Type));
17826           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17827                                          Type, ELoc);
17828         } else if (Type->isScalarType()) {
17829           uint64_t Size = Context.getTypeSize(Type);
17830           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
17831           llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
17832           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17833         }
17834         if (Init && OrigType->isAnyComplexType()) {
17835           // Init = 0xFFFF + 0xFFFFi;
17836           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
17837           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
17838         }
17839         Type = OrigType;
17840         break;
17841       }
17842       case BO_LT:
17843       case BO_GT: {
17844         // 'min' reduction op - initializer is 'Largest representable number in
17845         // the reduction list item type'.
17846         // 'max' reduction op - initializer is 'Least representable number in
17847         // the reduction list item type'.
17848         if (Type->isIntegerType() || Type->isPointerType()) {
17849           bool IsSigned = Type->hasSignedIntegerRepresentation();
17850           uint64_t Size = Context.getTypeSize(Type);
17851           QualType IntTy =
17852               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
17853           llvm::APInt InitValue =
17854               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
17855                                         : llvm::APInt::getMinValue(Size)
17856               : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
17857                              : llvm::APInt::getMaxValue(Size);
17858           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17859           if (Type->isPointerType()) {
17860             // Cast to pointer type.
17861             ExprResult CastExpr = S.BuildCStyleCastExpr(
17862                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
17863             if (CastExpr.isInvalid())
17864               continue;
17865             Init = CastExpr.get();
17866           }
17867         } else if (Type->isRealFloatingType()) {
17868           llvm::APFloat InitValue = llvm::APFloat::getLargest(
17869               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
17870           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17871                                          Type, ELoc);
17872         }
17873         break;
17874       }
17875       case BO_PtrMemD:
17876       case BO_PtrMemI:
17877       case BO_MulAssign:
17878       case BO_Div:
17879       case BO_Rem:
17880       case BO_Sub:
17881       case BO_Shl:
17882       case BO_Shr:
17883       case BO_LE:
17884       case BO_GE:
17885       case BO_EQ:
17886       case BO_NE:
17887       case BO_Cmp:
17888       case BO_AndAssign:
17889       case BO_XorAssign:
17890       case BO_OrAssign:
17891       case BO_Assign:
17892       case BO_AddAssign:
17893       case BO_SubAssign:
17894       case BO_DivAssign:
17895       case BO_RemAssign:
17896       case BO_ShlAssign:
17897       case BO_ShrAssign:
17898       case BO_Comma:
17899         llvm_unreachable("Unexpected reduction operation");
17900       }
17901     }
17902     if (Init && DeclareReductionRef.isUnset()) {
17903       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
17904       // Store initializer for single element in private copy. Will be used
17905       // during codegen.
17906       PrivateVD->setInit(RHSVD->getInit());
17907       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17908     } else if (!Init) {
17909       S.ActOnUninitializedDecl(RHSVD);
17910       // Store initializer for single element in private copy. Will be used
17911       // during codegen.
17912       PrivateVD->setInit(RHSVD->getInit());
17913       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17914     }
17915     if (RHSVD->isInvalidDecl())
17916       continue;
17917     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
17918       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
17919           << Type << ReductionIdRange;
17920       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17921                                VarDecl::DeclarationOnly;
17922       S.Diag(D->getLocation(),
17923              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17924           << D;
17925       continue;
17926     }
17927     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
17928     ExprResult ReductionOp;
17929     if (DeclareReductionRef.isUsable()) {
17930       QualType RedTy = DeclareReductionRef.get()->getType();
17931       QualType PtrRedTy = Context.getPointerType(RedTy);
17932       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
17933       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
17934       if (!BasePath.empty()) {
17935         LHS = S.DefaultLvalueConversion(LHS.get());
17936         RHS = S.DefaultLvalueConversion(RHS.get());
17937         LHS = ImplicitCastExpr::Create(
17938             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
17939             LHS.get()->getValueKind(), FPOptionsOverride());
17940         RHS = ImplicitCastExpr::Create(
17941             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
17942             RHS.get()->getValueKind(), FPOptionsOverride());
17943       }
17944       FunctionProtoType::ExtProtoInfo EPI;
17945       QualType Params[] = {PtrRedTy, PtrRedTy};
17946       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
17947       auto *OVE = new (Context) OpaqueValueExpr(
17948           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
17949           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
17950       Expr *Args[] = {LHS.get(), RHS.get()};
17951       ReductionOp =
17952           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
17953                            S.CurFPFeatureOverrides());
17954     } else {
17955       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
17956       if (Type->isRecordType() && CombBOK != BOK) {
17957         Sema::TentativeAnalysisScope Trap(S);
17958         ReductionOp =
17959             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17960                          CombBOK, LHSDRE, RHSDRE);
17961       }
17962       if (!ReductionOp.isUsable()) {
17963         ReductionOp =
17964             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
17965                          LHSDRE, RHSDRE);
17966         if (ReductionOp.isUsable()) {
17967           if (BOK != BO_LT && BOK != BO_GT) {
17968             ReductionOp =
17969                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17970                              BO_Assign, LHSDRE, ReductionOp.get());
17971           } else {
17972             auto *ConditionalOp = new (Context)
17973                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
17974                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
17975             ReductionOp =
17976                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17977                              BO_Assign, LHSDRE, ConditionalOp);
17978           }
17979         }
17980       }
17981       if (ReductionOp.isUsable())
17982         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
17983                                             /*DiscardedValue*/ false);
17984       if (!ReductionOp.isUsable())
17985         continue;
17986     }
17987 
17988     // Add copy operations for inscan reductions.
17989     // LHS = RHS;
17990     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
17991     if (ClauseKind == OMPC_reduction &&
17992         RD.RedModifier == OMPC_REDUCTION_inscan) {
17993       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
17994       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
17995                                RHS.get());
17996       if (!CopyOpRes.isUsable())
17997         continue;
17998       CopyOpRes =
17999           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
18000       if (!CopyOpRes.isUsable())
18001         continue;
18002       // For simd directive and simd-based directives in simd mode no need to
18003       // construct temp array, need just a single temp element.
18004       if (Stack->getCurrentDirective() == OMPD_simd ||
18005           (S.getLangOpts().OpenMPSimd &&
18006            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
18007         VarDecl *TempArrayVD =
18008             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
18009                          D->hasAttrs() ? &D->getAttrs() : nullptr);
18010         // Add a constructor to the temp decl.
18011         S.ActOnUninitializedDecl(TempArrayVD);
18012         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
18013       } else {
18014         // Build temp array for prefix sum.
18015         auto *Dim = new (S.Context)
18016             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
18017         QualType ArrayTy =
18018             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
18019                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
18020         VarDecl *TempArrayVD =
18021             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
18022                          D->hasAttrs() ? &D->getAttrs() : nullptr);
18023         // Add a constructor to the temp decl.
18024         S.ActOnUninitializedDecl(TempArrayVD);
18025         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
18026         TempArrayElem =
18027             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
18028         auto *Idx = new (S.Context)
18029             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
18030         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
18031                                                           ELoc, Idx, ELoc);
18032       }
18033     }
18034 
18035     // OpenMP [2.15.4.6, Restrictions, p.2]
18036     // A list item that appears in an in_reduction clause of a task construct
18037     // must appear in a task_reduction clause of a construct associated with a
18038     // taskgroup region that includes the participating task in its taskgroup
18039     // set. The construct associated with the innermost region that meets this
18040     // condition must specify the same reduction-identifier as the in_reduction
18041     // clause.
18042     if (ClauseKind == OMPC_in_reduction) {
18043       SourceRange ParentSR;
18044       BinaryOperatorKind ParentBOK;
18045       const Expr *ParentReductionOp = nullptr;
18046       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
18047       DSAStackTy::DSAVarData ParentBOKDSA =
18048           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
18049                                                   ParentBOKTD);
18050       DSAStackTy::DSAVarData ParentReductionOpDSA =
18051           Stack->getTopMostTaskgroupReductionData(
18052               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
18053       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
18054       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
18055       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
18056           (DeclareReductionRef.isUsable() && IsParentBOK) ||
18057           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
18058         bool EmitError = true;
18059         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
18060           llvm::FoldingSetNodeID RedId, ParentRedId;
18061           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
18062           DeclareReductionRef.get()->Profile(RedId, Context,
18063                                              /*Canonical=*/true);
18064           EmitError = RedId != ParentRedId;
18065         }
18066         if (EmitError) {
18067           S.Diag(ReductionId.getBeginLoc(),
18068                  diag::err_omp_reduction_identifier_mismatch)
18069               << ReductionIdRange << RefExpr->getSourceRange();
18070           S.Diag(ParentSR.getBegin(),
18071                  diag::note_omp_previous_reduction_identifier)
18072               << ParentSR
18073               << (IsParentBOK ? ParentBOKDSA.RefExpr
18074                               : ParentReductionOpDSA.RefExpr)
18075                      ->getSourceRange();
18076           continue;
18077         }
18078       }
18079       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
18080     }
18081 
18082     DeclRefExpr *Ref = nullptr;
18083     Expr *VarsExpr = RefExpr->IgnoreParens();
18084     if (!VD && !S.CurContext->isDependentContext()) {
18085       if (ASE || OASE) {
18086         TransformExprToCaptures RebuildToCapture(S, D);
18087         VarsExpr =
18088             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
18089         Ref = RebuildToCapture.getCapturedExpr();
18090       } else {
18091         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
18092       }
18093       if (!S.isOpenMPCapturedDecl(D)) {
18094         RD.ExprCaptures.emplace_back(Ref->getDecl());
18095         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
18096           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
18097           if (!RefRes.isUsable())
18098             continue;
18099           ExprResult PostUpdateRes =
18100               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
18101                            RefRes.get());
18102           if (!PostUpdateRes.isUsable())
18103             continue;
18104           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
18105               Stack->getCurrentDirective() == OMPD_taskgroup) {
18106             S.Diag(RefExpr->getExprLoc(),
18107                    diag::err_omp_reduction_non_addressable_expression)
18108                 << RefExpr->getSourceRange();
18109             continue;
18110           }
18111           RD.ExprPostUpdates.emplace_back(
18112               S.IgnoredValueConversions(PostUpdateRes.get()).get());
18113         }
18114       }
18115     }
18116     // All reduction items are still marked as reduction (to do not increase
18117     // code base size).
18118     unsigned Modifier = RD.RedModifier;
18119     // Consider task_reductions as reductions with task modifier. Required for
18120     // correct analysis of in_reduction clauses.
18121     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
18122       Modifier = OMPC_REDUCTION_task;
18123     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
18124                   ASE || OASE);
18125     if (Modifier == OMPC_REDUCTION_task &&
18126         (CurrDir == OMPD_taskgroup ||
18127          ((isOpenMPParallelDirective(CurrDir) ||
18128            isOpenMPWorksharingDirective(CurrDir)) &&
18129           !isOpenMPSimdDirective(CurrDir)))) {
18130       if (DeclareReductionRef.isUsable())
18131         Stack->addTaskgroupReductionData(D, ReductionIdRange,
18132                                          DeclareReductionRef.get());
18133       else
18134         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
18135     }
18136     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
18137             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
18138             TempArrayElem.get());
18139   }
18140   return RD.Vars.empty();
18141 }
18142 
18143 OMPClause *Sema::ActOnOpenMPReductionClause(
18144     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
18145     SourceLocation StartLoc, SourceLocation LParenLoc,
18146     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
18147     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18148     ArrayRef<Expr *> UnresolvedReductions) {
18149   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
18150     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
18151         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
18152                                    /*Last=*/OMPC_REDUCTION_unknown)
18153         << getOpenMPClauseName(OMPC_reduction);
18154     return nullptr;
18155   }
18156   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
18157   // A reduction clause with the inscan reduction-modifier may only appear on a
18158   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
18159   // construct, a parallel worksharing-loop construct or a parallel
18160   // worksharing-loop SIMD construct.
18161   if (Modifier == OMPC_REDUCTION_inscan &&
18162       (DSAStack->getCurrentDirective() != OMPD_for &&
18163        DSAStack->getCurrentDirective() != OMPD_for_simd &&
18164        DSAStack->getCurrentDirective() != OMPD_simd &&
18165        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
18166        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
18167     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
18168     return nullptr;
18169   }
18170 
18171   ReductionData RD(VarList.size(), Modifier);
18172   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
18173                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
18174                                   ReductionIdScopeSpec, ReductionId,
18175                                   UnresolvedReductions, RD))
18176     return nullptr;
18177 
18178   return OMPReductionClause::Create(
18179       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
18180       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
18181       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
18182       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
18183       buildPreInits(Context, RD.ExprCaptures),
18184       buildPostUpdate(*this, RD.ExprPostUpdates));
18185 }
18186 
18187 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
18188     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
18189     SourceLocation ColonLoc, SourceLocation EndLoc,
18190     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18191     ArrayRef<Expr *> UnresolvedReductions) {
18192   ReductionData RD(VarList.size());
18193   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
18194                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
18195                                   ReductionIdScopeSpec, ReductionId,
18196                                   UnresolvedReductions, RD))
18197     return nullptr;
18198 
18199   return OMPTaskReductionClause::Create(
18200       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
18201       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
18202       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
18203       buildPreInits(Context, RD.ExprCaptures),
18204       buildPostUpdate(*this, RD.ExprPostUpdates));
18205 }
18206 
18207 OMPClause *Sema::ActOnOpenMPInReductionClause(
18208     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
18209     SourceLocation ColonLoc, SourceLocation EndLoc,
18210     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
18211     ArrayRef<Expr *> UnresolvedReductions) {
18212   ReductionData RD(VarList.size());
18213   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
18214                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
18215                                   ReductionIdScopeSpec, ReductionId,
18216                                   UnresolvedReductions, RD))
18217     return nullptr;
18218 
18219   return OMPInReductionClause::Create(
18220       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
18221       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
18222       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
18223       buildPreInits(Context, RD.ExprCaptures),
18224       buildPostUpdate(*this, RD.ExprPostUpdates));
18225 }
18226 
18227 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
18228                                      SourceLocation LinLoc) {
18229   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
18230       LinKind == OMPC_LINEAR_unknown) {
18231     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
18232     return true;
18233   }
18234   return false;
18235 }
18236 
18237 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
18238                                  OpenMPLinearClauseKind LinKind, QualType Type,
18239                                  bool IsDeclareSimd) {
18240   const auto *VD = dyn_cast_or_null<VarDecl>(D);
18241   // A variable must not have an incomplete type or a reference type.
18242   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
18243     return true;
18244   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
18245       !Type->isReferenceType()) {
18246     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
18247         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
18248     return true;
18249   }
18250   Type = Type.getNonReferenceType();
18251 
18252   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
18253   // A variable that is privatized must not have a const-qualified type
18254   // unless it is of class type with a mutable member. This restriction does
18255   // not apply to the firstprivate clause, nor to the linear clause on
18256   // declarative directives (like declare simd).
18257   if (!IsDeclareSimd &&
18258       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
18259     return true;
18260 
18261   // A list item must be of integral or pointer type.
18262   Type = Type.getUnqualifiedType().getCanonicalType();
18263   const auto *Ty = Type.getTypePtrOrNull();
18264   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
18265               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
18266     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
18267     if (D) {
18268       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18269                                VarDecl::DeclarationOnly;
18270       Diag(D->getLocation(),
18271            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18272           << D;
18273     }
18274     return true;
18275   }
18276   return false;
18277 }
18278 
18279 OMPClause *Sema::ActOnOpenMPLinearClause(
18280     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
18281     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
18282     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
18283   SmallVector<Expr *, 8> Vars;
18284   SmallVector<Expr *, 8> Privates;
18285   SmallVector<Expr *, 8> Inits;
18286   SmallVector<Decl *, 4> ExprCaptures;
18287   SmallVector<Expr *, 4> ExprPostUpdates;
18288   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
18289     LinKind = OMPC_LINEAR_val;
18290   for (Expr *RefExpr : VarList) {
18291     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18292     SourceLocation ELoc;
18293     SourceRange ERange;
18294     Expr *SimpleRefExpr = RefExpr;
18295     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18296     if (Res.second) {
18297       // It will be analyzed later.
18298       Vars.push_back(RefExpr);
18299       Privates.push_back(nullptr);
18300       Inits.push_back(nullptr);
18301     }
18302     ValueDecl *D = Res.first;
18303     if (!D)
18304       continue;
18305 
18306     QualType Type = D->getType();
18307     auto *VD = dyn_cast<VarDecl>(D);
18308 
18309     // OpenMP [2.14.3.7, linear clause]
18310     //  A list-item cannot appear in more than one linear clause.
18311     //  A list-item that appears in a linear clause cannot appear in any
18312     //  other data-sharing attribute clause.
18313     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
18314     if (DVar.RefExpr) {
18315       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
18316                                           << getOpenMPClauseName(OMPC_linear);
18317       reportOriginalDsa(*this, DSAStack, D, DVar);
18318       continue;
18319     }
18320 
18321     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
18322       continue;
18323     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
18324 
18325     // Build private copy of original var.
18326     VarDecl *Private =
18327         buildVarDecl(*this, ELoc, Type, D->getName(),
18328                      D->hasAttrs() ? &D->getAttrs() : nullptr,
18329                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
18330     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
18331     // Build var to save initial value.
18332     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
18333     Expr *InitExpr;
18334     DeclRefExpr *Ref = nullptr;
18335     if (!VD && !CurContext->isDependentContext()) {
18336       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
18337       if (!isOpenMPCapturedDecl(D)) {
18338         ExprCaptures.push_back(Ref->getDecl());
18339         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
18340           ExprResult RefRes = DefaultLvalueConversion(Ref);
18341           if (!RefRes.isUsable())
18342             continue;
18343           ExprResult PostUpdateRes =
18344               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
18345                          SimpleRefExpr, RefRes.get());
18346           if (!PostUpdateRes.isUsable())
18347             continue;
18348           ExprPostUpdates.push_back(
18349               IgnoredValueConversions(PostUpdateRes.get()).get());
18350         }
18351       }
18352     }
18353     if (LinKind == OMPC_LINEAR_uval)
18354       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
18355     else
18356       InitExpr = VD ? SimpleRefExpr : Ref;
18357     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
18358                          /*DirectInit=*/false);
18359     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
18360 
18361     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
18362     Vars.push_back((VD || CurContext->isDependentContext())
18363                        ? RefExpr->IgnoreParens()
18364                        : Ref);
18365     Privates.push_back(PrivateRef);
18366     Inits.push_back(InitRef);
18367   }
18368 
18369   if (Vars.empty())
18370     return nullptr;
18371 
18372   Expr *StepExpr = Step;
18373   Expr *CalcStepExpr = nullptr;
18374   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
18375       !Step->isInstantiationDependent() &&
18376       !Step->containsUnexpandedParameterPack()) {
18377     SourceLocation StepLoc = Step->getBeginLoc();
18378     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
18379     if (Val.isInvalid())
18380       return nullptr;
18381     StepExpr = Val.get();
18382 
18383     // Build var to save the step value.
18384     VarDecl *SaveVar =
18385         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
18386     ExprResult SaveRef =
18387         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
18388     ExprResult CalcStep =
18389         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
18390     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
18391 
18392     // Warn about zero linear step (it would be probably better specified as
18393     // making corresponding variables 'const').
18394     if (Optional<llvm::APSInt> Result =
18395             StepExpr->getIntegerConstantExpr(Context)) {
18396       if (!Result->isNegative() && !Result->isStrictlyPositive())
18397         Diag(StepLoc, diag::warn_omp_linear_step_zero)
18398             << Vars[0] << (Vars.size() > 1);
18399     } else if (CalcStep.isUsable()) {
18400       // Calculate the step beforehand instead of doing this on each iteration.
18401       // (This is not used if the number of iterations may be kfold-ed).
18402       CalcStepExpr = CalcStep.get();
18403     }
18404   }
18405 
18406   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
18407                                  ColonLoc, EndLoc, Vars, Privates, Inits,
18408                                  StepExpr, CalcStepExpr,
18409                                  buildPreInits(Context, ExprCaptures),
18410                                  buildPostUpdate(*this, ExprPostUpdates));
18411 }
18412 
18413 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
18414                                      Expr *NumIterations, Sema &SemaRef,
18415                                      Scope *S, DSAStackTy *Stack) {
18416   // Walk the vars and build update/final expressions for the CodeGen.
18417   SmallVector<Expr *, 8> Updates;
18418   SmallVector<Expr *, 8> Finals;
18419   SmallVector<Expr *, 8> UsedExprs;
18420   Expr *Step = Clause.getStep();
18421   Expr *CalcStep = Clause.getCalcStep();
18422   // OpenMP [2.14.3.7, linear clause]
18423   // If linear-step is not specified it is assumed to be 1.
18424   if (!Step)
18425     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
18426   else if (CalcStep)
18427     Step = cast<BinaryOperator>(CalcStep)->getLHS();
18428   bool HasErrors = false;
18429   auto CurInit = Clause.inits().begin();
18430   auto CurPrivate = Clause.privates().begin();
18431   OpenMPLinearClauseKind LinKind = Clause.getModifier();
18432   for (Expr *RefExpr : Clause.varlists()) {
18433     SourceLocation ELoc;
18434     SourceRange ERange;
18435     Expr *SimpleRefExpr = RefExpr;
18436     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
18437     ValueDecl *D = Res.first;
18438     if (Res.second || !D) {
18439       Updates.push_back(nullptr);
18440       Finals.push_back(nullptr);
18441       HasErrors = true;
18442       continue;
18443     }
18444     auto &&Info = Stack->isLoopControlVariable(D);
18445     // OpenMP [2.15.11, distribute simd Construct]
18446     // A list item may not appear in a linear clause, unless it is the loop
18447     // iteration variable.
18448     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
18449         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
18450       SemaRef.Diag(ELoc,
18451                    diag::err_omp_linear_distribute_var_non_loop_iteration);
18452       Updates.push_back(nullptr);
18453       Finals.push_back(nullptr);
18454       HasErrors = true;
18455       continue;
18456     }
18457     Expr *InitExpr = *CurInit;
18458 
18459     // Build privatized reference to the current linear var.
18460     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
18461     Expr *CapturedRef;
18462     if (LinKind == OMPC_LINEAR_uval)
18463       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
18464     else
18465       CapturedRef =
18466           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
18467                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
18468                            /*RefersToCapture=*/true);
18469 
18470     // Build update: Var = InitExpr + IV * Step
18471     ExprResult Update;
18472     if (!Info.first)
18473       Update = buildCounterUpdate(
18474           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
18475           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
18476     else
18477       Update = *CurPrivate;
18478     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
18479                                          /*DiscardedValue*/ false);
18480 
18481     // Build final: Var = PrivCopy;
18482     ExprResult Final;
18483     if (!Info.first)
18484       Final = SemaRef.BuildBinOp(
18485           S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
18486           SemaRef.DefaultLvalueConversion(*CurPrivate).get());
18487     else
18488       Final = *CurPrivate;
18489     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
18490                                         /*DiscardedValue*/ false);
18491 
18492     if (!Update.isUsable() || !Final.isUsable()) {
18493       Updates.push_back(nullptr);
18494       Finals.push_back(nullptr);
18495       UsedExprs.push_back(nullptr);
18496       HasErrors = true;
18497     } else {
18498       Updates.push_back(Update.get());
18499       Finals.push_back(Final.get());
18500       if (!Info.first)
18501         UsedExprs.push_back(SimpleRefExpr);
18502     }
18503     ++CurInit;
18504     ++CurPrivate;
18505   }
18506   if (Expr *S = Clause.getStep())
18507     UsedExprs.push_back(S);
18508   // Fill the remaining part with the nullptr.
18509   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
18510   Clause.setUpdates(Updates);
18511   Clause.setFinals(Finals);
18512   Clause.setUsedExprs(UsedExprs);
18513   return HasErrors;
18514 }
18515 
18516 OMPClause *Sema::ActOnOpenMPAlignedClause(
18517     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
18518     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
18519   SmallVector<Expr *, 8> Vars;
18520   for (Expr *RefExpr : VarList) {
18521     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18522     SourceLocation ELoc;
18523     SourceRange ERange;
18524     Expr *SimpleRefExpr = RefExpr;
18525     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18526     if (Res.second) {
18527       // It will be analyzed later.
18528       Vars.push_back(RefExpr);
18529     }
18530     ValueDecl *D = Res.first;
18531     if (!D)
18532       continue;
18533 
18534     QualType QType = D->getType();
18535     auto *VD = dyn_cast<VarDecl>(D);
18536 
18537     // OpenMP  [2.8.1, simd construct, Restrictions]
18538     // The type of list items appearing in the aligned clause must be
18539     // array, pointer, reference to array, or reference to pointer.
18540     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
18541     const Type *Ty = QType.getTypePtrOrNull();
18542     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
18543       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
18544           << QType << getLangOpts().CPlusPlus << ERange;
18545       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18546                                VarDecl::DeclarationOnly;
18547       Diag(D->getLocation(),
18548            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18549           << D;
18550       continue;
18551     }
18552 
18553     // OpenMP  [2.8.1, simd construct, Restrictions]
18554     // A list-item cannot appear in more than one aligned clause.
18555     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
18556       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18557           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
18558       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18559           << getOpenMPClauseName(OMPC_aligned);
18560       continue;
18561     }
18562 
18563     DeclRefExpr *Ref = nullptr;
18564     if (!VD && isOpenMPCapturedDecl(D))
18565       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18566     Vars.push_back(DefaultFunctionArrayConversion(
18567                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
18568                        .get());
18569   }
18570 
18571   // OpenMP [2.8.1, simd construct, Description]
18572   // The parameter of the aligned clause, alignment, must be a constant
18573   // positive integer expression.
18574   // If no optional parameter is specified, implementation-defined default
18575   // alignments for SIMD instructions on the target platforms are assumed.
18576   if (Alignment != nullptr) {
18577     ExprResult AlignResult =
18578         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
18579     if (AlignResult.isInvalid())
18580       return nullptr;
18581     Alignment = AlignResult.get();
18582   }
18583   if (Vars.empty())
18584     return nullptr;
18585 
18586   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
18587                                   EndLoc, Vars, Alignment);
18588 }
18589 
18590 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
18591                                          SourceLocation StartLoc,
18592                                          SourceLocation LParenLoc,
18593                                          SourceLocation EndLoc) {
18594   SmallVector<Expr *, 8> Vars;
18595   SmallVector<Expr *, 8> SrcExprs;
18596   SmallVector<Expr *, 8> DstExprs;
18597   SmallVector<Expr *, 8> AssignmentOps;
18598   for (Expr *RefExpr : VarList) {
18599     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
18600     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18601       // It will be analyzed later.
18602       Vars.push_back(RefExpr);
18603       SrcExprs.push_back(nullptr);
18604       DstExprs.push_back(nullptr);
18605       AssignmentOps.push_back(nullptr);
18606       continue;
18607     }
18608 
18609     SourceLocation ELoc = RefExpr->getExprLoc();
18610     // OpenMP [2.1, C/C++]
18611     //  A list item is a variable name.
18612     // OpenMP  [2.14.4.1, Restrictions, p.1]
18613     //  A list item that appears in a copyin clause must be threadprivate.
18614     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
18615     if (!DE || !isa<VarDecl>(DE->getDecl())) {
18616       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
18617           << 0 << RefExpr->getSourceRange();
18618       continue;
18619     }
18620 
18621     Decl *D = DE->getDecl();
18622     auto *VD = cast<VarDecl>(D);
18623 
18624     QualType Type = VD->getType();
18625     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
18626       // It will be analyzed later.
18627       Vars.push_back(DE);
18628       SrcExprs.push_back(nullptr);
18629       DstExprs.push_back(nullptr);
18630       AssignmentOps.push_back(nullptr);
18631       continue;
18632     }
18633 
18634     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
18635     //  A list item that appears in a copyin clause must be threadprivate.
18636     if (!DSAStack->isThreadPrivate(VD)) {
18637       Diag(ELoc, diag::err_omp_required_access)
18638           << getOpenMPClauseName(OMPC_copyin)
18639           << getOpenMPDirectiveName(OMPD_threadprivate);
18640       continue;
18641     }
18642 
18643     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18644     //  A variable of class type (or array thereof) that appears in a
18645     //  copyin clause requires an accessible, unambiguous copy assignment
18646     //  operator for the class type.
18647     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
18648     VarDecl *SrcVD =
18649         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
18650                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18651     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
18652         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
18653     VarDecl *DstVD =
18654         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
18655                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18656     DeclRefExpr *PseudoDstExpr =
18657         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
18658     // For arrays generate assignment operation for single element and replace
18659     // it by the original array element in CodeGen.
18660     ExprResult AssignmentOp =
18661         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
18662                    PseudoSrcExpr);
18663     if (AssignmentOp.isInvalid())
18664       continue;
18665     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
18666                                        /*DiscardedValue*/ false);
18667     if (AssignmentOp.isInvalid())
18668       continue;
18669 
18670     DSAStack->addDSA(VD, DE, OMPC_copyin);
18671     Vars.push_back(DE);
18672     SrcExprs.push_back(PseudoSrcExpr);
18673     DstExprs.push_back(PseudoDstExpr);
18674     AssignmentOps.push_back(AssignmentOp.get());
18675   }
18676 
18677   if (Vars.empty())
18678     return nullptr;
18679 
18680   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
18681                                  SrcExprs, DstExprs, AssignmentOps);
18682 }
18683 
18684 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
18685                                               SourceLocation StartLoc,
18686                                               SourceLocation LParenLoc,
18687                                               SourceLocation EndLoc) {
18688   SmallVector<Expr *, 8> Vars;
18689   SmallVector<Expr *, 8> SrcExprs;
18690   SmallVector<Expr *, 8> DstExprs;
18691   SmallVector<Expr *, 8> AssignmentOps;
18692   for (Expr *RefExpr : VarList) {
18693     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18694     SourceLocation ELoc;
18695     SourceRange ERange;
18696     Expr *SimpleRefExpr = RefExpr;
18697     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18698     if (Res.second) {
18699       // It will be analyzed later.
18700       Vars.push_back(RefExpr);
18701       SrcExprs.push_back(nullptr);
18702       DstExprs.push_back(nullptr);
18703       AssignmentOps.push_back(nullptr);
18704     }
18705     ValueDecl *D = Res.first;
18706     if (!D)
18707       continue;
18708 
18709     QualType Type = D->getType();
18710     auto *VD = dyn_cast<VarDecl>(D);
18711 
18712     // OpenMP [2.14.4.2, Restrictions, p.2]
18713     //  A list item that appears in a copyprivate clause may not appear in a
18714     //  private or firstprivate clause on the single construct.
18715     if (!VD || !DSAStack->isThreadPrivate(VD)) {
18716       DSAStackTy::DSAVarData DVar =
18717           DSAStack->getTopDSA(D, /*FromParent=*/false);
18718       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
18719           DVar.RefExpr) {
18720         Diag(ELoc, diag::err_omp_wrong_dsa)
18721             << getOpenMPClauseName(DVar.CKind)
18722             << getOpenMPClauseName(OMPC_copyprivate);
18723         reportOriginalDsa(*this, DSAStack, D, DVar);
18724         continue;
18725       }
18726 
18727       // OpenMP [2.11.4.2, Restrictions, p.1]
18728       //  All list items that appear in a copyprivate clause must be either
18729       //  threadprivate or private in the enclosing context.
18730       if (DVar.CKind == OMPC_unknown) {
18731         DVar = DSAStack->getImplicitDSA(D, false);
18732         if (DVar.CKind == OMPC_shared) {
18733           Diag(ELoc, diag::err_omp_required_access)
18734               << getOpenMPClauseName(OMPC_copyprivate)
18735               << "threadprivate or private in the enclosing context";
18736           reportOriginalDsa(*this, DSAStack, D, DVar);
18737           continue;
18738         }
18739       }
18740     }
18741 
18742     // Variably modified types are not supported.
18743     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
18744       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
18745           << getOpenMPClauseName(OMPC_copyprivate) << Type
18746           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18747       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18748                                VarDecl::DeclarationOnly;
18749       Diag(D->getLocation(),
18750            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18751           << D;
18752       continue;
18753     }
18754 
18755     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18756     //  A variable of class type (or array thereof) that appears in a
18757     //  copyin clause requires an accessible, unambiguous copy assignment
18758     //  operator for the class type.
18759     Type = Context.getBaseElementType(Type.getNonReferenceType())
18760                .getUnqualifiedType();
18761     VarDecl *SrcVD =
18762         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
18763                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18764     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
18765     VarDecl *DstVD =
18766         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
18767                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18768     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
18769     ExprResult AssignmentOp = BuildBinOp(
18770         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
18771     if (AssignmentOp.isInvalid())
18772       continue;
18773     AssignmentOp =
18774         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
18775     if (AssignmentOp.isInvalid())
18776       continue;
18777 
18778     // No need to mark vars as copyprivate, they are already threadprivate or
18779     // implicitly private.
18780     assert(VD || isOpenMPCapturedDecl(D));
18781     Vars.push_back(
18782         VD ? RefExpr->IgnoreParens()
18783            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
18784     SrcExprs.push_back(PseudoSrcExpr);
18785     DstExprs.push_back(PseudoDstExpr);
18786     AssignmentOps.push_back(AssignmentOp.get());
18787   }
18788 
18789   if (Vars.empty())
18790     return nullptr;
18791 
18792   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18793                                       Vars, SrcExprs, DstExprs, AssignmentOps);
18794 }
18795 
18796 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
18797                                         SourceLocation StartLoc,
18798                                         SourceLocation LParenLoc,
18799                                         SourceLocation EndLoc) {
18800   if (VarList.empty())
18801     return nullptr;
18802 
18803   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
18804 }
18805 
18806 /// Tries to find omp_depend_t. type.
18807 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
18808                            bool Diagnose = true) {
18809   QualType OMPDependT = Stack->getOMPDependT();
18810   if (!OMPDependT.isNull())
18811     return true;
18812   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
18813   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18814   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18815     if (Diagnose)
18816       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
18817     return false;
18818   }
18819   Stack->setOMPDependT(PT.get());
18820   return true;
18821 }
18822 
18823 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
18824                                          SourceLocation LParenLoc,
18825                                          SourceLocation EndLoc) {
18826   if (!Depobj)
18827     return nullptr;
18828 
18829   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
18830 
18831   // OpenMP 5.0, 2.17.10.1 depobj Construct
18832   // depobj is an lvalue expression of type omp_depend_t.
18833   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
18834       !Depobj->isInstantiationDependent() &&
18835       !Depobj->containsUnexpandedParameterPack() &&
18836       (OMPDependTFound &&
18837        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
18838                                    /*CompareUnqualified=*/true))) {
18839     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18840         << 0 << Depobj->getType() << Depobj->getSourceRange();
18841   }
18842 
18843   if (!Depobj->isLValue()) {
18844     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18845         << 1 << Depobj->getSourceRange();
18846   }
18847 
18848   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
18849 }
18850 
18851 OMPClause *
18852 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
18853                               SourceLocation DepLoc, SourceLocation ColonLoc,
18854                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18855                               SourceLocation LParenLoc, SourceLocation EndLoc) {
18856   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
18857       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
18858     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18859         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
18860     return nullptr;
18861   }
18862   if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
18863       DepKind == OMPC_DEPEND_mutexinoutset) {
18864     Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
18865     return nullptr;
18866   }
18867   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
18868        DSAStack->getCurrentDirective() == OMPD_depobj) &&
18869       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
18870        DepKind == OMPC_DEPEND_sink ||
18871        ((LangOpts.OpenMP < 50 ||
18872          DSAStack->getCurrentDirective() == OMPD_depobj) &&
18873         DepKind == OMPC_DEPEND_depobj))) {
18874     SmallVector<unsigned, 3> Except;
18875     Except.push_back(OMPC_DEPEND_source);
18876     Except.push_back(OMPC_DEPEND_sink);
18877     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
18878       Except.push_back(OMPC_DEPEND_depobj);
18879     if (LangOpts.OpenMP < 51)
18880       Except.push_back(OMPC_DEPEND_inoutset);
18881     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
18882                                ? "depend modifier(iterator) or "
18883                                : "";
18884     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18885         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
18886                                               /*Last=*/OMPC_DEPEND_unknown,
18887                                               Except)
18888         << getOpenMPClauseName(OMPC_depend);
18889     return nullptr;
18890   }
18891   if (DepModifier &&
18892       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
18893     Diag(DepModifier->getExprLoc(),
18894          diag::err_omp_depend_sink_source_with_modifier);
18895     return nullptr;
18896   }
18897   if (DepModifier &&
18898       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
18899     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
18900 
18901   SmallVector<Expr *, 8> Vars;
18902   DSAStackTy::OperatorOffsetTy OpsOffs;
18903   llvm::APSInt DepCounter(/*BitWidth=*/32);
18904   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
18905   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
18906     if (const Expr *OrderedCountExpr =
18907             DSAStack->getParentOrderedRegionParam().first) {
18908       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
18909       TotalDepCount.setIsUnsigned(/*Val=*/true);
18910     }
18911   }
18912   for (Expr *RefExpr : VarList) {
18913     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18914     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18915       // It will be analyzed later.
18916       Vars.push_back(RefExpr);
18917       continue;
18918     }
18919 
18920     SourceLocation ELoc = RefExpr->getExprLoc();
18921     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
18922     if (DepKind == OMPC_DEPEND_sink) {
18923       if (DSAStack->getParentOrderedRegionParam().first &&
18924           DepCounter >= TotalDepCount) {
18925         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
18926         continue;
18927       }
18928       ++DepCounter;
18929       // OpenMP  [2.13.9, Summary]
18930       // depend(dependence-type : vec), where dependence-type is:
18931       // 'sink' and where vec is the iteration vector, which has the form:
18932       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
18933       // where n is the value specified by the ordered clause in the loop
18934       // directive, xi denotes the loop iteration variable of the i-th nested
18935       // loop associated with the loop directive, and di is a constant
18936       // non-negative integer.
18937       if (CurContext->isDependentContext()) {
18938         // It will be analyzed later.
18939         Vars.push_back(RefExpr);
18940         continue;
18941       }
18942       SimpleExpr = SimpleExpr->IgnoreImplicit();
18943       OverloadedOperatorKind OOK = OO_None;
18944       SourceLocation OOLoc;
18945       Expr *LHS = SimpleExpr;
18946       Expr *RHS = nullptr;
18947       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
18948         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
18949         OOLoc = BO->getOperatorLoc();
18950         LHS = BO->getLHS()->IgnoreParenImpCasts();
18951         RHS = BO->getRHS()->IgnoreParenImpCasts();
18952       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
18953         OOK = OCE->getOperator();
18954         OOLoc = OCE->getOperatorLoc();
18955         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18956         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
18957       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
18958         OOK = MCE->getMethodDecl()
18959                   ->getNameInfo()
18960                   .getName()
18961                   .getCXXOverloadedOperator();
18962         OOLoc = MCE->getCallee()->getExprLoc();
18963         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
18964         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18965       }
18966       SourceLocation ELoc;
18967       SourceRange ERange;
18968       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
18969       if (Res.second) {
18970         // It will be analyzed later.
18971         Vars.push_back(RefExpr);
18972       }
18973       ValueDecl *D = Res.first;
18974       if (!D)
18975         continue;
18976 
18977       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
18978         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
18979         continue;
18980       }
18981       if (RHS) {
18982         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
18983             RHS, OMPC_depend, /*StrictlyPositive=*/false);
18984         if (RHSRes.isInvalid())
18985           continue;
18986       }
18987       if (!CurContext->isDependentContext() &&
18988           DSAStack->getParentOrderedRegionParam().first &&
18989           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
18990         const ValueDecl *VD =
18991             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
18992         if (VD)
18993           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
18994               << 1 << VD;
18995         else
18996           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
18997         continue;
18998       }
18999       OpsOffs.emplace_back(RHS, OOK);
19000     } else {
19001       bool OMPDependTFound = LangOpts.OpenMP >= 50;
19002       if (OMPDependTFound)
19003         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
19004                                          DepKind == OMPC_DEPEND_depobj);
19005       if (DepKind == OMPC_DEPEND_depobj) {
19006         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
19007         // List items used in depend clauses with the depobj dependence type
19008         // must be expressions of the omp_depend_t type.
19009         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
19010             !RefExpr->isInstantiationDependent() &&
19011             !RefExpr->containsUnexpandedParameterPack() &&
19012             (OMPDependTFound &&
19013              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
19014                                              RefExpr->getType()))) {
19015           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
19016               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
19017           continue;
19018         }
19019         if (!RefExpr->isLValue()) {
19020           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
19021               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
19022           continue;
19023         }
19024       } else {
19025         // OpenMP 5.0 [2.17.11, Restrictions]
19026         // List items used in depend clauses cannot be zero-length array
19027         // sections.
19028         QualType ExprTy = RefExpr->getType().getNonReferenceType();
19029         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
19030         if (OASE) {
19031           QualType BaseType =
19032               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19033           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19034             ExprTy = ATy->getElementType();
19035           else
19036             ExprTy = BaseType->getPointeeType();
19037           ExprTy = ExprTy.getNonReferenceType();
19038           const Expr *Length = OASE->getLength();
19039           Expr::EvalResult Result;
19040           if (Length && !Length->isValueDependent() &&
19041               Length->EvaluateAsInt(Result, Context) &&
19042               Result.Val.getInt().isZero()) {
19043             Diag(ELoc,
19044                  diag::err_omp_depend_zero_length_array_section_not_allowed)
19045                 << SimpleExpr->getSourceRange();
19046             continue;
19047           }
19048         }
19049 
19050         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
19051         // List items used in depend clauses with the in, out, inout,
19052         // inoutset, or mutexinoutset dependence types cannot be
19053         // expressions of the omp_depend_t type.
19054         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
19055             !RefExpr->isInstantiationDependent() &&
19056             !RefExpr->containsUnexpandedParameterPack() &&
19057             (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
19058              (OMPDependTFound &&
19059               DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
19060           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19061               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19062               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19063           continue;
19064         }
19065 
19066         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
19067         if (ASE && !ASE->getBase()->isTypeDependent() &&
19068             !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
19069             !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
19070           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19071               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19072               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19073           continue;
19074         }
19075 
19076         ExprResult Res;
19077         {
19078           Sema::TentativeAnalysisScope Trap(*this);
19079           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
19080                                      RefExpr->IgnoreParenImpCasts());
19081         }
19082         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
19083             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
19084           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19085               << (LangOpts.OpenMP >= 50 ? 1 : 0)
19086               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
19087           continue;
19088         }
19089       }
19090     }
19091     Vars.push_back(RefExpr->IgnoreParenImpCasts());
19092   }
19093 
19094   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
19095       TotalDepCount > VarList.size() &&
19096       DSAStack->getParentOrderedRegionParam().first &&
19097       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
19098     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
19099         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
19100   }
19101   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
19102       Vars.empty())
19103     return nullptr;
19104 
19105   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19106                                     DepModifier, DepKind, DepLoc, ColonLoc,
19107                                     Vars, TotalDepCount.getZExtValue());
19108   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
19109       DSAStack->isParentOrderedRegion())
19110     DSAStack->addDoacrossDependClause(C, OpsOffs);
19111   return C;
19112 }
19113 
19114 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
19115                                          Expr *Device, SourceLocation StartLoc,
19116                                          SourceLocation LParenLoc,
19117                                          SourceLocation ModifierLoc,
19118                                          SourceLocation EndLoc) {
19119   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
19120          "Unexpected device modifier in OpenMP < 50.");
19121 
19122   bool ErrorFound = false;
19123   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
19124     std::string Values =
19125         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
19126     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
19127         << Values << getOpenMPClauseName(OMPC_device);
19128     ErrorFound = true;
19129   }
19130 
19131   Expr *ValExpr = Device;
19132   Stmt *HelperValStmt = nullptr;
19133 
19134   // OpenMP [2.9.1, Restrictions]
19135   // The device expression must evaluate to a non-negative integer value.
19136   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
19137                                           /*StrictlyPositive=*/false) ||
19138                ErrorFound;
19139   if (ErrorFound)
19140     return nullptr;
19141 
19142   // OpenMP 5.0 [2.12.5, Restrictions]
19143   // In case of ancestor device-modifier, a requires directive with
19144   // the reverse_offload clause must be specified.
19145   if (Modifier == OMPC_DEVICE_ancestor) {
19146     if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) {
19147       targetDiag(
19148           StartLoc,
19149           diag::err_omp_device_ancestor_without_requires_reverse_offload);
19150       ErrorFound = true;
19151     }
19152   }
19153 
19154   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19155   OpenMPDirectiveKind CaptureRegion =
19156       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
19157   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19158     ValExpr = MakeFullExpr(ValExpr).get();
19159     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19160     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19161     HelperValStmt = buildPreInits(Context, Captures);
19162   }
19163 
19164   return new (Context)
19165       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
19166                       LParenLoc, ModifierLoc, EndLoc);
19167 }
19168 
19169 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
19170                               DSAStackTy *Stack, QualType QTy,
19171                               bool FullCheck = true) {
19172   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
19173     return false;
19174   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
19175       !QTy.isTriviallyCopyableType(SemaRef.Context))
19176     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
19177   return true;
19178 }
19179 
19180 /// Return true if it can be proven that the provided array expression
19181 /// (array section or array subscript) does NOT specify the whole size of the
19182 /// array whose base type is \a BaseQTy.
19183 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
19184                                                         const Expr *E,
19185                                                         QualType BaseQTy) {
19186   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
19187 
19188   // If this is an array subscript, it refers to the whole size if the size of
19189   // the dimension is constant and equals 1. Also, an array section assumes the
19190   // format of an array subscript if no colon is used.
19191   if (isa<ArraySubscriptExpr>(E) ||
19192       (OASE && OASE->getColonLocFirst().isInvalid())) {
19193     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
19194       return ATy->getSize().getSExtValue() != 1;
19195     // Size can't be evaluated statically.
19196     return false;
19197   }
19198 
19199   assert(OASE && "Expecting array section if not an array subscript.");
19200   const Expr *LowerBound = OASE->getLowerBound();
19201   const Expr *Length = OASE->getLength();
19202 
19203   // If there is a lower bound that does not evaluates to zero, we are not
19204   // covering the whole dimension.
19205   if (LowerBound) {
19206     Expr::EvalResult Result;
19207     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
19208       return false; // Can't get the integer value as a constant.
19209 
19210     llvm::APSInt ConstLowerBound = Result.Val.getInt();
19211     if (ConstLowerBound.getSExtValue())
19212       return true;
19213   }
19214 
19215   // If we don't have a length we covering the whole dimension.
19216   if (!Length)
19217     return false;
19218 
19219   // If the base is a pointer, we don't have a way to get the size of the
19220   // pointee.
19221   if (BaseQTy->isPointerType())
19222     return false;
19223 
19224   // We can only check if the length is the same as the size of the dimension
19225   // if we have a constant array.
19226   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
19227   if (!CATy)
19228     return false;
19229 
19230   Expr::EvalResult Result;
19231   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
19232     return false; // Can't get the integer value as a constant.
19233 
19234   llvm::APSInt ConstLength = Result.Val.getInt();
19235   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
19236 }
19237 
19238 // Return true if it can be proven that the provided array expression (array
19239 // section or array subscript) does NOT specify a single element of the array
19240 // whose base type is \a BaseQTy.
19241 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
19242                                                         const Expr *E,
19243                                                         QualType BaseQTy) {
19244   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
19245 
19246   // An array subscript always refer to a single element. Also, an array section
19247   // assumes the format of an array subscript if no colon is used.
19248   if (isa<ArraySubscriptExpr>(E) ||
19249       (OASE && OASE->getColonLocFirst().isInvalid()))
19250     return false;
19251 
19252   assert(OASE && "Expecting array section if not an array subscript.");
19253   const Expr *Length = OASE->getLength();
19254 
19255   // If we don't have a length we have to check if the array has unitary size
19256   // for this dimension. Also, we should always expect a length if the base type
19257   // is pointer.
19258   if (!Length) {
19259     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
19260       return ATy->getSize().getSExtValue() != 1;
19261     // We cannot assume anything.
19262     return false;
19263   }
19264 
19265   // Check if the length evaluates to 1.
19266   Expr::EvalResult Result;
19267   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
19268     return false; // Can't get the integer value as a constant.
19269 
19270   llvm::APSInt ConstLength = Result.Val.getInt();
19271   return ConstLength.getSExtValue() != 1;
19272 }
19273 
19274 // The base of elements of list in a map clause have to be either:
19275 //  - a reference to variable or field.
19276 //  - a member expression.
19277 //  - an array expression.
19278 //
19279 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
19280 // reference to 'r'.
19281 //
19282 // If we have:
19283 //
19284 // struct SS {
19285 //   Bla S;
19286 //   foo() {
19287 //     #pragma omp target map (S.Arr[:12]);
19288 //   }
19289 // }
19290 //
19291 // We want to retrieve the member expression 'this->S';
19292 
19293 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
19294 //  If a list item is an array section, it must specify contiguous storage.
19295 //
19296 // For this restriction it is sufficient that we make sure only references
19297 // to variables or fields and array expressions, and that no array sections
19298 // exist except in the rightmost expression (unless they cover the whole
19299 // dimension of the array). E.g. these would be invalid:
19300 //
19301 //   r.ArrS[3:5].Arr[6:7]
19302 //
19303 //   r.ArrS[3:5].x
19304 //
19305 // but these would be valid:
19306 //   r.ArrS[3].Arr[6:7]
19307 //
19308 //   r.ArrS[3].x
19309 namespace {
19310 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
19311   Sema &SemaRef;
19312   OpenMPClauseKind CKind = OMPC_unknown;
19313   OpenMPDirectiveKind DKind = OMPD_unknown;
19314   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
19315   bool IsNonContiguous = false;
19316   bool NoDiagnose = false;
19317   const Expr *RelevantExpr = nullptr;
19318   bool AllowUnitySizeArraySection = true;
19319   bool AllowWholeSizeArraySection = true;
19320   bool AllowAnotherPtr = true;
19321   SourceLocation ELoc;
19322   SourceRange ERange;
19323 
19324   void emitErrorMsg() {
19325     // If nothing else worked, this is not a valid map clause expression.
19326     if (SemaRef.getLangOpts().OpenMP < 50) {
19327       SemaRef.Diag(ELoc,
19328                    diag::err_omp_expected_named_var_member_or_array_expression)
19329           << ERange;
19330     } else {
19331       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19332           << getOpenMPClauseName(CKind) << ERange;
19333     }
19334   }
19335 
19336 public:
19337   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
19338     if (!isa<VarDecl>(DRE->getDecl())) {
19339       emitErrorMsg();
19340       return false;
19341     }
19342     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19343     RelevantExpr = DRE;
19344     // Record the component.
19345     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
19346     return true;
19347   }
19348 
19349   bool VisitMemberExpr(MemberExpr *ME) {
19350     Expr *E = ME;
19351     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
19352 
19353     if (isa<CXXThisExpr>(BaseE)) {
19354       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19355       // We found a base expression: this->Val.
19356       RelevantExpr = ME;
19357     } else {
19358       E = BaseE;
19359     }
19360 
19361     if (!isa<FieldDecl>(ME->getMemberDecl())) {
19362       if (!NoDiagnose) {
19363         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
19364             << ME->getSourceRange();
19365         return false;
19366       }
19367       if (RelevantExpr)
19368         return false;
19369       return Visit(E);
19370     }
19371 
19372     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
19373 
19374     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
19375     //  A bit-field cannot appear in a map clause.
19376     //
19377     if (FD->isBitField()) {
19378       if (!NoDiagnose) {
19379         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
19380             << ME->getSourceRange() << getOpenMPClauseName(CKind);
19381         return false;
19382       }
19383       if (RelevantExpr)
19384         return false;
19385       return Visit(E);
19386     }
19387 
19388     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19389     //  If the type of a list item is a reference to a type T then the type
19390     //  will be considered to be T for all purposes of this clause.
19391     QualType CurType = BaseE->getType().getNonReferenceType();
19392 
19393     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
19394     //  A list item cannot be a variable that is a member of a structure with
19395     //  a union type.
19396     //
19397     if (CurType->isUnionType()) {
19398       if (!NoDiagnose) {
19399         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
19400             << ME->getSourceRange();
19401         return false;
19402       }
19403       return RelevantExpr || Visit(E);
19404     }
19405 
19406     // If we got a member expression, we should not expect any array section
19407     // before that:
19408     //
19409     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
19410     //  If a list item is an element of a structure, only the rightmost symbol
19411     //  of the variable reference can be an array section.
19412     //
19413     AllowUnitySizeArraySection = false;
19414     AllowWholeSizeArraySection = false;
19415 
19416     // Record the component.
19417     Components.emplace_back(ME, FD, IsNonContiguous);
19418     return RelevantExpr || Visit(E);
19419   }
19420 
19421   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
19422     Expr *E = AE->getBase()->IgnoreParenImpCasts();
19423 
19424     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
19425       if (!NoDiagnose) {
19426         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19427             << 0 << AE->getSourceRange();
19428         return false;
19429       }
19430       return RelevantExpr || Visit(E);
19431     }
19432 
19433     // If we got an array subscript that express the whole dimension we
19434     // can have any array expressions before. If it only expressing part of
19435     // the dimension, we can only have unitary-size array expressions.
19436     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
19437       AllowWholeSizeArraySection = false;
19438 
19439     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
19440       Expr::EvalResult Result;
19441       if (!AE->getIdx()->isValueDependent() &&
19442           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
19443           !Result.Val.getInt().isZero()) {
19444         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19445                      diag::err_omp_invalid_map_this_expr);
19446         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19447                      diag::note_omp_invalid_subscript_on_this_ptr_map);
19448       }
19449       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19450       RelevantExpr = TE;
19451     }
19452 
19453     // Record the component - we don't have any declaration associated.
19454     Components.emplace_back(AE, nullptr, IsNonContiguous);
19455 
19456     return RelevantExpr || Visit(E);
19457   }
19458 
19459   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
19460     // After OMP 5.0  Array section in reduction clause will be implicitly
19461     // mapped
19462     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
19463            "Array sections cannot be implicitly mapped.");
19464     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19465     QualType CurType =
19466         OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19467 
19468     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19469     //  If the type of a list item is a reference to a type T then the type
19470     //  will be considered to be T for all purposes of this clause.
19471     if (CurType->isReferenceType())
19472       CurType = CurType->getPointeeType();
19473 
19474     bool IsPointer = CurType->isAnyPointerType();
19475 
19476     if (!IsPointer && !CurType->isArrayType()) {
19477       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19478           << 0 << OASE->getSourceRange();
19479       return false;
19480     }
19481 
19482     bool NotWhole =
19483         checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
19484     bool NotUnity =
19485         checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
19486 
19487     if (AllowWholeSizeArraySection) {
19488       // Any array section is currently allowed. Allowing a whole size array
19489       // section implies allowing a unity array section as well.
19490       //
19491       // If this array section refers to the whole dimension we can still
19492       // accept other array sections before this one, except if the base is a
19493       // pointer. Otherwise, only unitary sections are accepted.
19494       if (NotWhole || IsPointer)
19495         AllowWholeSizeArraySection = false;
19496     } else if (DKind == OMPD_target_update &&
19497                SemaRef.getLangOpts().OpenMP >= 50) {
19498       if (IsPointer && !AllowAnotherPtr)
19499         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
19500             << /*array of unknown bound */ 1;
19501       else
19502         IsNonContiguous = true;
19503     } else if (AllowUnitySizeArraySection && NotUnity) {
19504       // A unity or whole array section is not allowed and that is not
19505       // compatible with the properties of the current array section.
19506       if (NoDiagnose)
19507         return false;
19508       SemaRef.Diag(ELoc,
19509                    diag::err_array_section_does_not_specify_contiguous_storage)
19510           << OASE->getSourceRange();
19511       return false;
19512     }
19513 
19514     if (IsPointer)
19515       AllowAnotherPtr = false;
19516 
19517     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
19518       Expr::EvalResult ResultR;
19519       Expr::EvalResult ResultL;
19520       if (!OASE->getLength()->isValueDependent() &&
19521           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
19522           !ResultR.Val.getInt().isOne()) {
19523         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19524                      diag::err_omp_invalid_map_this_expr);
19525         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19526                      diag::note_omp_invalid_length_on_this_ptr_mapping);
19527       }
19528       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
19529           OASE->getLowerBound()->EvaluateAsInt(ResultL,
19530                                                SemaRef.getASTContext()) &&
19531           !ResultL.Val.getInt().isZero()) {
19532         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19533                      diag::err_omp_invalid_map_this_expr);
19534         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19535                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
19536       }
19537       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19538       RelevantExpr = TE;
19539     }
19540 
19541     // Record the component - we don't have any declaration associated.
19542     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
19543     return RelevantExpr || Visit(E);
19544   }
19545   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
19546     Expr *Base = E->getBase();
19547 
19548     // Record the component - we don't have any declaration associated.
19549     Components.emplace_back(E, nullptr, IsNonContiguous);
19550 
19551     return Visit(Base->IgnoreParenImpCasts());
19552   }
19553 
19554   bool VisitUnaryOperator(UnaryOperator *UO) {
19555     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
19556         UO->getOpcode() != UO_Deref) {
19557       emitErrorMsg();
19558       return false;
19559     }
19560     if (!RelevantExpr) {
19561       // Record the component if haven't found base decl.
19562       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
19563     }
19564     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
19565   }
19566   bool VisitBinaryOperator(BinaryOperator *BO) {
19567     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
19568       emitErrorMsg();
19569       return false;
19570     }
19571 
19572     // Pointer arithmetic is the only thing we expect to happen here so after we
19573     // make sure the binary operator is a pointer type, the we only thing need
19574     // to to is to visit the subtree that has the same type as root (so that we
19575     // know the other subtree is just an offset)
19576     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
19577     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
19578     Components.emplace_back(BO, nullptr, false);
19579     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
19580             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
19581            "Either LHS or RHS have base decl inside");
19582     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
19583       return RelevantExpr || Visit(LE);
19584     return RelevantExpr || Visit(RE);
19585   }
19586   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
19587     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19588     RelevantExpr = CTE;
19589     Components.emplace_back(CTE, nullptr, IsNonContiguous);
19590     return true;
19591   }
19592   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
19593     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19594     Components.emplace_back(COCE, nullptr, IsNonContiguous);
19595     return true;
19596   }
19597   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
19598     Expr *Source = E->getSourceExpr();
19599     if (!Source) {
19600       emitErrorMsg();
19601       return false;
19602     }
19603     return Visit(Source);
19604   }
19605   bool VisitStmt(Stmt *) {
19606     emitErrorMsg();
19607     return false;
19608   }
19609   const Expr *getFoundBase() const { return RelevantExpr; }
19610   explicit MapBaseChecker(
19611       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
19612       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
19613       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
19614       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
19615         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
19616 };
19617 } // namespace
19618 
19619 /// Return the expression of the base of the mappable expression or null if it
19620 /// cannot be determined and do all the necessary checks to see if the
19621 /// expression is valid as a standalone mappable expression. In the process,
19622 /// record all the components of the expression.
19623 static const Expr *checkMapClauseExpressionBase(
19624     Sema &SemaRef, Expr *E,
19625     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
19626     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
19627   SourceLocation ELoc = E->getExprLoc();
19628   SourceRange ERange = E->getSourceRange();
19629   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
19630                          ERange);
19631   if (Checker.Visit(E->IgnoreParens())) {
19632     // Check if the highest dimension array section has length specified
19633     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
19634         (CKind == OMPC_to || CKind == OMPC_from)) {
19635       auto CI = CurComponents.rbegin();
19636       auto CE = CurComponents.rend();
19637       for (; CI != CE; ++CI) {
19638         const auto *OASE =
19639             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
19640         if (!OASE)
19641           continue;
19642         if (OASE && OASE->getLength())
19643           break;
19644         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
19645             << ERange;
19646       }
19647     }
19648     return Checker.getFoundBase();
19649   }
19650   return nullptr;
19651 }
19652 
19653 // Return true if expression E associated with value VD has conflicts with other
19654 // map information.
19655 static bool checkMapConflicts(
19656     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
19657     bool CurrentRegionOnly,
19658     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
19659     OpenMPClauseKind CKind) {
19660   assert(VD && E);
19661   SourceLocation ELoc = E->getExprLoc();
19662   SourceRange ERange = E->getSourceRange();
19663 
19664   // In order to easily check the conflicts we need to match each component of
19665   // the expression under test with the components of the expressions that are
19666   // already in the stack.
19667 
19668   assert(!CurComponents.empty() && "Map clause expression with no components!");
19669   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
19670          "Map clause expression with unexpected base!");
19671 
19672   // Variables to help detecting enclosing problems in data environment nests.
19673   bool IsEnclosedByDataEnvironmentExpr = false;
19674   const Expr *EnclosingExpr = nullptr;
19675 
19676   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
19677       VD, CurrentRegionOnly,
19678       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
19679        ERange, CKind, &EnclosingExpr,
19680        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
19681                           StackComponents,
19682                       OpenMPClauseKind Kind) {
19683         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
19684           return false;
19685         assert(!StackComponents.empty() &&
19686                "Map clause expression with no components!");
19687         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
19688                "Map clause expression with unexpected base!");
19689         (void)VD;
19690 
19691         // The whole expression in the stack.
19692         const Expr *RE = StackComponents.front().getAssociatedExpression();
19693 
19694         // Expressions must start from the same base. Here we detect at which
19695         // point both expressions diverge from each other and see if we can
19696         // detect if the memory referred to both expressions is contiguous and
19697         // do not overlap.
19698         auto CI = CurComponents.rbegin();
19699         auto CE = CurComponents.rend();
19700         auto SI = StackComponents.rbegin();
19701         auto SE = StackComponents.rend();
19702         for (; CI != CE && SI != SE; ++CI, ++SI) {
19703 
19704           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
19705           //  At most one list item can be an array item derived from a given
19706           //  variable in map clauses of the same construct.
19707           if (CurrentRegionOnly &&
19708               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
19709                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
19710                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
19711               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
19712                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
19713                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
19714             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
19715                          diag::err_omp_multiple_array_items_in_map_clause)
19716                 << CI->getAssociatedExpression()->getSourceRange();
19717             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
19718                          diag::note_used_here)
19719                 << SI->getAssociatedExpression()->getSourceRange();
19720             return true;
19721           }
19722 
19723           // Do both expressions have the same kind?
19724           if (CI->getAssociatedExpression()->getStmtClass() !=
19725               SI->getAssociatedExpression()->getStmtClass())
19726             break;
19727 
19728           // Are we dealing with different variables/fields?
19729           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
19730             break;
19731         }
19732         // Check if the extra components of the expressions in the enclosing
19733         // data environment are redundant for the current base declaration.
19734         // If they are, the maps completely overlap, which is legal.
19735         for (; SI != SE; ++SI) {
19736           QualType Type;
19737           if (const auto *ASE =
19738                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
19739             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
19740           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
19741                          SI->getAssociatedExpression())) {
19742             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19743             Type =
19744                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19745           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
19746                          SI->getAssociatedExpression())) {
19747             Type = OASE->getBase()->getType()->getPointeeType();
19748           }
19749           if (Type.isNull() || Type->isAnyPointerType() ||
19750               checkArrayExpressionDoesNotReferToWholeSize(
19751                   SemaRef, SI->getAssociatedExpression(), Type))
19752             break;
19753         }
19754 
19755         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19756         //  List items of map clauses in the same construct must not share
19757         //  original storage.
19758         //
19759         // If the expressions are exactly the same or one is a subset of the
19760         // other, it means they are sharing storage.
19761         if (CI == CE && SI == SE) {
19762           if (CurrentRegionOnly) {
19763             if (CKind == OMPC_map) {
19764               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19765             } else {
19766               assert(CKind == OMPC_to || CKind == OMPC_from);
19767               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19768                   << ERange;
19769             }
19770             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19771                 << RE->getSourceRange();
19772             return true;
19773           }
19774           // If we find the same expression in the enclosing data environment,
19775           // that is legal.
19776           IsEnclosedByDataEnvironmentExpr = true;
19777           return false;
19778         }
19779 
19780         QualType DerivedType =
19781             std::prev(CI)->getAssociatedDeclaration()->getType();
19782         SourceLocation DerivedLoc =
19783             std::prev(CI)->getAssociatedExpression()->getExprLoc();
19784 
19785         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19786         //  If the type of a list item is a reference to a type T then the type
19787         //  will be considered to be T for all purposes of this clause.
19788         DerivedType = DerivedType.getNonReferenceType();
19789 
19790         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
19791         //  A variable for which the type is pointer and an array section
19792         //  derived from that variable must not appear as list items of map
19793         //  clauses of the same construct.
19794         //
19795         // Also, cover one of the cases in:
19796         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19797         //  If any part of the original storage of a list item has corresponding
19798         //  storage in the device data environment, all of the original storage
19799         //  must have corresponding storage in the device data environment.
19800         //
19801         if (DerivedType->isAnyPointerType()) {
19802           if (CI == CE || SI == SE) {
19803             SemaRef.Diag(
19804                 DerivedLoc,
19805                 diag::err_omp_pointer_mapped_along_with_derived_section)
19806                 << DerivedLoc;
19807             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19808                 << RE->getSourceRange();
19809             return true;
19810           }
19811           if (CI->getAssociatedExpression()->getStmtClass() !=
19812                   SI->getAssociatedExpression()->getStmtClass() ||
19813               CI->getAssociatedDeclaration()->getCanonicalDecl() ==
19814                   SI->getAssociatedDeclaration()->getCanonicalDecl()) {
19815             assert(CI != CE && SI != SE);
19816             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
19817                 << DerivedLoc;
19818             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19819                 << RE->getSourceRange();
19820             return true;
19821           }
19822         }
19823 
19824         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19825         //  List items of map clauses in the same construct must not share
19826         //  original storage.
19827         //
19828         // An expression is a subset of the other.
19829         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
19830           if (CKind == OMPC_map) {
19831             if (CI != CE || SI != SE) {
19832               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
19833               // a pointer.
19834               auto Begin =
19835                   CI != CE ? CurComponents.begin() : StackComponents.begin();
19836               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
19837               auto It = Begin;
19838               while (It != End && !It->getAssociatedDeclaration())
19839                 std::advance(It, 1);
19840               assert(It != End &&
19841                      "Expected at least one component with the declaration.");
19842               if (It != Begin && It->getAssociatedDeclaration()
19843                                      ->getType()
19844                                      .getCanonicalType()
19845                                      ->isAnyPointerType()) {
19846                 IsEnclosedByDataEnvironmentExpr = false;
19847                 EnclosingExpr = nullptr;
19848                 return false;
19849               }
19850             }
19851             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19852           } else {
19853             assert(CKind == OMPC_to || CKind == OMPC_from);
19854             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19855                 << ERange;
19856           }
19857           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19858               << RE->getSourceRange();
19859           return true;
19860         }
19861 
19862         // The current expression uses the same base as other expression in the
19863         // data environment but does not contain it completely.
19864         if (!CurrentRegionOnly && SI != SE)
19865           EnclosingExpr = RE;
19866 
19867         // The current expression is a subset of the expression in the data
19868         // environment.
19869         IsEnclosedByDataEnvironmentExpr |=
19870             (!CurrentRegionOnly && CI != CE && SI == SE);
19871 
19872         return false;
19873       });
19874 
19875   if (CurrentRegionOnly)
19876     return FoundError;
19877 
19878   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19879   //  If any part of the original storage of a list item has corresponding
19880   //  storage in the device data environment, all of the original storage must
19881   //  have corresponding storage in the device data environment.
19882   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
19883   //  If a list item is an element of a structure, and a different element of
19884   //  the structure has a corresponding list item in the device data environment
19885   //  prior to a task encountering the construct associated with the map clause,
19886   //  then the list item must also have a corresponding list item in the device
19887   //  data environment prior to the task encountering the construct.
19888   //
19889   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
19890     SemaRef.Diag(ELoc,
19891                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
19892         << ERange;
19893     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
19894         << EnclosingExpr->getSourceRange();
19895     return true;
19896   }
19897 
19898   return FoundError;
19899 }
19900 
19901 // Look up the user-defined mapper given the mapper name and mapped type, and
19902 // build a reference to it.
19903 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
19904                                             CXXScopeSpec &MapperIdScopeSpec,
19905                                             const DeclarationNameInfo &MapperId,
19906                                             QualType Type,
19907                                             Expr *UnresolvedMapper) {
19908   if (MapperIdScopeSpec.isInvalid())
19909     return ExprError();
19910   // Get the actual type for the array type.
19911   if (Type->isArrayType()) {
19912     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
19913     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
19914   }
19915   // Find all user-defined mappers with the given MapperId.
19916   SmallVector<UnresolvedSet<8>, 4> Lookups;
19917   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
19918   Lookup.suppressDiagnostics();
19919   if (S) {
19920     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
19921       NamedDecl *D = Lookup.getRepresentativeDecl();
19922       while (S && !S->isDeclScope(D))
19923         S = S->getParent();
19924       if (S)
19925         S = S->getParent();
19926       Lookups.emplace_back();
19927       Lookups.back().append(Lookup.begin(), Lookup.end());
19928       Lookup.clear();
19929     }
19930   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
19931     // Extract the user-defined mappers with the given MapperId.
19932     Lookups.push_back(UnresolvedSet<8>());
19933     for (NamedDecl *D : ULE->decls()) {
19934       auto *DMD = cast<OMPDeclareMapperDecl>(D);
19935       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
19936       Lookups.back().addDecl(DMD);
19937     }
19938   }
19939   // Defer the lookup for dependent types. The results will be passed through
19940   // UnresolvedMapper on instantiation.
19941   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
19942       Type->isInstantiationDependentType() ||
19943       Type->containsUnexpandedParameterPack() ||
19944       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
19945         return !D->isInvalidDecl() &&
19946                (D->getType()->isDependentType() ||
19947                 D->getType()->isInstantiationDependentType() ||
19948                 D->getType()->containsUnexpandedParameterPack());
19949       })) {
19950     UnresolvedSet<8> URS;
19951     for (const UnresolvedSet<8> &Set : Lookups) {
19952       if (Set.empty())
19953         continue;
19954       URS.append(Set.begin(), Set.end());
19955     }
19956     return UnresolvedLookupExpr::Create(
19957         SemaRef.Context, /*NamingClass=*/nullptr,
19958         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
19959         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
19960   }
19961   SourceLocation Loc = MapperId.getLoc();
19962   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19963   //  The type must be of struct, union or class type in C and C++
19964   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
19965       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
19966     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
19967     return ExprError();
19968   }
19969   // Perform argument dependent lookup.
19970   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
19971     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
19972   // Return the first user-defined mapper with the desired type.
19973   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19974           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
19975             if (!D->isInvalidDecl() &&
19976                 SemaRef.Context.hasSameType(D->getType(), Type))
19977               return D;
19978             return nullptr;
19979           }))
19980     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19981   // Find the first user-defined mapper with a type derived from the desired
19982   // type.
19983   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19984           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
19985             if (!D->isInvalidDecl() &&
19986                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
19987                 !Type.isMoreQualifiedThan(D->getType()))
19988               return D;
19989             return nullptr;
19990           })) {
19991     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
19992                        /*DetectVirtual=*/false);
19993     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
19994       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
19995               VD->getType().getUnqualifiedType()))) {
19996         if (SemaRef.CheckBaseClassAccess(
19997                 Loc, VD->getType(), Type, Paths.front(),
19998                 /*DiagID=*/0) != Sema::AR_inaccessible) {
19999           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
20000         }
20001       }
20002     }
20003   }
20004   // Report error if a mapper is specified, but cannot be found.
20005   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
20006     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
20007         << Type << MapperId.getName();
20008     return ExprError();
20009   }
20010   return ExprEmpty();
20011 }
20012 
20013 namespace {
20014 // Utility struct that gathers all the related lists associated with a mappable
20015 // expression.
20016 struct MappableVarListInfo {
20017   // The list of expressions.
20018   ArrayRef<Expr *> VarList;
20019   // The list of processed expressions.
20020   SmallVector<Expr *, 16> ProcessedVarList;
20021   // The mappble components for each expression.
20022   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
20023   // The base declaration of the variable.
20024   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
20025   // The reference to the user-defined mapper associated with every expression.
20026   SmallVector<Expr *, 16> UDMapperList;
20027 
20028   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
20029     // We have a list of components and base declarations for each entry in the
20030     // variable list.
20031     VarComponents.reserve(VarList.size());
20032     VarBaseDeclarations.reserve(VarList.size());
20033   }
20034 };
20035 } // namespace
20036 
20037 // Check the validity of the provided variable list for the provided clause kind
20038 // \a CKind. In the check process the valid expressions, mappable expression
20039 // components, variables, and user-defined mappers are extracted and used to
20040 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
20041 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
20042 // and \a MapperId are expected to be valid if the clause kind is 'map'.
20043 static void checkMappableExpressionList(
20044     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
20045     MappableVarListInfo &MVLI, SourceLocation StartLoc,
20046     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
20047     ArrayRef<Expr *> UnresolvedMappers,
20048     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
20049     ArrayRef<OpenMPMapModifierKind> Modifiers = None,
20050     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
20051   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
20052   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
20053          "Unexpected clause kind with mappable expressions!");
20054 
20055   // If the identifier of user-defined mapper is not specified, it is "default".
20056   // We do not change the actual name in this clause to distinguish whether a
20057   // mapper is specified explicitly, i.e., it is not explicitly specified when
20058   // MapperId.getName() is empty.
20059   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
20060     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
20061     MapperId.setName(DeclNames.getIdentifier(
20062         &SemaRef.getASTContext().Idents.get("default")));
20063     MapperId.setLoc(StartLoc);
20064   }
20065 
20066   // Iterators to find the current unresolved mapper expression.
20067   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
20068   bool UpdateUMIt = false;
20069   Expr *UnresolvedMapper = nullptr;
20070 
20071   bool HasHoldModifier =
20072       llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
20073 
20074   // Keep track of the mappable components and base declarations in this clause.
20075   // Each entry in the list is going to have a list of components associated. We
20076   // record each set of the components so that we can build the clause later on.
20077   // In the end we should have the same amount of declarations and component
20078   // lists.
20079 
20080   for (Expr *RE : MVLI.VarList) {
20081     assert(RE && "Null expr in omp to/from/map clause");
20082     SourceLocation ELoc = RE->getExprLoc();
20083 
20084     // Find the current unresolved mapper expression.
20085     if (UpdateUMIt && UMIt != UMEnd) {
20086       UMIt++;
20087       assert(
20088           UMIt != UMEnd &&
20089           "Expect the size of UnresolvedMappers to match with that of VarList");
20090     }
20091     UpdateUMIt = true;
20092     if (UMIt != UMEnd)
20093       UnresolvedMapper = *UMIt;
20094 
20095     const Expr *VE = RE->IgnoreParenLValueCasts();
20096 
20097     if (VE->isValueDependent() || VE->isTypeDependent() ||
20098         VE->isInstantiationDependent() ||
20099         VE->containsUnexpandedParameterPack()) {
20100       // Try to find the associated user-defined mapper.
20101       ExprResult ER = buildUserDefinedMapperRef(
20102           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20103           VE->getType().getCanonicalType(), UnresolvedMapper);
20104       if (ER.isInvalid())
20105         continue;
20106       MVLI.UDMapperList.push_back(ER.get());
20107       // We can only analyze this information once the missing information is
20108       // resolved.
20109       MVLI.ProcessedVarList.push_back(RE);
20110       continue;
20111     }
20112 
20113     Expr *SimpleExpr = RE->IgnoreParenCasts();
20114 
20115     if (!RE->isLValue()) {
20116       if (SemaRef.getLangOpts().OpenMP < 50) {
20117         SemaRef.Diag(
20118             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
20119             << RE->getSourceRange();
20120       } else {
20121         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
20122             << getOpenMPClauseName(CKind) << RE->getSourceRange();
20123       }
20124       continue;
20125     }
20126 
20127     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
20128     ValueDecl *CurDeclaration = nullptr;
20129 
20130     // Obtain the array or member expression bases if required. Also, fill the
20131     // components array with all the components identified in the process.
20132     const Expr *BE =
20133         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
20134                                      DSAS->getCurrentDirective(), NoDiagnose);
20135     if (!BE)
20136       continue;
20137 
20138     assert(!CurComponents.empty() &&
20139            "Invalid mappable expression information.");
20140 
20141     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
20142       // Add store "this" pointer to class in DSAStackTy for future checking
20143       DSAS->addMappedClassesQualTypes(TE->getType());
20144       // Try to find the associated user-defined mapper.
20145       ExprResult ER = buildUserDefinedMapperRef(
20146           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20147           VE->getType().getCanonicalType(), UnresolvedMapper);
20148       if (ER.isInvalid())
20149         continue;
20150       MVLI.UDMapperList.push_back(ER.get());
20151       // Skip restriction checking for variable or field declarations
20152       MVLI.ProcessedVarList.push_back(RE);
20153       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20154       MVLI.VarComponents.back().append(CurComponents.begin(),
20155                                        CurComponents.end());
20156       MVLI.VarBaseDeclarations.push_back(nullptr);
20157       continue;
20158     }
20159 
20160     // For the following checks, we rely on the base declaration which is
20161     // expected to be associated with the last component. The declaration is
20162     // expected to be a variable or a field (if 'this' is being mapped).
20163     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
20164     assert(CurDeclaration && "Null decl on map clause.");
20165     assert(
20166         CurDeclaration->isCanonicalDecl() &&
20167         "Expecting components to have associated only canonical declarations.");
20168 
20169     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
20170     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
20171 
20172     assert((VD || FD) && "Only variables or fields are expected here!");
20173     (void)FD;
20174 
20175     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
20176     // threadprivate variables cannot appear in a map clause.
20177     // OpenMP 4.5 [2.10.5, target update Construct]
20178     // threadprivate variables cannot appear in a from clause.
20179     if (VD && DSAS->isThreadPrivate(VD)) {
20180       if (NoDiagnose)
20181         continue;
20182       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
20183       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
20184           << getOpenMPClauseName(CKind);
20185       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
20186       continue;
20187     }
20188 
20189     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
20190     //  A list item cannot appear in both a map clause and a data-sharing
20191     //  attribute clause on the same construct.
20192 
20193     // Check conflicts with other map clause expressions. We check the conflicts
20194     // with the current construct separately from the enclosing data
20195     // environment, because the restrictions are different. We only have to
20196     // check conflicts across regions for the map clauses.
20197     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
20198                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
20199       break;
20200     if (CKind == OMPC_map &&
20201         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
20202         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
20203                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
20204       break;
20205 
20206     // OpenMP 4.5 [2.10.5, target update Construct]
20207     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
20208     //  If the type of a list item is a reference to a type T then the type will
20209     //  be considered to be T for all purposes of this clause.
20210     auto I = llvm::find_if(
20211         CurComponents,
20212         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
20213           return MC.getAssociatedDeclaration();
20214         });
20215     assert(I != CurComponents.end() && "Null decl on map clause.");
20216     (void)I;
20217     QualType Type;
20218     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
20219     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
20220     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
20221     if (ASE) {
20222       Type = ASE->getType().getNonReferenceType();
20223     } else if (OASE) {
20224       QualType BaseType =
20225           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
20226       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
20227         Type = ATy->getElementType();
20228       else
20229         Type = BaseType->getPointeeType();
20230       Type = Type.getNonReferenceType();
20231     } else if (OAShE) {
20232       Type = OAShE->getBase()->getType()->getPointeeType();
20233     } else {
20234       Type = VE->getType();
20235     }
20236 
20237     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
20238     // A list item in a to or from clause must have a mappable type.
20239     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
20240     //  A list item must have a mappable type.
20241     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
20242                            DSAS, Type, /*FullCheck=*/true))
20243       continue;
20244 
20245     if (CKind == OMPC_map) {
20246       // target enter data
20247       // OpenMP [2.10.2, Restrictions, p. 99]
20248       // A map-type must be specified in all map clauses and must be either
20249       // to or alloc.
20250       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
20251       if (DKind == OMPD_target_enter_data &&
20252           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
20253         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
20254             << (IsMapTypeImplicit ? 1 : 0)
20255             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
20256             << getOpenMPDirectiveName(DKind);
20257         continue;
20258       }
20259 
20260       // target exit_data
20261       // OpenMP [2.10.3, Restrictions, p. 102]
20262       // A map-type must be specified in all map clauses and must be either
20263       // from, release, or delete.
20264       if (DKind == OMPD_target_exit_data &&
20265           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
20266             MapType == OMPC_MAP_delete)) {
20267         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
20268             << (IsMapTypeImplicit ? 1 : 0)
20269             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
20270             << getOpenMPDirectiveName(DKind);
20271         continue;
20272       }
20273 
20274       // The 'ompx_hold' modifier is specifically intended to be used on a
20275       // 'target' or 'target data' directive to prevent data from being unmapped
20276       // during the associated statement.  It is not permitted on a 'target
20277       // enter data' or 'target exit data' directive, which have no associated
20278       // statement.
20279       if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
20280           HasHoldModifier) {
20281         SemaRef.Diag(StartLoc,
20282                      diag::err_omp_invalid_map_type_modifier_for_directive)
20283             << getOpenMPSimpleClauseTypeName(OMPC_map,
20284                                              OMPC_MAP_MODIFIER_ompx_hold)
20285             << getOpenMPDirectiveName(DKind);
20286         continue;
20287       }
20288 
20289       // target, target data
20290       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
20291       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
20292       // A map-type in a map clause must be to, from, tofrom or alloc
20293       if ((DKind == OMPD_target_data ||
20294            isOpenMPTargetExecutionDirective(DKind)) &&
20295           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
20296             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
20297         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
20298             << (IsMapTypeImplicit ? 1 : 0)
20299             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
20300             << getOpenMPDirectiveName(DKind);
20301         continue;
20302       }
20303 
20304       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
20305       // A list item cannot appear in both a map clause and a data-sharing
20306       // attribute clause on the same construct
20307       //
20308       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
20309       // A list item cannot appear in both a map clause and a data-sharing
20310       // attribute clause on the same construct unless the construct is a
20311       // combined construct.
20312       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
20313                   isOpenMPTargetExecutionDirective(DKind)) ||
20314                  DKind == OMPD_target)) {
20315         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
20316         if (isOpenMPPrivate(DVar.CKind)) {
20317           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
20318               << getOpenMPClauseName(DVar.CKind)
20319               << getOpenMPClauseName(OMPC_map)
20320               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
20321           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
20322           continue;
20323         }
20324       }
20325     }
20326 
20327     // Try to find the associated user-defined mapper.
20328     ExprResult ER = buildUserDefinedMapperRef(
20329         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
20330         Type.getCanonicalType(), UnresolvedMapper);
20331     if (ER.isInvalid())
20332       continue;
20333     MVLI.UDMapperList.push_back(ER.get());
20334 
20335     // Save the current expression.
20336     MVLI.ProcessedVarList.push_back(RE);
20337 
20338     // Store the components in the stack so that they can be used to check
20339     // against other clauses later on.
20340     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
20341                                           /*WhereFoundClauseKind=*/OMPC_map);
20342 
20343     // Save the components and declaration to create the clause. For purposes of
20344     // the clause creation, any component list that has has base 'this' uses
20345     // null as base declaration.
20346     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20347     MVLI.VarComponents.back().append(CurComponents.begin(),
20348                                      CurComponents.end());
20349     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
20350                                                            : CurDeclaration);
20351   }
20352 }
20353 
20354 OMPClause *Sema::ActOnOpenMPMapClause(
20355     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
20356     ArrayRef<SourceLocation> MapTypeModifiersLoc,
20357     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20358     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
20359     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20360     const OMPVarListLocTy &Locs, bool NoDiagnose,
20361     ArrayRef<Expr *> UnresolvedMappers) {
20362   OpenMPMapModifierKind Modifiers[] = {
20363       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
20364       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
20365       OMPC_MAP_MODIFIER_unknown};
20366   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
20367 
20368   // Process map-type-modifiers, flag errors for duplicate modifiers.
20369   unsigned Count = 0;
20370   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
20371     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
20372         llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
20373       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
20374       continue;
20375     }
20376     assert(Count < NumberOfOMPMapClauseModifiers &&
20377            "Modifiers exceed the allowed number of map type modifiers");
20378     Modifiers[Count] = MapTypeModifiers[I];
20379     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
20380     ++Count;
20381   }
20382 
20383   MappableVarListInfo MVLI(VarList);
20384   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
20385                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
20386                               MapType, Modifiers, IsMapTypeImplicit,
20387                               NoDiagnose);
20388 
20389   // We need to produce a map clause even if we don't have variables so that
20390   // other diagnostics related with non-existing map clauses are accurate.
20391   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
20392                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
20393                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
20394                               MapperIdScopeSpec.getWithLocInContext(Context),
20395                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
20396 }
20397 
20398 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
20399                                                TypeResult ParsedType) {
20400   assert(ParsedType.isUsable());
20401 
20402   QualType ReductionType = GetTypeFromParser(ParsedType.get());
20403   if (ReductionType.isNull())
20404     return QualType();
20405 
20406   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
20407   // A type name in a declare reduction directive cannot be a function type, an
20408   // array type, a reference type, or a type qualified with const, volatile or
20409   // restrict.
20410   if (ReductionType.hasQualifiers()) {
20411     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
20412     return QualType();
20413   }
20414 
20415   if (ReductionType->isFunctionType()) {
20416     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
20417     return QualType();
20418   }
20419   if (ReductionType->isReferenceType()) {
20420     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
20421     return QualType();
20422   }
20423   if (ReductionType->isArrayType()) {
20424     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
20425     return QualType();
20426   }
20427   return ReductionType;
20428 }
20429 
20430 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
20431     Scope *S, DeclContext *DC, DeclarationName Name,
20432     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
20433     AccessSpecifier AS, Decl *PrevDeclInScope) {
20434   SmallVector<Decl *, 8> Decls;
20435   Decls.reserve(ReductionTypes.size());
20436 
20437   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
20438                       forRedeclarationInCurContext());
20439   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
20440   // A reduction-identifier may not be re-declared in the current scope for the
20441   // same type or for a type that is compatible according to the base language
20442   // rules.
20443   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20444   OMPDeclareReductionDecl *PrevDRD = nullptr;
20445   bool InCompoundScope = true;
20446   if (S != nullptr) {
20447     // Find previous declaration with the same name not referenced in other
20448     // declarations.
20449     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20450     InCompoundScope =
20451         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20452     LookupName(Lookup, S);
20453     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20454                          /*AllowInlineNamespace=*/false);
20455     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
20456     LookupResult::Filter Filter = Lookup.makeFilter();
20457     while (Filter.hasNext()) {
20458       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
20459       if (InCompoundScope) {
20460         auto I = UsedAsPrevious.find(PrevDecl);
20461         if (I == UsedAsPrevious.end())
20462           UsedAsPrevious[PrevDecl] = false;
20463         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
20464           UsedAsPrevious[D] = true;
20465       }
20466       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20467           PrevDecl->getLocation();
20468     }
20469     Filter.done();
20470     if (InCompoundScope) {
20471       for (const auto &PrevData : UsedAsPrevious) {
20472         if (!PrevData.second) {
20473           PrevDRD = PrevData.first;
20474           break;
20475         }
20476       }
20477     }
20478   } else if (PrevDeclInScope != nullptr) {
20479     auto *PrevDRDInScope = PrevDRD =
20480         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
20481     do {
20482       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
20483           PrevDRDInScope->getLocation();
20484       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
20485     } while (PrevDRDInScope != nullptr);
20486   }
20487   for (const auto &TyData : ReductionTypes) {
20488     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
20489     bool Invalid = false;
20490     if (I != PreviousRedeclTypes.end()) {
20491       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
20492           << TyData.first;
20493       Diag(I->second, diag::note_previous_definition);
20494       Invalid = true;
20495     }
20496     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
20497     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
20498                                                 Name, TyData.first, PrevDRD);
20499     DC->addDecl(DRD);
20500     DRD->setAccess(AS);
20501     Decls.push_back(DRD);
20502     if (Invalid)
20503       DRD->setInvalidDecl();
20504     else
20505       PrevDRD = DRD;
20506   }
20507 
20508   return DeclGroupPtrTy::make(
20509       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
20510 }
20511 
20512 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
20513   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20514 
20515   // Enter new function scope.
20516   PushFunctionScope();
20517   setFunctionHasBranchProtectedScope();
20518   getCurFunction()->setHasOMPDeclareReductionCombiner();
20519 
20520   if (S != nullptr)
20521     PushDeclContext(S, DRD);
20522   else
20523     CurContext = DRD;
20524 
20525   PushExpressionEvaluationContext(
20526       ExpressionEvaluationContext::PotentiallyEvaluated);
20527 
20528   QualType ReductionType = DRD->getType();
20529   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
20530   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
20531   // uses semantics of argument handles by value, but it should be passed by
20532   // reference. C lang does not support references, so pass all parameters as
20533   // pointers.
20534   // Create 'T omp_in;' variable.
20535   VarDecl *OmpInParm =
20536       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
20537   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
20538   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
20539   // uses semantics of argument handles by value, but it should be passed by
20540   // reference. C lang does not support references, so pass all parameters as
20541   // pointers.
20542   // Create 'T omp_out;' variable.
20543   VarDecl *OmpOutParm =
20544       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
20545   if (S != nullptr) {
20546     PushOnScopeChains(OmpInParm, S);
20547     PushOnScopeChains(OmpOutParm, S);
20548   } else {
20549     DRD->addDecl(OmpInParm);
20550     DRD->addDecl(OmpOutParm);
20551   }
20552   Expr *InE =
20553       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
20554   Expr *OutE =
20555       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
20556   DRD->setCombinerData(InE, OutE);
20557 }
20558 
20559 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
20560   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20561   DiscardCleanupsInEvaluationContext();
20562   PopExpressionEvaluationContext();
20563 
20564   PopDeclContext();
20565   PopFunctionScopeInfo();
20566 
20567   if (Combiner != nullptr)
20568     DRD->setCombiner(Combiner);
20569   else
20570     DRD->setInvalidDecl();
20571 }
20572 
20573 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
20574   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20575 
20576   // Enter new function scope.
20577   PushFunctionScope();
20578   setFunctionHasBranchProtectedScope();
20579 
20580   if (S != nullptr)
20581     PushDeclContext(S, DRD);
20582   else
20583     CurContext = DRD;
20584 
20585   PushExpressionEvaluationContext(
20586       ExpressionEvaluationContext::PotentiallyEvaluated);
20587 
20588   QualType ReductionType = DRD->getType();
20589   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
20590   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
20591   // uses semantics of argument handles by value, but it should be passed by
20592   // reference. C lang does not support references, so pass all parameters as
20593   // pointers.
20594   // Create 'T omp_priv;' variable.
20595   VarDecl *OmpPrivParm =
20596       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
20597   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
20598   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
20599   // uses semantics of argument handles by value, but it should be passed by
20600   // reference. C lang does not support references, so pass all parameters as
20601   // pointers.
20602   // Create 'T omp_orig;' variable.
20603   VarDecl *OmpOrigParm =
20604       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
20605   if (S != nullptr) {
20606     PushOnScopeChains(OmpPrivParm, S);
20607     PushOnScopeChains(OmpOrigParm, S);
20608   } else {
20609     DRD->addDecl(OmpPrivParm);
20610     DRD->addDecl(OmpOrigParm);
20611   }
20612   Expr *OrigE =
20613       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
20614   Expr *PrivE =
20615       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
20616   DRD->setInitializerData(OrigE, PrivE);
20617   return OmpPrivParm;
20618 }
20619 
20620 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
20621                                                      VarDecl *OmpPrivParm) {
20622   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20623   DiscardCleanupsInEvaluationContext();
20624   PopExpressionEvaluationContext();
20625 
20626   PopDeclContext();
20627   PopFunctionScopeInfo();
20628 
20629   if (Initializer != nullptr) {
20630     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
20631   } else if (OmpPrivParm->hasInit()) {
20632     DRD->setInitializer(OmpPrivParm->getInit(),
20633                         OmpPrivParm->isDirectInit()
20634                             ? OMPDeclareReductionDecl::DirectInit
20635                             : OMPDeclareReductionDecl::CopyInit);
20636   } else {
20637     DRD->setInvalidDecl();
20638   }
20639 }
20640 
20641 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
20642     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
20643   for (Decl *D : DeclReductions.get()) {
20644     if (IsValid) {
20645       if (S)
20646         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
20647                           /*AddToContext=*/false);
20648     } else {
20649       D->setInvalidDecl();
20650     }
20651   }
20652   return DeclReductions;
20653 }
20654 
20655 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
20656   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
20657   QualType T = TInfo->getType();
20658   if (D.isInvalidType())
20659     return true;
20660 
20661   if (getLangOpts().CPlusPlus) {
20662     // Check that there are no default arguments (C++ only).
20663     CheckExtraCXXDefaultArguments(D);
20664   }
20665 
20666   return CreateParsedType(T, TInfo);
20667 }
20668 
20669 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
20670                                             TypeResult ParsedType) {
20671   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
20672 
20673   QualType MapperType = GetTypeFromParser(ParsedType.get());
20674   assert(!MapperType.isNull() && "Expect valid mapper type");
20675 
20676   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20677   //  The type must be of struct, union or class type in C and C++
20678   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
20679     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
20680     return QualType();
20681   }
20682   return MapperType;
20683 }
20684 
20685 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
20686     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
20687     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
20688     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
20689   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
20690                       forRedeclarationInCurContext());
20691   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20692   //  A mapper-identifier may not be redeclared in the current scope for the
20693   //  same type or for a type that is compatible according to the base language
20694   //  rules.
20695   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20696   OMPDeclareMapperDecl *PrevDMD = nullptr;
20697   bool InCompoundScope = true;
20698   if (S != nullptr) {
20699     // Find previous declaration with the same name not referenced in other
20700     // declarations.
20701     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20702     InCompoundScope =
20703         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20704     LookupName(Lookup, S);
20705     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20706                          /*AllowInlineNamespace=*/false);
20707     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
20708     LookupResult::Filter Filter = Lookup.makeFilter();
20709     while (Filter.hasNext()) {
20710       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
20711       if (InCompoundScope) {
20712         auto I = UsedAsPrevious.find(PrevDecl);
20713         if (I == UsedAsPrevious.end())
20714           UsedAsPrevious[PrevDecl] = false;
20715         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
20716           UsedAsPrevious[D] = true;
20717       }
20718       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20719           PrevDecl->getLocation();
20720     }
20721     Filter.done();
20722     if (InCompoundScope) {
20723       for (const auto &PrevData : UsedAsPrevious) {
20724         if (!PrevData.second) {
20725           PrevDMD = PrevData.first;
20726           break;
20727         }
20728       }
20729     }
20730   } else if (PrevDeclInScope) {
20731     auto *PrevDMDInScope = PrevDMD =
20732         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
20733     do {
20734       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
20735           PrevDMDInScope->getLocation();
20736       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
20737     } while (PrevDMDInScope != nullptr);
20738   }
20739   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
20740   bool Invalid = false;
20741   if (I != PreviousRedeclTypes.end()) {
20742     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
20743         << MapperType << Name;
20744     Diag(I->second, diag::note_previous_definition);
20745     Invalid = true;
20746   }
20747   // Build expressions for implicit maps of data members with 'default'
20748   // mappers.
20749   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
20750                                                   Clauses.end());
20751   if (LangOpts.OpenMP >= 50)
20752     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
20753   auto *DMD =
20754       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
20755                                    ClausesWithImplicit, PrevDMD);
20756   if (S)
20757     PushOnScopeChains(DMD, S);
20758   else
20759     DC->addDecl(DMD);
20760   DMD->setAccess(AS);
20761   if (Invalid)
20762     DMD->setInvalidDecl();
20763 
20764   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
20765   VD->setDeclContext(DMD);
20766   VD->setLexicalDeclContext(DMD);
20767   DMD->addDecl(VD);
20768   DMD->setMapperVarRef(MapperVarRef);
20769 
20770   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
20771 }
20772 
20773 ExprResult
20774 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
20775                                                SourceLocation StartLoc,
20776                                                DeclarationName VN) {
20777   TypeSourceInfo *TInfo =
20778       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
20779   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
20780                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
20781                              MapperType, TInfo, SC_None);
20782   if (S)
20783     PushOnScopeChains(VD, S, /*AddToContext=*/false);
20784   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
20785   DSAStack->addDeclareMapperVarRef(E);
20786   return E;
20787 }
20788 
20789 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
20790   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20791   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
20792   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
20793     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
20794       return true;
20795     if (VD->isUsableInConstantExpressions(Context))
20796       return true;
20797     return false;
20798   }
20799   return true;
20800 }
20801 
20802 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
20803   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20804   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
20805 }
20806 
20807 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
20808                                            SourceLocation StartLoc,
20809                                            SourceLocation LParenLoc,
20810                                            SourceLocation EndLoc) {
20811   Expr *ValExpr = NumTeams;
20812   Stmt *HelperValStmt = nullptr;
20813 
20814   // OpenMP [teams Constrcut, Restrictions]
20815   // The num_teams expression must evaluate to a positive integer value.
20816   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
20817                                  /*StrictlyPositive=*/true))
20818     return nullptr;
20819 
20820   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20821   OpenMPDirectiveKind CaptureRegion =
20822       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
20823   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20824     ValExpr = MakeFullExpr(ValExpr).get();
20825     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20826     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20827     HelperValStmt = buildPreInits(Context, Captures);
20828   }
20829 
20830   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
20831                                          StartLoc, LParenLoc, EndLoc);
20832 }
20833 
20834 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
20835                                               SourceLocation StartLoc,
20836                                               SourceLocation LParenLoc,
20837                                               SourceLocation EndLoc) {
20838   Expr *ValExpr = ThreadLimit;
20839   Stmt *HelperValStmt = nullptr;
20840 
20841   // OpenMP [teams Constrcut, Restrictions]
20842   // The thread_limit expression must evaluate to a positive integer value.
20843   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
20844                                  /*StrictlyPositive=*/true))
20845     return nullptr;
20846 
20847   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20848   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
20849       DKind, OMPC_thread_limit, LangOpts.OpenMP);
20850   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20851     ValExpr = MakeFullExpr(ValExpr).get();
20852     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20853     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20854     HelperValStmt = buildPreInits(Context, Captures);
20855   }
20856 
20857   return new (Context) OMPThreadLimitClause(
20858       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20859 }
20860 
20861 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
20862                                            SourceLocation StartLoc,
20863                                            SourceLocation LParenLoc,
20864                                            SourceLocation EndLoc) {
20865   Expr *ValExpr = Priority;
20866   Stmt *HelperValStmt = nullptr;
20867   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20868 
20869   // OpenMP [2.9.1, task Constrcut]
20870   // The priority-value is a non-negative numerical scalar expression.
20871   if (!isNonNegativeIntegerValue(
20872           ValExpr, *this, OMPC_priority,
20873           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
20874           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20875     return nullptr;
20876 
20877   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
20878                                          StartLoc, LParenLoc, EndLoc);
20879 }
20880 
20881 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
20882                                             SourceLocation StartLoc,
20883                                             SourceLocation LParenLoc,
20884                                             SourceLocation EndLoc) {
20885   Expr *ValExpr = Grainsize;
20886   Stmt *HelperValStmt = nullptr;
20887   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20888 
20889   // OpenMP [2.9.2, taskloop Constrcut]
20890   // The parameter of the grainsize clause must be a positive integer
20891   // expression.
20892   if (!isNonNegativeIntegerValue(
20893           ValExpr, *this, OMPC_grainsize,
20894           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20895           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20896     return nullptr;
20897 
20898   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
20899                                           StartLoc, LParenLoc, EndLoc);
20900 }
20901 
20902 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
20903                                            SourceLocation StartLoc,
20904                                            SourceLocation LParenLoc,
20905                                            SourceLocation EndLoc) {
20906   Expr *ValExpr = NumTasks;
20907   Stmt *HelperValStmt = nullptr;
20908   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20909 
20910   // OpenMP [2.9.2, taskloop Constrcut]
20911   // The parameter of the num_tasks clause must be a positive integer
20912   // expression.
20913   if (!isNonNegativeIntegerValue(
20914           ValExpr, *this, OMPC_num_tasks,
20915           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20916           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20917     return nullptr;
20918 
20919   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
20920                                          StartLoc, LParenLoc, EndLoc);
20921 }
20922 
20923 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
20924                                        SourceLocation LParenLoc,
20925                                        SourceLocation EndLoc) {
20926   // OpenMP [2.13.2, critical construct, Description]
20927   // ... where hint-expression is an integer constant expression that evaluates
20928   // to a valid lock hint.
20929   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
20930   if (HintExpr.isInvalid())
20931     return nullptr;
20932   return new (Context)
20933       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
20934 }
20935 
20936 /// Tries to find omp_event_handle_t type.
20937 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
20938                                 DSAStackTy *Stack) {
20939   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
20940   if (!OMPEventHandleT.isNull())
20941     return true;
20942   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
20943   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
20944   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20945     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
20946     return false;
20947   }
20948   Stack->setOMPEventHandleT(PT.get());
20949   return true;
20950 }
20951 
20952 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
20953                                          SourceLocation LParenLoc,
20954                                          SourceLocation EndLoc) {
20955   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
20956       !Evt->isInstantiationDependent() &&
20957       !Evt->containsUnexpandedParameterPack()) {
20958     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
20959       return nullptr;
20960     // OpenMP 5.0, 2.10.1 task Construct.
20961     // event-handle is a variable of the omp_event_handle_t type.
20962     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
20963     if (!Ref) {
20964       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20965           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20966       return nullptr;
20967     }
20968     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
20969     if (!VD) {
20970       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20971           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20972       return nullptr;
20973     }
20974     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
20975                                         VD->getType()) ||
20976         VD->getType().isConstant(Context)) {
20977       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20978           << "omp_event_handle_t" << 1 << VD->getType()
20979           << Evt->getSourceRange();
20980       return nullptr;
20981     }
20982     // OpenMP 5.0, 2.10.1 task Construct
20983     // [detach clause]... The event-handle will be considered as if it was
20984     // specified on a firstprivate clause.
20985     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
20986     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
20987         DVar.RefExpr) {
20988       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
20989           << getOpenMPClauseName(DVar.CKind)
20990           << getOpenMPClauseName(OMPC_firstprivate);
20991       reportOriginalDsa(*this, DSAStack, VD, DVar);
20992       return nullptr;
20993     }
20994   }
20995 
20996   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
20997 }
20998 
20999 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
21000     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
21001     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
21002     SourceLocation EndLoc) {
21003   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
21004     std::string Values;
21005     Values += "'";
21006     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
21007     Values += "'";
21008     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21009         << Values << getOpenMPClauseName(OMPC_dist_schedule);
21010     return nullptr;
21011   }
21012   Expr *ValExpr = ChunkSize;
21013   Stmt *HelperValStmt = nullptr;
21014   if (ChunkSize) {
21015     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
21016         !ChunkSize->isInstantiationDependent() &&
21017         !ChunkSize->containsUnexpandedParameterPack()) {
21018       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
21019       ExprResult Val =
21020           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
21021       if (Val.isInvalid())
21022         return nullptr;
21023 
21024       ValExpr = Val.get();
21025 
21026       // OpenMP [2.7.1, Restrictions]
21027       //  chunk_size must be a loop invariant integer expression with a positive
21028       //  value.
21029       if (Optional<llvm::APSInt> Result =
21030               ValExpr->getIntegerConstantExpr(Context)) {
21031         if (Result->isSigned() && !Result->isStrictlyPositive()) {
21032           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
21033               << "dist_schedule" << ChunkSize->getSourceRange();
21034           return nullptr;
21035         }
21036       } else if (getOpenMPCaptureRegionForClause(
21037                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
21038                      LangOpts.OpenMP) != OMPD_unknown &&
21039                  !CurContext->isDependentContext()) {
21040         ValExpr = MakeFullExpr(ValExpr).get();
21041         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
21042         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
21043         HelperValStmt = buildPreInits(Context, Captures);
21044       }
21045     }
21046   }
21047 
21048   return new (Context)
21049       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
21050                             Kind, ValExpr, HelperValStmt);
21051 }
21052 
21053 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
21054     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
21055     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
21056     SourceLocation KindLoc, SourceLocation EndLoc) {
21057   if (getLangOpts().OpenMP < 50) {
21058     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
21059         Kind != OMPC_DEFAULTMAP_scalar) {
21060       std::string Value;
21061       SourceLocation Loc;
21062       Value += "'";
21063       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
21064         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
21065                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
21066         Loc = MLoc;
21067       } else {
21068         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
21069                                                OMPC_DEFAULTMAP_scalar);
21070         Loc = KindLoc;
21071       }
21072       Value += "'";
21073       Diag(Loc, diag::err_omp_unexpected_clause_value)
21074           << Value << getOpenMPClauseName(OMPC_defaultmap);
21075       return nullptr;
21076     }
21077   } else {
21078     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
21079     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
21080                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
21081     if (!isDefaultmapKind || !isDefaultmapModifier) {
21082       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
21083       if (LangOpts.OpenMP == 50) {
21084         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
21085                                   "'firstprivate', 'none', 'default'";
21086         if (!isDefaultmapKind && isDefaultmapModifier) {
21087           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21088               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21089         } else if (isDefaultmapKind && !isDefaultmapModifier) {
21090           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21091               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21092         } else {
21093           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21094               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21095           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21096               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21097         }
21098       } else {
21099         StringRef ModifierValue =
21100             "'alloc', 'from', 'to', 'tofrom', "
21101             "'firstprivate', 'none', 'default', 'present'";
21102         if (!isDefaultmapKind && isDefaultmapModifier) {
21103           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21104               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21105         } else if (isDefaultmapKind && !isDefaultmapModifier) {
21106           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21107               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21108         } else {
21109           Diag(MLoc, diag::err_omp_unexpected_clause_value)
21110               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
21111           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21112               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
21113         }
21114       }
21115       return nullptr;
21116     }
21117 
21118     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
21119     //  At most one defaultmap clause for each category can appear on the
21120     //  directive.
21121     if (DSAStack->checkDefaultmapCategory(Kind)) {
21122       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
21123       return nullptr;
21124     }
21125   }
21126   if (Kind == OMPC_DEFAULTMAP_unknown) {
21127     // Variable category is not specified - mark all categories.
21128     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
21129     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
21130     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
21131   } else {
21132     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
21133   }
21134 
21135   return new (Context)
21136       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
21137 }
21138 
21139 bool Sema::ActOnStartOpenMPDeclareTargetContext(
21140     DeclareTargetContextInfo &DTCI) {
21141   DeclContext *CurLexicalContext = getCurLexicalContext();
21142   if (!CurLexicalContext->isFileContext() &&
21143       !CurLexicalContext->isExternCContext() &&
21144       !CurLexicalContext->isExternCXXContext() &&
21145       !isa<CXXRecordDecl>(CurLexicalContext) &&
21146       !isa<ClassTemplateDecl>(CurLexicalContext) &&
21147       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
21148       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
21149     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
21150     return false;
21151   }
21152   DeclareTargetNesting.push_back(DTCI);
21153   return true;
21154 }
21155 
21156 const Sema::DeclareTargetContextInfo
21157 Sema::ActOnOpenMPEndDeclareTargetDirective() {
21158   assert(!DeclareTargetNesting.empty() &&
21159          "check isInOpenMPDeclareTargetContext() first!");
21160   return DeclareTargetNesting.pop_back_val();
21161 }
21162 
21163 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
21164     DeclareTargetContextInfo &DTCI) {
21165   for (auto &It : DTCI.ExplicitlyMapped)
21166     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI);
21167 }
21168 
21169 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
21170                                                CXXScopeSpec &ScopeSpec,
21171                                                const DeclarationNameInfo &Id) {
21172   LookupResult Lookup(*this, Id, LookupOrdinaryName);
21173   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
21174 
21175   if (Lookup.isAmbiguous())
21176     return nullptr;
21177   Lookup.suppressDiagnostics();
21178 
21179   if (!Lookup.isSingleResult()) {
21180     VarOrFuncDeclFilterCCC CCC(*this);
21181     if (TypoCorrection Corrected =
21182             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
21183                         CTK_ErrorRecovery)) {
21184       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
21185                                   << Id.getName());
21186       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
21187       return nullptr;
21188     }
21189 
21190     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
21191     return nullptr;
21192   }
21193 
21194   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
21195   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
21196       !isa<FunctionTemplateDecl>(ND)) {
21197     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
21198     return nullptr;
21199   }
21200   return ND;
21201 }
21202 
21203 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
21204                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
21205                                         DeclareTargetContextInfo &DTCI) {
21206   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
21207           isa<FunctionTemplateDecl>(ND)) &&
21208          "Expected variable, function or function template.");
21209 
21210   // Diagnose marking after use as it may lead to incorrect diagnosis and
21211   // codegen.
21212   if (LangOpts.OpenMP >= 50 &&
21213       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
21214     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
21215 
21216   // Explicit declare target lists have precedence.
21217   const unsigned Level = -1;
21218 
21219   auto *VD = cast<ValueDecl>(ND);
21220   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
21221       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
21222   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT &&
21223       ActiveAttr.getValue()->getLevel() == Level) {
21224     Diag(Loc, diag::err_omp_device_type_mismatch)
21225         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
21226         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
21227                ActiveAttr.getValue()->getDevType());
21228     return;
21229   }
21230   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
21231       ActiveAttr.getValue()->getLevel() == Level) {
21232     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
21233     return;
21234   }
21235 
21236   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
21237     return;
21238 
21239   Expr *IndirectE = nullptr;
21240   bool IsIndirect = false;
21241   if (DTCI.Indirect.hasValue()) {
21242     IndirectE = DTCI.Indirect.getValue();
21243     if (!IndirectE)
21244       IsIndirect = true;
21245   }
21246   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
21247       Context, MT, DTCI.DT, IndirectE, IsIndirect, Level,
21248       SourceRange(Loc, Loc));
21249   ND->addAttr(A);
21250   if (ASTMutationListener *ML = Context.getASTMutationListener())
21251     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
21252   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
21253 }
21254 
21255 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
21256                                      Sema &SemaRef, Decl *D) {
21257   if (!D || !isa<VarDecl>(D))
21258     return;
21259   auto *VD = cast<VarDecl>(D);
21260   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
21261       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
21262   if (SemaRef.LangOpts.OpenMP >= 50 &&
21263       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
21264        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
21265       VD->hasGlobalStorage()) {
21266     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
21267       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
21268       // If a lambda declaration and definition appears between a
21269       // declare target directive and the matching end declare target
21270       // directive, all variables that are captured by the lambda
21271       // expression must also appear in a to clause.
21272       SemaRef.Diag(VD->getLocation(),
21273                    diag::err_omp_lambda_capture_in_declare_target_not_to);
21274       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
21275           << VD << 0 << SR;
21276       return;
21277     }
21278   }
21279   if (MapTy.hasValue())
21280     return;
21281   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
21282   SemaRef.Diag(SL, diag::note_used_here) << SR;
21283 }
21284 
21285 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
21286                                    Sema &SemaRef, DSAStackTy *Stack,
21287                                    ValueDecl *VD) {
21288   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
21289          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
21290                            /*FullCheck=*/false);
21291 }
21292 
21293 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
21294                                             SourceLocation IdLoc) {
21295   if (!D || D->isInvalidDecl())
21296     return;
21297   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
21298   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
21299   if (auto *VD = dyn_cast<VarDecl>(D)) {
21300     // Only global variables can be marked as declare target.
21301     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
21302         !VD->isStaticDataMember())
21303       return;
21304     // 2.10.6: threadprivate variable cannot appear in a declare target
21305     // directive.
21306     if (DSAStack->isThreadPrivate(VD)) {
21307       Diag(SL, diag::err_omp_threadprivate_in_target);
21308       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
21309       return;
21310     }
21311   }
21312   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
21313     D = FTD->getTemplatedDecl();
21314   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
21315     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
21316         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
21317     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
21318       Diag(IdLoc, diag::err_omp_function_in_link_clause);
21319       Diag(FD->getLocation(), diag::note_defined_here) << FD;
21320       return;
21321     }
21322   }
21323   if (auto *VD = dyn_cast<ValueDecl>(D)) {
21324     // Problem if any with var declared with incomplete type will be reported
21325     // as normal, so no need to check it here.
21326     if ((E || !VD->getType()->isIncompleteType()) &&
21327         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
21328       return;
21329     if (!E && isInOpenMPDeclareTargetContext()) {
21330       // Checking declaration inside declare target region.
21331       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
21332           isa<FunctionTemplateDecl>(D)) {
21333         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
21334             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
21335         unsigned Level = DeclareTargetNesting.size();
21336         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
21337           return;
21338         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
21339         Expr *IndirectE = nullptr;
21340         bool IsIndirect = false;
21341         if (DTCI.Indirect.hasValue()) {
21342           IndirectE = DTCI.Indirect.getValue();
21343           if (!IndirectE)
21344             IsIndirect = true;
21345         }
21346         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
21347             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE,
21348             IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc));
21349         D->addAttr(A);
21350         if (ASTMutationListener *ML = Context.getASTMutationListener())
21351           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
21352       }
21353       return;
21354     }
21355   }
21356   if (!E)
21357     return;
21358   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
21359 }
21360 
21361 OMPClause *Sema::ActOnOpenMPToClause(
21362     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
21363     ArrayRef<SourceLocation> MotionModifiersLoc,
21364     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
21365     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
21366     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
21367   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
21368                                           OMPC_MOTION_MODIFIER_unknown};
21369   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
21370 
21371   // Process motion-modifiers, flag errors for duplicate modifiers.
21372   unsigned Count = 0;
21373   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
21374     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
21375         llvm::is_contained(Modifiers, MotionModifiers[I])) {
21376       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
21377       continue;
21378     }
21379     assert(Count < NumberOfOMPMotionModifiers &&
21380            "Modifiers exceed the allowed number of motion modifiers");
21381     Modifiers[Count] = MotionModifiers[I];
21382     ModifiersLoc[Count] = MotionModifiersLoc[I];
21383     ++Count;
21384   }
21385 
21386   MappableVarListInfo MVLI(VarList);
21387   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
21388                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
21389   if (MVLI.ProcessedVarList.empty())
21390     return nullptr;
21391 
21392   return OMPToClause::Create(
21393       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
21394       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
21395       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
21396 }
21397 
21398 OMPClause *Sema::ActOnOpenMPFromClause(
21399     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
21400     ArrayRef<SourceLocation> MotionModifiersLoc,
21401     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
21402     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
21403     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
21404   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
21405                                           OMPC_MOTION_MODIFIER_unknown};
21406   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
21407 
21408   // Process motion-modifiers, flag errors for duplicate modifiers.
21409   unsigned Count = 0;
21410   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
21411     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
21412         llvm::is_contained(Modifiers, MotionModifiers[I])) {
21413       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
21414       continue;
21415     }
21416     assert(Count < NumberOfOMPMotionModifiers &&
21417            "Modifiers exceed the allowed number of motion modifiers");
21418     Modifiers[Count] = MotionModifiers[I];
21419     ModifiersLoc[Count] = MotionModifiersLoc[I];
21420     ++Count;
21421   }
21422 
21423   MappableVarListInfo MVLI(VarList);
21424   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
21425                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
21426   if (MVLI.ProcessedVarList.empty())
21427     return nullptr;
21428 
21429   return OMPFromClause::Create(
21430       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
21431       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
21432       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
21433 }
21434 
21435 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
21436                                                const OMPVarListLocTy &Locs) {
21437   MappableVarListInfo MVLI(VarList);
21438   SmallVector<Expr *, 8> PrivateCopies;
21439   SmallVector<Expr *, 8> Inits;
21440 
21441   for (Expr *RefExpr : VarList) {
21442     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
21443     SourceLocation ELoc;
21444     SourceRange ERange;
21445     Expr *SimpleRefExpr = RefExpr;
21446     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21447     if (Res.second) {
21448       // It will be analyzed later.
21449       MVLI.ProcessedVarList.push_back(RefExpr);
21450       PrivateCopies.push_back(nullptr);
21451       Inits.push_back(nullptr);
21452     }
21453     ValueDecl *D = Res.first;
21454     if (!D)
21455       continue;
21456 
21457     QualType Type = D->getType();
21458     Type = Type.getNonReferenceType().getUnqualifiedType();
21459 
21460     auto *VD = dyn_cast<VarDecl>(D);
21461 
21462     // Item should be a pointer or reference to pointer.
21463     if (!Type->isPointerType()) {
21464       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
21465           << 0 << RefExpr->getSourceRange();
21466       continue;
21467     }
21468 
21469     // Build the private variable and the expression that refers to it.
21470     auto VDPrivate =
21471         buildVarDecl(*this, ELoc, Type, D->getName(),
21472                      D->hasAttrs() ? &D->getAttrs() : nullptr,
21473                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
21474     if (VDPrivate->isInvalidDecl())
21475       continue;
21476 
21477     CurContext->addDecl(VDPrivate);
21478     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
21479         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
21480 
21481     // Add temporary variable to initialize the private copy of the pointer.
21482     VarDecl *VDInit =
21483         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
21484     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
21485         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
21486     AddInitializerToDecl(VDPrivate,
21487                          DefaultLvalueConversion(VDInitRefExpr).get(),
21488                          /*DirectInit=*/false);
21489 
21490     // If required, build a capture to implement the privatization initialized
21491     // with the current list item value.
21492     DeclRefExpr *Ref = nullptr;
21493     if (!VD)
21494       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21495     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21496     PrivateCopies.push_back(VDPrivateRefExpr);
21497     Inits.push_back(VDInitRefExpr);
21498 
21499     // We need to add a data sharing attribute for this variable to make sure it
21500     // is correctly captured. A variable that shows up in a use_device_ptr has
21501     // similar properties of a first private variable.
21502     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21503 
21504     // Create a mappable component for the list item. List items in this clause
21505     // only need a component.
21506     MVLI.VarBaseDeclarations.push_back(D);
21507     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21508     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
21509                                            /*IsNonContiguous=*/false);
21510   }
21511 
21512   if (MVLI.ProcessedVarList.empty())
21513     return nullptr;
21514 
21515   return OMPUseDevicePtrClause::Create(
21516       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
21517       MVLI.VarBaseDeclarations, MVLI.VarComponents);
21518 }
21519 
21520 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
21521                                                 const OMPVarListLocTy &Locs) {
21522   MappableVarListInfo MVLI(VarList);
21523 
21524   for (Expr *RefExpr : VarList) {
21525     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
21526     SourceLocation ELoc;
21527     SourceRange ERange;
21528     Expr *SimpleRefExpr = RefExpr;
21529     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21530                               /*AllowArraySection=*/true);
21531     if (Res.second) {
21532       // It will be analyzed later.
21533       MVLI.ProcessedVarList.push_back(RefExpr);
21534     }
21535     ValueDecl *D = Res.first;
21536     if (!D)
21537       continue;
21538     auto *VD = dyn_cast<VarDecl>(D);
21539 
21540     // If required, build a capture to implement the privatization initialized
21541     // with the current list item value.
21542     DeclRefExpr *Ref = nullptr;
21543     if (!VD)
21544       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21545     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21546 
21547     // We need to add a data sharing attribute for this variable to make sure it
21548     // is correctly captured. A variable that shows up in a use_device_addr has
21549     // similar properties of a first private variable.
21550     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21551 
21552     // Create a mappable component for the list item. List items in this clause
21553     // only need a component.
21554     MVLI.VarBaseDeclarations.push_back(D);
21555     MVLI.VarComponents.emplace_back();
21556     Expr *Component = SimpleRefExpr;
21557     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
21558                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
21559       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
21560     MVLI.VarComponents.back().emplace_back(Component, D,
21561                                            /*IsNonContiguous=*/false);
21562   }
21563 
21564   if (MVLI.ProcessedVarList.empty())
21565     return nullptr;
21566 
21567   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21568                                         MVLI.VarBaseDeclarations,
21569                                         MVLI.VarComponents);
21570 }
21571 
21572 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
21573                                               const OMPVarListLocTy &Locs) {
21574   MappableVarListInfo MVLI(VarList);
21575   for (Expr *RefExpr : VarList) {
21576     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
21577     SourceLocation ELoc;
21578     SourceRange ERange;
21579     Expr *SimpleRefExpr = RefExpr;
21580     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21581     if (Res.second) {
21582       // It will be analyzed later.
21583       MVLI.ProcessedVarList.push_back(RefExpr);
21584     }
21585     ValueDecl *D = Res.first;
21586     if (!D)
21587       continue;
21588 
21589     QualType Type = D->getType();
21590     // item should be a pointer or array or reference to pointer or array
21591     if (!Type.getNonReferenceType()->isPointerType() &&
21592         !Type.getNonReferenceType()->isArrayType()) {
21593       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
21594           << 0 << RefExpr->getSourceRange();
21595       continue;
21596     }
21597 
21598     // Check if the declaration in the clause does not show up in any data
21599     // sharing attribute.
21600     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21601     if (isOpenMPPrivate(DVar.CKind)) {
21602       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21603           << getOpenMPClauseName(DVar.CKind)
21604           << getOpenMPClauseName(OMPC_is_device_ptr)
21605           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
21606       reportOriginalDsa(*this, DSAStack, D, DVar);
21607       continue;
21608     }
21609 
21610     const Expr *ConflictExpr;
21611     if (DSAStack->checkMappableExprComponentListsForDecl(
21612             D, /*CurrentRegionOnly=*/true,
21613             [&ConflictExpr](
21614                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
21615                 OpenMPClauseKind) -> bool {
21616               ConflictExpr = R.front().getAssociatedExpression();
21617               return true;
21618             })) {
21619       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
21620       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
21621           << ConflictExpr->getSourceRange();
21622       continue;
21623     }
21624 
21625     // Store the components in the stack so that they can be used to check
21626     // against other clauses later on.
21627     OMPClauseMappableExprCommon::MappableComponent MC(
21628         SimpleRefExpr, D, /*IsNonContiguous=*/false);
21629     DSAStack->addMappableExpressionComponents(
21630         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
21631 
21632     // Record the expression we've just processed.
21633     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
21634 
21635     // Create a mappable component for the list item. List items in this clause
21636     // only need a component. We use a null declaration to signal fields in
21637     // 'this'.
21638     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
21639             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
21640            "Unexpected device pointer expression!");
21641     MVLI.VarBaseDeclarations.push_back(
21642         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
21643     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21644     MVLI.VarComponents.back().push_back(MC);
21645   }
21646 
21647   if (MVLI.ProcessedVarList.empty())
21648     return nullptr;
21649 
21650   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21651                                       MVLI.VarBaseDeclarations,
21652                                       MVLI.VarComponents);
21653 }
21654 
21655 OMPClause *Sema::ActOnOpenMPAllocateClause(
21656     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
21657     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
21658   if (Allocator) {
21659     // OpenMP [2.11.4 allocate Clause, Description]
21660     // allocator is an expression of omp_allocator_handle_t type.
21661     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
21662       return nullptr;
21663 
21664     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
21665     if (AllocatorRes.isInvalid())
21666       return nullptr;
21667     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
21668                                              DSAStack->getOMPAllocatorHandleT(),
21669                                              Sema::AA_Initializing,
21670                                              /*AllowExplicit=*/true);
21671     if (AllocatorRes.isInvalid())
21672       return nullptr;
21673     Allocator = AllocatorRes.get();
21674   } else {
21675     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
21676     // allocate clauses that appear on a target construct or on constructs in a
21677     // target region must specify an allocator expression unless a requires
21678     // directive with the dynamic_allocators clause is present in the same
21679     // compilation unit.
21680     if (LangOpts.OpenMPIsDevice &&
21681         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
21682       targetDiag(StartLoc, diag::err_expected_allocator_expression);
21683   }
21684   // Analyze and build list of variables.
21685   SmallVector<Expr *, 8> Vars;
21686   for (Expr *RefExpr : VarList) {
21687     assert(RefExpr && "NULL expr in OpenMP private clause.");
21688     SourceLocation ELoc;
21689     SourceRange ERange;
21690     Expr *SimpleRefExpr = RefExpr;
21691     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21692     if (Res.second) {
21693       // It will be analyzed later.
21694       Vars.push_back(RefExpr);
21695     }
21696     ValueDecl *D = Res.first;
21697     if (!D)
21698       continue;
21699 
21700     auto *VD = dyn_cast<VarDecl>(D);
21701     DeclRefExpr *Ref = nullptr;
21702     if (!VD && !CurContext->isDependentContext())
21703       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
21704     Vars.push_back((VD || CurContext->isDependentContext())
21705                        ? RefExpr->IgnoreParens()
21706                        : Ref);
21707   }
21708 
21709   if (Vars.empty())
21710     return nullptr;
21711 
21712   if (Allocator)
21713     DSAStack->addInnerAllocatorExpr(Allocator);
21714   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
21715                                    ColonLoc, EndLoc, Vars);
21716 }
21717 
21718 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
21719                                               SourceLocation StartLoc,
21720                                               SourceLocation LParenLoc,
21721                                               SourceLocation EndLoc) {
21722   SmallVector<Expr *, 8> Vars;
21723   for (Expr *RefExpr : VarList) {
21724     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21725     SourceLocation ELoc;
21726     SourceRange ERange;
21727     Expr *SimpleRefExpr = RefExpr;
21728     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21729     if (Res.second)
21730       // It will be analyzed later.
21731       Vars.push_back(RefExpr);
21732     ValueDecl *D = Res.first;
21733     if (!D)
21734       continue;
21735 
21736     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
21737     // A list-item cannot appear in more than one nontemporal clause.
21738     if (const Expr *PrevRef =
21739             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
21740       Diag(ELoc, diag::err_omp_used_in_clause_twice)
21741           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
21742       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
21743           << getOpenMPClauseName(OMPC_nontemporal);
21744       continue;
21745     }
21746 
21747     Vars.push_back(RefExpr);
21748   }
21749 
21750   if (Vars.empty())
21751     return nullptr;
21752 
21753   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21754                                       Vars);
21755 }
21756 
21757 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
21758                                             SourceLocation StartLoc,
21759                                             SourceLocation LParenLoc,
21760                                             SourceLocation EndLoc) {
21761   SmallVector<Expr *, 8> Vars;
21762   for (Expr *RefExpr : VarList) {
21763     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21764     SourceLocation ELoc;
21765     SourceRange ERange;
21766     Expr *SimpleRefExpr = RefExpr;
21767     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21768                               /*AllowArraySection=*/true);
21769     if (Res.second)
21770       // It will be analyzed later.
21771       Vars.push_back(RefExpr);
21772     ValueDecl *D = Res.first;
21773     if (!D)
21774       continue;
21775 
21776     const DSAStackTy::DSAVarData DVar =
21777         DSAStack->getTopDSA(D, /*FromParent=*/true);
21778     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21779     // A list item that appears in the inclusive or exclusive clause must appear
21780     // in a reduction clause with the inscan modifier on the enclosing
21781     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21782     if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
21783       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21784           << RefExpr->getSourceRange();
21785 
21786     if (DSAStack->getParentDirective() != OMPD_unknown)
21787       DSAStack->markDeclAsUsedInScanDirective(D);
21788     Vars.push_back(RefExpr);
21789   }
21790 
21791   if (Vars.empty())
21792     return nullptr;
21793 
21794   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21795 }
21796 
21797 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
21798                                             SourceLocation StartLoc,
21799                                             SourceLocation LParenLoc,
21800                                             SourceLocation EndLoc) {
21801   SmallVector<Expr *, 8> Vars;
21802   for (Expr *RefExpr : VarList) {
21803     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21804     SourceLocation ELoc;
21805     SourceRange ERange;
21806     Expr *SimpleRefExpr = RefExpr;
21807     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21808                               /*AllowArraySection=*/true);
21809     if (Res.second)
21810       // It will be analyzed later.
21811       Vars.push_back(RefExpr);
21812     ValueDecl *D = Res.first;
21813     if (!D)
21814       continue;
21815 
21816     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
21817     DSAStackTy::DSAVarData DVar;
21818     if (ParentDirective != OMPD_unknown)
21819       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
21820     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21821     // A list item that appears in the inclusive or exclusive clause must appear
21822     // in a reduction clause with the inscan modifier on the enclosing
21823     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21824     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
21825         DVar.Modifier != OMPC_REDUCTION_inscan) {
21826       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21827           << RefExpr->getSourceRange();
21828     } else {
21829       DSAStack->markDeclAsUsedInScanDirective(D);
21830     }
21831     Vars.push_back(RefExpr);
21832   }
21833 
21834   if (Vars.empty())
21835     return nullptr;
21836 
21837   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21838 }
21839 
21840 /// Tries to find omp_alloctrait_t type.
21841 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
21842   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
21843   if (!OMPAlloctraitT.isNull())
21844     return true;
21845   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
21846   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
21847   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21848     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
21849     return false;
21850   }
21851   Stack->setOMPAlloctraitT(PT.get());
21852   return true;
21853 }
21854 
21855 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
21856     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
21857     ArrayRef<UsesAllocatorsData> Data) {
21858   // OpenMP [2.12.5, target Construct]
21859   // allocator is an identifier of omp_allocator_handle_t type.
21860   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
21861     return nullptr;
21862   // OpenMP [2.12.5, target Construct]
21863   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
21864   if (llvm::any_of(
21865           Data,
21866           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
21867       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
21868     return nullptr;
21869   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
21870   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
21871     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
21872     StringRef Allocator =
21873         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
21874     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
21875     PredefinedAllocators.insert(LookupSingleName(
21876         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
21877   }
21878 
21879   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
21880   for (const UsesAllocatorsData &D : Data) {
21881     Expr *AllocatorExpr = nullptr;
21882     // Check allocator expression.
21883     if (D.Allocator->isTypeDependent()) {
21884       AllocatorExpr = D.Allocator;
21885     } else {
21886       // Traits were specified - need to assign new allocator to the specified
21887       // allocator, so it must be an lvalue.
21888       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
21889       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
21890       bool IsPredefinedAllocator = false;
21891       if (DRE)
21892         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
21893       if (!DRE ||
21894           !(Context.hasSameUnqualifiedType(
21895                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
21896             Context.typesAreCompatible(AllocatorExpr->getType(),
21897                                        DSAStack->getOMPAllocatorHandleT(),
21898                                        /*CompareUnqualified=*/true)) ||
21899           (!IsPredefinedAllocator &&
21900            (AllocatorExpr->getType().isConstant(Context) ||
21901             !AllocatorExpr->isLValue()))) {
21902         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
21903             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
21904             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
21905         continue;
21906       }
21907       // OpenMP [2.12.5, target Construct]
21908       // Predefined allocators appearing in a uses_allocators clause cannot have
21909       // traits specified.
21910       if (IsPredefinedAllocator && D.AllocatorTraits) {
21911         Diag(D.AllocatorTraits->getExprLoc(),
21912              diag::err_omp_predefined_allocator_with_traits)
21913             << D.AllocatorTraits->getSourceRange();
21914         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
21915             << cast<NamedDecl>(DRE->getDecl())->getName()
21916             << D.Allocator->getSourceRange();
21917         continue;
21918       }
21919       // OpenMP [2.12.5, target Construct]
21920       // Non-predefined allocators appearing in a uses_allocators clause must
21921       // have traits specified.
21922       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
21923         Diag(D.Allocator->getExprLoc(),
21924              diag::err_omp_nonpredefined_allocator_without_traits);
21925         continue;
21926       }
21927       // No allocator traits - just convert it to rvalue.
21928       if (!D.AllocatorTraits)
21929         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
21930       DSAStack->addUsesAllocatorsDecl(
21931           DRE->getDecl(),
21932           IsPredefinedAllocator
21933               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
21934               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
21935     }
21936     Expr *AllocatorTraitsExpr = nullptr;
21937     if (D.AllocatorTraits) {
21938       if (D.AllocatorTraits->isTypeDependent()) {
21939         AllocatorTraitsExpr = D.AllocatorTraits;
21940       } else {
21941         // OpenMP [2.12.5, target Construct]
21942         // Arrays that contain allocator traits that appear in a uses_allocators
21943         // clause must be constant arrays, have constant values and be defined
21944         // in the same scope as the construct in which the clause appears.
21945         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
21946         // Check that traits expr is a constant array.
21947         QualType TraitTy;
21948         if (const ArrayType *Ty =
21949                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
21950           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
21951             TraitTy = ConstArrayTy->getElementType();
21952         if (TraitTy.isNull() ||
21953             !(Context.hasSameUnqualifiedType(TraitTy,
21954                                              DSAStack->getOMPAlloctraitT()) ||
21955               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
21956                                          /*CompareUnqualified=*/true))) {
21957           Diag(D.AllocatorTraits->getExprLoc(),
21958                diag::err_omp_expected_array_alloctraits)
21959               << AllocatorTraitsExpr->getType();
21960           continue;
21961         }
21962         // Do not map by default allocator traits if it is a standalone
21963         // variable.
21964         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
21965           DSAStack->addUsesAllocatorsDecl(
21966               DRE->getDecl(),
21967               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
21968       }
21969     }
21970     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
21971     NewD.Allocator = AllocatorExpr;
21972     NewD.AllocatorTraits = AllocatorTraitsExpr;
21973     NewD.LParenLoc = D.LParenLoc;
21974     NewD.RParenLoc = D.RParenLoc;
21975   }
21976   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21977                                          NewData);
21978 }
21979 
21980 OMPClause *Sema::ActOnOpenMPAffinityClause(
21981     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
21982     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
21983   SmallVector<Expr *, 8> Vars;
21984   for (Expr *RefExpr : Locators) {
21985     assert(RefExpr && "NULL expr in OpenMP shared clause.");
21986     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
21987       // It will be analyzed later.
21988       Vars.push_back(RefExpr);
21989       continue;
21990     }
21991 
21992     SourceLocation ELoc = RefExpr->getExprLoc();
21993     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
21994 
21995     if (!SimpleExpr->isLValue()) {
21996       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21997           << 1 << 0 << RefExpr->getSourceRange();
21998       continue;
21999     }
22000 
22001     ExprResult Res;
22002     {
22003       Sema::TentativeAnalysisScope Trap(*this);
22004       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
22005     }
22006     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
22007         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
22008       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
22009           << 1 << 0 << RefExpr->getSourceRange();
22010       continue;
22011     }
22012     Vars.push_back(SimpleExpr);
22013   }
22014 
22015   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
22016                                    EndLoc, Modifier, Vars);
22017 }
22018 
22019 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
22020                                        SourceLocation KindLoc,
22021                                        SourceLocation StartLoc,
22022                                        SourceLocation LParenLoc,
22023                                        SourceLocation EndLoc) {
22024   if (Kind == OMPC_BIND_unknown) {
22025     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
22026         << getListOfPossibleValues(OMPC_bind, /*First=*/0,
22027                                    /*Last=*/unsigned(OMPC_BIND_unknown))
22028         << getOpenMPClauseName(OMPC_bind);
22029     return nullptr;
22030   }
22031 
22032   return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
22033                                EndLoc);
22034 }
22035