1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements semantic analysis for OpenMP directives and
11 /// clauses.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/Basic/OpenMPKinds.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "llvm/ADT/PointerEmbeddedInt.h"
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37 
38 static const Expr *checkMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
49 };
50 
51 /// Attributes of the defaultmap clause.
52 enum DefaultMapAttributes {
53   DMA_unspecified,   /// Default mapping is not specified.
54   DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55 };
56 
57 /// Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy {
60 public:
61   struct DSAVarData {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     const Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70                SourceLocation ImplicitDSALoc)
71         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73   };
74   using OperatorOffsetTy =
75       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76   using DoacrossDependMapTy =
77       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78 
79 private:
80   struct DSAInfo {
81     OpenMPClauseKind Attributes = OMPC_unknown;
82     /// Pointer to a reference expression and a flag which shows that the
83     /// variable is marked as lastprivate(true) or not (false).
84     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85     DeclRefExpr *PrivateCopy = nullptr;
86   };
87   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88   using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90   using LoopControlVariablesMapTy =
91       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92   /// Struct that associates a component with the clause kind where they are
93   /// found.
94   struct MappedExprComponentTy {
95     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96     OpenMPClauseKind Kind = OMPC_unknown;
97   };
98   using MappedExprComponentsTy =
99       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100   using CriticalsWithHintsTy =
101       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102   struct ReductionData {
103     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104     SourceRange ReductionRange;
105     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106     ReductionData() = default;
107     void set(BinaryOperatorKind BO, SourceRange RR) {
108       ReductionRange = RR;
109       ReductionOp = BO;
110     }
111     void set(const Expr *RefExpr, SourceRange RR) {
112       ReductionRange = RR;
113       ReductionOp = RefExpr;
114     }
115   };
116   using DeclReductionMapTy =
117       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118 
119   struct SharingMapTy {
120     DeclSAMapTy SharingMap;
121     DeclReductionMapTy ReductionMap;
122     AlignedMapTy AlignedMap;
123     MappedExprComponentsTy MappedExprComponents;
124     LoopControlVariablesMapTy LCVMap;
125     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126     SourceLocation DefaultAttrLoc;
127     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128     SourceLocation DefaultMapAttrLoc;
129     OpenMPDirectiveKind Directive = OMPD_unknown;
130     DeclarationNameInfo DirectiveName;
131     Scope *CurScope = nullptr;
132     SourceLocation ConstructLoc;
133     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134     /// get the data (loop counters etc.) about enclosing loop-based construct.
135     /// This data is required during codegen.
136     DoacrossDependMapTy DoacrossDepends;
137     /// first argument (Expr *) contains optional argument of the
138     /// 'ordered' clause, the second one is true if the regions has 'ordered'
139     /// clause, false otherwise.
140     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141     unsigned AssociatedLoops = 1;
142     const Decl *PossiblyLoopCounter = nullptr;
143     bool NowaitRegion = false;
144     bool CancelRegion = false;
145     bool LoopStart = false;
146     SourceLocation InnerTeamsRegionLoc;
147     /// Reference to the taskgroup task_reduction reference expression.
148     Expr *TaskgroupReductionRef = nullptr;
149     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
150                  Scope *CurScope, SourceLocation Loc)
151         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
152           ConstructLoc(Loc) {}
153     SharingMapTy() = default;
154   };
155 
156   using StackTy = SmallVector<SharingMapTy, 4>;
157 
158   /// Stack of used declaration and their data-sharing attributes.
159   DeclSAMapTy Threadprivates;
160   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
161   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
162   /// true, if check for DSA must be from parent directive, false, if
163   /// from current directive.
164   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
165   Sema &SemaRef;
166   bool ForceCapturing = false;
167   CriticalsWithHintsTy Criticals;
168 
169   using iterator = StackTy::const_reverse_iterator;
170 
171   DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
172 
173   /// Checks if the variable is a local for OpenMP region.
174   bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
175 
176   bool isStackEmpty() const {
177     return Stack.empty() ||
178            Stack.back().second != CurrentNonCapturingFunctionScope ||
179            Stack.back().first.empty();
180   }
181 
182   /// Vector of previously declared requires directives
183   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
184 
185 public:
186   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
187 
188   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
189   OpenMPClauseKind getClauseParsingMode() const {
190     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
191     return ClauseKindMode;
192   }
193   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
194 
195   bool isForceVarCapturing() const { return ForceCapturing; }
196   void setForceVarCapturing(bool V) { ForceCapturing = V; }
197 
198   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
199             Scope *CurScope, SourceLocation Loc) {
200     if (Stack.empty() ||
201         Stack.back().second != CurrentNonCapturingFunctionScope)
202       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
203     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
204     Stack.back().first.back().DefaultAttrLoc = Loc;
205   }
206 
207   void pop() {
208     assert(!Stack.back().first.empty() &&
209            "Data-sharing attributes stack is empty!");
210     Stack.back().first.pop_back();
211   }
212 
213   /// Marks that we're started loop parsing.
214   void loopInit() {
215     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
216            "Expected loop-based directive.");
217     Stack.back().first.back().LoopStart = true;
218   }
219   /// Start capturing of the variables in the loop context.
220   void loopStart() {
221     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
222            "Expected loop-based directive.");
223     Stack.back().first.back().LoopStart = false;
224   }
225   /// true, if variables are captured, false otherwise.
226   bool isLoopStarted() const {
227     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
228            "Expected loop-based directive.");
229     return !Stack.back().first.back().LoopStart;
230   }
231   /// Marks (or clears) declaration as possibly loop counter.
232   void resetPossibleLoopCounter(const Decl *D = nullptr) {
233     Stack.back().first.back().PossiblyLoopCounter =
234         D ? D->getCanonicalDecl() : D;
235   }
236   /// Gets the possible loop counter decl.
237   const Decl *getPossiblyLoopCunter() const {
238     return Stack.back().first.back().PossiblyLoopCounter;
239   }
240   /// Start new OpenMP region stack in new non-capturing function.
241   void pushFunction() {
242     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
243     assert(!isa<CapturingScopeInfo>(CurFnScope));
244     CurrentNonCapturingFunctionScope = CurFnScope;
245   }
246   /// Pop region stack for non-capturing function.
247   void popFunction(const FunctionScopeInfo *OldFSI) {
248     if (!Stack.empty() && Stack.back().second == OldFSI) {
249       assert(Stack.back().first.empty());
250       Stack.pop_back();
251     }
252     CurrentNonCapturingFunctionScope = nullptr;
253     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
254       if (!isa<CapturingScopeInfo>(FSI)) {
255         CurrentNonCapturingFunctionScope = FSI;
256         break;
257       }
258     }
259   }
260 
261   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
262     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
263   }
264   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
265   getCriticalWithHint(const DeclarationNameInfo &Name) const {
266     auto I = Criticals.find(Name.getAsString());
267     if (I != Criticals.end())
268       return I->second;
269     return std::make_pair(nullptr, llvm::APSInt());
270   }
271   /// If 'aligned' declaration for given variable \a D was not seen yet,
272   /// add it and return NULL; otherwise return previous occurrence's expression
273   /// for diagnostics.
274   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
275 
276   /// Register specified variable as loop control variable.
277   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
278   /// Check if the specified variable is a loop control variable for
279   /// current region.
280   /// \return The index of the loop control variable in the list of associated
281   /// for-loops (from outer to inner).
282   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
283   /// Check if the specified variable is a loop control variable for
284   /// parent region.
285   /// \return The index of the loop control variable in the list of associated
286   /// for-loops (from outer to inner).
287   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
288   /// Get the loop control variable for the I-th loop (or nullptr) in
289   /// parent directive.
290   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
291 
292   /// Adds explicit data sharing attribute to the specified declaration.
293   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
294               DeclRefExpr *PrivateCopy = nullptr);
295 
296   /// Adds additional information for the reduction items with the reduction id
297   /// represented as an operator.
298   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
299                                  BinaryOperatorKind BOK);
300   /// Adds additional information for the reduction items with the reduction id
301   /// represented as reduction identifier.
302   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
303                                  const Expr *ReductionRef);
304   /// Returns the location and reduction operation from the innermost parent
305   /// region for the given \p D.
306   const DSAVarData
307   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
308                                    BinaryOperatorKind &BOK,
309                                    Expr *&TaskgroupDescriptor) const;
310   /// Returns the location and reduction operation from the innermost parent
311   /// region for the given \p D.
312   const DSAVarData
313   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
314                                    const Expr *&ReductionRef,
315                                    Expr *&TaskgroupDescriptor) const;
316   /// Return reduction reference expression for the current taskgroup.
317   Expr *getTaskgroupReductionRef() const {
318     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
319            "taskgroup reference expression requested for non taskgroup "
320            "directive.");
321     return Stack.back().first.back().TaskgroupReductionRef;
322   }
323   /// Checks if the given \p VD declaration is actually a taskgroup reduction
324   /// descriptor variable at the \p Level of OpenMP regions.
325   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
326     return Stack.back().first[Level].TaskgroupReductionRef &&
327            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
328                    ->getDecl() == VD;
329   }
330 
331   /// Returns data sharing attributes from top of the stack for the
332   /// specified declaration.
333   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
334   /// Returns data-sharing attributes for the specified declaration.
335   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
336   /// Checks if the specified variables has data-sharing attributes which
337   /// match specified \a CPred predicate in any directive which matches \a DPred
338   /// predicate.
339   const DSAVarData
340   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
341          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
342          bool FromParent) const;
343   /// Checks if the specified variables has data-sharing attributes which
344   /// match specified \a CPred predicate in any innermost directive which
345   /// matches \a DPred predicate.
346   const DSAVarData
347   hasInnermostDSA(ValueDecl *D,
348                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
349                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
350                   bool FromParent) const;
351   /// Checks if the specified variables has explicit data-sharing
352   /// attributes which match specified \a CPred predicate at the specified
353   /// OpenMP region.
354   bool hasExplicitDSA(const ValueDecl *D,
355                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
356                       unsigned Level, bool NotLastprivate = false) const;
357 
358   /// Returns true if the directive at level \Level matches in the
359   /// specified \a DPred predicate.
360   bool hasExplicitDirective(
361       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
362       unsigned Level) const;
363 
364   /// Finds a directive which matches specified \a DPred predicate.
365   bool hasDirective(
366       const llvm::function_ref<bool(
367           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
368           DPred,
369       bool FromParent) const;
370 
371   /// Returns currently analyzed directive.
372   OpenMPDirectiveKind getCurrentDirective() const {
373     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
374   }
375   /// Returns directive kind at specified level.
376   OpenMPDirectiveKind getDirective(unsigned Level) const {
377     assert(!isStackEmpty() && "No directive at specified level.");
378     return Stack.back().first[Level].Directive;
379   }
380   /// Returns parent directive.
381   OpenMPDirectiveKind getParentDirective() const {
382     if (isStackEmpty() || Stack.back().first.size() == 1)
383       return OMPD_unknown;
384     return std::next(Stack.back().first.rbegin())->Directive;
385   }
386 
387   /// Add requires decl to internal vector
388   void addRequiresDecl(OMPRequiresDecl *RD) {
389     RequiresDecls.push_back(RD);
390   }
391 
392   /// Checks for a duplicate clause amongst previously declared requires
393   /// directives
394   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
395     bool IsDuplicate = false;
396     for (OMPClause *CNew : ClauseList) {
397       for (const OMPRequiresDecl *D : RequiresDecls) {
398         for (const OMPClause *CPrev : D->clauselists()) {
399           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
400             SemaRef.Diag(CNew->getBeginLoc(),
401                          diag::err_omp_requires_clause_redeclaration)
402                 << getOpenMPClauseName(CNew->getClauseKind());
403             SemaRef.Diag(CPrev->getBeginLoc(),
404                          diag::note_omp_requires_previous_clause)
405                 << getOpenMPClauseName(CPrev->getClauseKind());
406             IsDuplicate = true;
407           }
408         }
409       }
410     }
411     return IsDuplicate;
412   }
413 
414   /// Set default data sharing attribute to none.
415   void setDefaultDSANone(SourceLocation Loc) {
416     assert(!isStackEmpty());
417     Stack.back().first.back().DefaultAttr = DSA_none;
418     Stack.back().first.back().DefaultAttrLoc = Loc;
419   }
420   /// Set default data sharing attribute to shared.
421   void setDefaultDSAShared(SourceLocation Loc) {
422     assert(!isStackEmpty());
423     Stack.back().first.back().DefaultAttr = DSA_shared;
424     Stack.back().first.back().DefaultAttrLoc = Loc;
425   }
426   /// Set default data mapping attribute to 'tofrom:scalar'.
427   void setDefaultDMAToFromScalar(SourceLocation Loc) {
428     assert(!isStackEmpty());
429     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
430     Stack.back().first.back().DefaultMapAttrLoc = Loc;
431   }
432 
433   DefaultDataSharingAttributes getDefaultDSA() const {
434     return isStackEmpty() ? DSA_unspecified
435                           : Stack.back().first.back().DefaultAttr;
436   }
437   SourceLocation getDefaultDSALocation() const {
438     return isStackEmpty() ? SourceLocation()
439                           : Stack.back().first.back().DefaultAttrLoc;
440   }
441   DefaultMapAttributes getDefaultDMA() const {
442     return isStackEmpty() ? DMA_unspecified
443                           : Stack.back().first.back().DefaultMapAttr;
444   }
445   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
446     return Stack.back().first[Level].DefaultMapAttr;
447   }
448   SourceLocation getDefaultDMALocation() const {
449     return isStackEmpty() ? SourceLocation()
450                           : Stack.back().first.back().DefaultMapAttrLoc;
451   }
452 
453   /// Checks if the specified variable is a threadprivate.
454   bool isThreadPrivate(VarDecl *D) {
455     const DSAVarData DVar = getTopDSA(D, false);
456     return isOpenMPThreadPrivate(DVar.CKind);
457   }
458 
459   /// Marks current region as ordered (it has an 'ordered' clause).
460   void setOrderedRegion(bool IsOrdered, const Expr *Param,
461                         OMPOrderedClause *Clause) {
462     assert(!isStackEmpty());
463     if (IsOrdered)
464       Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
465     else
466       Stack.back().first.back().OrderedRegion.reset();
467   }
468   /// Returns true, if region is ordered (has associated 'ordered' clause),
469   /// false - otherwise.
470   bool isOrderedRegion() const {
471     if (isStackEmpty())
472       return false;
473     return Stack.back().first.rbegin()->OrderedRegion.hasValue();
474   }
475   /// Returns optional parameter for the ordered region.
476   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
477     if (isStackEmpty() ||
478         !Stack.back().first.rbegin()->OrderedRegion.hasValue())
479       return std::make_pair(nullptr, nullptr);
480     return Stack.back().first.rbegin()->OrderedRegion.getValue();
481   }
482   /// Returns true, if parent region is ordered (has associated
483   /// 'ordered' clause), false - otherwise.
484   bool isParentOrderedRegion() const {
485     if (isStackEmpty() || Stack.back().first.size() == 1)
486       return false;
487     return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
488   }
489   /// Returns optional parameter for the ordered region.
490   std::pair<const Expr *, OMPOrderedClause *>
491   getParentOrderedRegionParam() const {
492     if (isStackEmpty() || Stack.back().first.size() == 1 ||
493         !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
494       return std::make_pair(nullptr, nullptr);
495     return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
496   }
497   /// Marks current region as nowait (it has a 'nowait' clause).
498   void setNowaitRegion(bool IsNowait = true) {
499     assert(!isStackEmpty());
500     Stack.back().first.back().NowaitRegion = IsNowait;
501   }
502   /// Returns true, if parent region is nowait (has associated
503   /// 'nowait' clause), false - otherwise.
504   bool isParentNowaitRegion() const {
505     if (isStackEmpty() || Stack.back().first.size() == 1)
506       return false;
507     return std::next(Stack.back().first.rbegin())->NowaitRegion;
508   }
509   /// Marks parent region as cancel region.
510   void setParentCancelRegion(bool Cancel = true) {
511     if (!isStackEmpty() && Stack.back().first.size() > 1) {
512       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
513       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
514     }
515   }
516   /// Return true if current region has inner cancel construct.
517   bool isCancelRegion() const {
518     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
519   }
520 
521   /// Set collapse value for the region.
522   void setAssociatedLoops(unsigned Val) {
523     assert(!isStackEmpty());
524     Stack.back().first.back().AssociatedLoops = Val;
525   }
526   /// Return collapse value for region.
527   unsigned getAssociatedLoops() const {
528     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
529   }
530 
531   /// Marks current target region as one with closely nested teams
532   /// region.
533   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
534     if (!isStackEmpty() && Stack.back().first.size() > 1) {
535       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
536           TeamsRegionLoc;
537     }
538   }
539   /// Returns true, if current region has closely nested teams region.
540   bool hasInnerTeamsRegion() const {
541     return getInnerTeamsRegionLoc().isValid();
542   }
543   /// Returns location of the nested teams region (if any).
544   SourceLocation getInnerTeamsRegionLoc() const {
545     return isStackEmpty() ? SourceLocation()
546                           : Stack.back().first.back().InnerTeamsRegionLoc;
547   }
548 
549   Scope *getCurScope() const {
550     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
551   }
552   SourceLocation getConstructLoc() const {
553     return isStackEmpty() ? SourceLocation()
554                           : Stack.back().first.back().ConstructLoc;
555   }
556 
557   /// Do the check specified in \a Check to all component lists and return true
558   /// if any issue is found.
559   bool checkMappableExprComponentListsForDecl(
560       const ValueDecl *VD, bool CurrentRegionOnly,
561       const llvm::function_ref<
562           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
563                OpenMPClauseKind)>
564           Check) const {
565     if (isStackEmpty())
566       return false;
567     auto SI = Stack.back().first.rbegin();
568     auto SE = Stack.back().first.rend();
569 
570     if (SI == SE)
571       return false;
572 
573     if (CurrentRegionOnly)
574       SE = std::next(SI);
575     else
576       std::advance(SI, 1);
577 
578     for (; SI != SE; ++SI) {
579       auto MI = SI->MappedExprComponents.find(VD);
580       if (MI != SI->MappedExprComponents.end())
581         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
582              MI->second.Components)
583           if (Check(L, MI->second.Kind))
584             return true;
585     }
586     return false;
587   }
588 
589   /// Do the check specified in \a Check to all component lists at a given level
590   /// and return true if any issue is found.
591   bool checkMappableExprComponentListsForDeclAtLevel(
592       const ValueDecl *VD, unsigned Level,
593       const llvm::function_ref<
594           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
595                OpenMPClauseKind)>
596           Check) const {
597     if (isStackEmpty())
598       return false;
599 
600     auto StartI = Stack.back().first.begin();
601     auto EndI = Stack.back().first.end();
602     if (std::distance(StartI, EndI) <= (int)Level)
603       return false;
604     std::advance(StartI, Level);
605 
606     auto MI = StartI->MappedExprComponents.find(VD);
607     if (MI != StartI->MappedExprComponents.end())
608       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
609            MI->second.Components)
610         if (Check(L, MI->second.Kind))
611           return true;
612     return false;
613   }
614 
615   /// Create a new mappable expression component list associated with a given
616   /// declaration and initialize it with the provided list of components.
617   void addMappableExpressionComponents(
618       const ValueDecl *VD,
619       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
620       OpenMPClauseKind WhereFoundClauseKind) {
621     assert(!isStackEmpty() &&
622            "Not expecting to retrieve components from a empty stack!");
623     MappedExprComponentTy &MEC =
624         Stack.back().first.back().MappedExprComponents[VD];
625     // Create new entry and append the new components there.
626     MEC.Components.resize(MEC.Components.size() + 1);
627     MEC.Components.back().append(Components.begin(), Components.end());
628     MEC.Kind = WhereFoundClauseKind;
629   }
630 
631   unsigned getNestingLevel() const {
632     assert(!isStackEmpty());
633     return Stack.back().first.size() - 1;
634   }
635   void addDoacrossDependClause(OMPDependClause *C,
636                                const OperatorOffsetTy &OpsOffs) {
637     assert(!isStackEmpty() && Stack.back().first.size() > 1);
638     SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
639     assert(isOpenMPWorksharingDirective(StackElem.Directive));
640     StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
641   }
642   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
643   getDoacrossDependClauses() const {
644     assert(!isStackEmpty());
645     const SharingMapTy &StackElem = Stack.back().first.back();
646     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
647       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
648       return llvm::make_range(Ref.begin(), Ref.end());
649     }
650     return llvm::make_range(StackElem.DoacrossDepends.end(),
651                             StackElem.DoacrossDepends.end());
652   }
653 };
654 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
655   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
656          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
657 }
658 
659 } // namespace
660 
661 static const Expr *getExprAsWritten(const Expr *E) {
662   if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
663     E = ExprTemp->getSubExpr();
664 
665   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
666     E = MTE->GetTemporaryExpr();
667 
668   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
669     E = Binder->getSubExpr();
670 
671   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
672     E = ICE->getSubExprAsWritten();
673   return E->IgnoreParens();
674 }
675 
676 static Expr *getExprAsWritten(Expr *E) {
677   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
678 }
679 
680 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
681   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
682     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
683       D = ME->getMemberDecl();
684   const auto *VD = dyn_cast<VarDecl>(D);
685   const auto *FD = dyn_cast<FieldDecl>(D);
686   if (VD != nullptr) {
687     VD = VD->getCanonicalDecl();
688     D = VD;
689   } else {
690     assert(FD);
691     FD = FD->getCanonicalDecl();
692     D = FD;
693   }
694   return D;
695 }
696 
697 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
698   return const_cast<ValueDecl *>(
699       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
700 }
701 
702 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
703                                           ValueDecl *D) const {
704   D = getCanonicalDecl(D);
705   auto *VD = dyn_cast<VarDecl>(D);
706   const auto *FD = dyn_cast<FieldDecl>(D);
707   DSAVarData DVar;
708   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
709     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
710     // in a region but not in construct]
711     //  File-scope or namespace-scope variables referenced in called routines
712     //  in the region are shared unless they appear in a threadprivate
713     //  directive.
714     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
715       DVar.CKind = OMPC_shared;
716 
717     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
718     // in a region but not in construct]
719     //  Variables with static storage duration that are declared in called
720     //  routines in the region are shared.
721     if (VD && VD->hasGlobalStorage())
722       DVar.CKind = OMPC_shared;
723 
724     // Non-static data members are shared by default.
725     if (FD)
726       DVar.CKind = OMPC_shared;
727 
728     return DVar;
729   }
730 
731   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
732   // in a Construct, C/C++, predetermined, p.1]
733   // Variables with automatic storage duration that are declared in a scope
734   // inside the construct are private.
735   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
736       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
737     DVar.CKind = OMPC_private;
738     return DVar;
739   }
740 
741   DVar.DKind = Iter->Directive;
742   // Explicitly specified attributes and local variables with predetermined
743   // attributes.
744   if (Iter->SharingMap.count(D)) {
745     const DSAInfo &Data = Iter->SharingMap.lookup(D);
746     DVar.RefExpr = Data.RefExpr.getPointer();
747     DVar.PrivateCopy = Data.PrivateCopy;
748     DVar.CKind = Data.Attributes;
749     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
750     return DVar;
751   }
752 
753   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
754   // in a Construct, C/C++, implicitly determined, p.1]
755   //  In a parallel or task construct, the data-sharing attributes of these
756   //  variables are determined by the default clause, if present.
757   switch (Iter->DefaultAttr) {
758   case DSA_shared:
759     DVar.CKind = OMPC_shared;
760     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
761     return DVar;
762   case DSA_none:
763     return DVar;
764   case DSA_unspecified:
765     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
766     // in a Construct, implicitly determined, p.2]
767     //  In a parallel construct, if no default clause is present, these
768     //  variables are shared.
769     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
770     if (isOpenMPParallelDirective(DVar.DKind) ||
771         isOpenMPTeamsDirective(DVar.DKind)) {
772       DVar.CKind = OMPC_shared;
773       return DVar;
774     }
775 
776     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
777     // in a Construct, implicitly determined, p.4]
778     //  In a task construct, if no default clause is present, a variable that in
779     //  the enclosing context is determined to be shared by all implicit tasks
780     //  bound to the current team is shared.
781     if (isOpenMPTaskingDirective(DVar.DKind)) {
782       DSAVarData DVarTemp;
783       iterator I = Iter, E = Stack.back().first.rend();
784       do {
785         ++I;
786         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
787         // Referenced in a Construct, implicitly determined, p.6]
788         //  In a task construct, if no default clause is present, a variable
789         //  whose data-sharing attribute is not determined by the rules above is
790         //  firstprivate.
791         DVarTemp = getDSA(I, D);
792         if (DVarTemp.CKind != OMPC_shared) {
793           DVar.RefExpr = nullptr;
794           DVar.CKind = OMPC_firstprivate;
795           return DVar;
796         }
797       } while (I != E && !isParallelOrTaskRegion(I->Directive));
798       DVar.CKind =
799           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
800       return DVar;
801     }
802   }
803   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
804   // in a Construct, implicitly determined, p.3]
805   //  For constructs other than task, if no default clause is present, these
806   //  variables inherit their data-sharing attributes from the enclosing
807   //  context.
808   return getDSA(++Iter, D);
809 }
810 
811 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
812                                          const Expr *NewDE) {
813   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
814   D = getCanonicalDecl(D);
815   SharingMapTy &StackElem = Stack.back().first.back();
816   auto It = StackElem.AlignedMap.find(D);
817   if (It == StackElem.AlignedMap.end()) {
818     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
819     StackElem.AlignedMap[D] = NewDE;
820     return nullptr;
821   }
822   assert(It->second && "Unexpected nullptr expr in the aligned map");
823   return It->second;
824 }
825 
826 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
827   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
828   D = getCanonicalDecl(D);
829   SharingMapTy &StackElem = Stack.back().first.back();
830   StackElem.LCVMap.try_emplace(
831       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
832 }
833 
834 const DSAStackTy::LCDeclInfo
835 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
836   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
837   D = getCanonicalDecl(D);
838   const SharingMapTy &StackElem = Stack.back().first.back();
839   auto It = StackElem.LCVMap.find(D);
840   if (It != StackElem.LCVMap.end())
841     return It->second;
842   return {0, nullptr};
843 }
844 
845 const DSAStackTy::LCDeclInfo
846 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
847   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
848          "Data-sharing attributes stack is empty");
849   D = getCanonicalDecl(D);
850   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
851   auto It = StackElem.LCVMap.find(D);
852   if (It != StackElem.LCVMap.end())
853     return It->second;
854   return {0, nullptr};
855 }
856 
857 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
858   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
859          "Data-sharing attributes stack is empty");
860   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
861   if (StackElem.LCVMap.size() < I)
862     return nullptr;
863   for (const auto &Pair : StackElem.LCVMap)
864     if (Pair.second.first == I)
865       return Pair.first;
866   return nullptr;
867 }
868 
869 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
870                         DeclRefExpr *PrivateCopy) {
871   D = getCanonicalDecl(D);
872   if (A == OMPC_threadprivate) {
873     DSAInfo &Data = Threadprivates[D];
874     Data.Attributes = A;
875     Data.RefExpr.setPointer(E);
876     Data.PrivateCopy = nullptr;
877   } else {
878     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
879     DSAInfo &Data = Stack.back().first.back().SharingMap[D];
880     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
881            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
882            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
883            (isLoopControlVariable(D).first && A == OMPC_private));
884     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
885       Data.RefExpr.setInt(/*IntVal=*/true);
886       return;
887     }
888     const bool IsLastprivate =
889         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
890     Data.Attributes = A;
891     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
892     Data.PrivateCopy = PrivateCopy;
893     if (PrivateCopy) {
894       DSAInfo &Data =
895           Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
896       Data.Attributes = A;
897       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
898       Data.PrivateCopy = nullptr;
899     }
900   }
901 }
902 
903 /// Build a variable declaration for OpenMP loop iteration variable.
904 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
905                              StringRef Name, const AttrVec *Attrs = nullptr,
906                              DeclRefExpr *OrigRef = nullptr) {
907   DeclContext *DC = SemaRef.CurContext;
908   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
909   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
910   auto *Decl =
911       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
912   if (Attrs) {
913     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
914          I != E; ++I)
915       Decl->addAttr(*I);
916   }
917   Decl->setImplicit();
918   if (OrigRef) {
919     Decl->addAttr(
920         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
921   }
922   return Decl;
923 }
924 
925 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
926                                      SourceLocation Loc,
927                                      bool RefersToCapture = false) {
928   D->setReferenced();
929   D->markUsed(S.Context);
930   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
931                              SourceLocation(), D, RefersToCapture, Loc, Ty,
932                              VK_LValue);
933 }
934 
935 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
936                                            BinaryOperatorKind BOK) {
937   D = getCanonicalDecl(D);
938   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
939   assert(
940       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
941       "Additional reduction info may be specified only for reduction items.");
942   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
943   assert(ReductionData.ReductionRange.isInvalid() &&
944          Stack.back().first.back().Directive == OMPD_taskgroup &&
945          "Additional reduction info may be specified only once for reduction "
946          "items.");
947   ReductionData.set(BOK, SR);
948   Expr *&TaskgroupReductionRef =
949       Stack.back().first.back().TaskgroupReductionRef;
950   if (!TaskgroupReductionRef) {
951     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
952                                SemaRef.Context.VoidPtrTy, ".task_red.");
953     TaskgroupReductionRef =
954         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
955   }
956 }
957 
958 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
959                                            const Expr *ReductionRef) {
960   D = getCanonicalDecl(D);
961   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
962   assert(
963       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
964       "Additional reduction info may be specified only for reduction items.");
965   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
966   assert(ReductionData.ReductionRange.isInvalid() &&
967          Stack.back().first.back().Directive == OMPD_taskgroup &&
968          "Additional reduction info may be specified only once for reduction "
969          "items.");
970   ReductionData.set(ReductionRef, SR);
971   Expr *&TaskgroupReductionRef =
972       Stack.back().first.back().TaskgroupReductionRef;
973   if (!TaskgroupReductionRef) {
974     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
975                                SemaRef.Context.VoidPtrTy, ".task_red.");
976     TaskgroupReductionRef =
977         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
978   }
979 }
980 
981 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
982     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
983     Expr *&TaskgroupDescriptor) const {
984   D = getCanonicalDecl(D);
985   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
986   if (Stack.back().first.empty())
987       return DSAVarData();
988   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
989                 E = Stack.back().first.rend();
990        I != E; std::advance(I, 1)) {
991     const DSAInfo &Data = I->SharingMap.lookup(D);
992     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
993       continue;
994     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
995     if (!ReductionData.ReductionOp ||
996         ReductionData.ReductionOp.is<const Expr *>())
997       return DSAVarData();
998     SR = ReductionData.ReductionRange;
999     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1000     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1001                                        "expression for the descriptor is not "
1002                                        "set.");
1003     TaskgroupDescriptor = I->TaskgroupReductionRef;
1004     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1005                       Data.PrivateCopy, I->DefaultAttrLoc);
1006   }
1007   return DSAVarData();
1008 }
1009 
1010 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1011     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1012     Expr *&TaskgroupDescriptor) const {
1013   D = getCanonicalDecl(D);
1014   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1015   if (Stack.back().first.empty())
1016       return DSAVarData();
1017   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1018                 E = Stack.back().first.rend();
1019        I != E; std::advance(I, 1)) {
1020     const DSAInfo &Data = I->SharingMap.lookup(D);
1021     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1022       continue;
1023     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1024     if (!ReductionData.ReductionOp ||
1025         !ReductionData.ReductionOp.is<const Expr *>())
1026       return DSAVarData();
1027     SR = ReductionData.ReductionRange;
1028     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1029     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1030                                        "expression for the descriptor is not "
1031                                        "set.");
1032     TaskgroupDescriptor = I->TaskgroupReductionRef;
1033     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1034                       Data.PrivateCopy, I->DefaultAttrLoc);
1035   }
1036   return DSAVarData();
1037 }
1038 
1039 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
1040   D = D->getCanonicalDecl();
1041   if (!isStackEmpty()) {
1042     iterator I = Iter, E = Stack.back().first.rend();
1043     Scope *TopScope = nullptr;
1044     while (I != E && !isParallelOrTaskRegion(I->Directive) &&
1045            !isOpenMPTargetExecutionDirective(I->Directive))
1046       ++I;
1047     if (I == E)
1048       return false;
1049     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1050     Scope *CurScope = getCurScope();
1051     while (CurScope != TopScope && !CurScope->isDeclScope(D))
1052       CurScope = CurScope->getParent();
1053     return CurScope != TopScope;
1054   }
1055   return false;
1056 }
1057 
1058 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1059                                                    bool FromParent) {
1060   D = getCanonicalDecl(D);
1061   DSAVarData DVar;
1062 
1063   auto *VD = dyn_cast<VarDecl>(D);
1064   auto TI = Threadprivates.find(D);
1065   if (TI != Threadprivates.end()) {
1066     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1067     DVar.CKind = OMPC_threadprivate;
1068     return DVar;
1069   }
1070   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1071     DVar.RefExpr = buildDeclRefExpr(
1072         SemaRef, VD, D->getType().getNonReferenceType(),
1073         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1074     DVar.CKind = OMPC_threadprivate;
1075     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1076     return DVar;
1077   }
1078   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1079   // in a Construct, C/C++, predetermined, p.1]
1080   //  Variables appearing in threadprivate directives are threadprivate.
1081   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1082        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1083          SemaRef.getLangOpts().OpenMPUseTLS &&
1084          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1085       (VD && VD->getStorageClass() == SC_Register &&
1086        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1087     DVar.RefExpr = buildDeclRefExpr(
1088         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1089     DVar.CKind = OMPC_threadprivate;
1090     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1091     return DVar;
1092   }
1093   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1094       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1095       !isLoopControlVariable(D).first) {
1096     iterator IterTarget =
1097         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1098                      [](const SharingMapTy &Data) {
1099                        return isOpenMPTargetExecutionDirective(Data.Directive);
1100                      });
1101     if (IterTarget != Stack.back().first.rend()) {
1102       iterator ParentIterTarget = std::next(IterTarget, 1);
1103       for (iterator Iter = Stack.back().first.rbegin();
1104            Iter != ParentIterTarget; std::advance(Iter, 1)) {
1105         if (isOpenMPLocal(VD, Iter)) {
1106           DVar.RefExpr =
1107               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1108                                D->getLocation());
1109           DVar.CKind = OMPC_threadprivate;
1110           return DVar;
1111         }
1112       }
1113       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1114         auto DSAIter = IterTarget->SharingMap.find(D);
1115         if (DSAIter != IterTarget->SharingMap.end() &&
1116             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1117           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1118           DVar.CKind = OMPC_threadprivate;
1119           return DVar;
1120         }
1121         iterator End = Stack.back().first.rend();
1122         if (!SemaRef.isOpenMPCapturedByRef(
1123                 D, std::distance(ParentIterTarget, End))) {
1124           DVar.RefExpr =
1125               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1126                                IterTarget->ConstructLoc);
1127           DVar.CKind = OMPC_threadprivate;
1128           return DVar;
1129         }
1130       }
1131     }
1132   }
1133 
1134   if (isStackEmpty())
1135     // Not in OpenMP execution region and top scope was already checked.
1136     return DVar;
1137 
1138   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1139   // in a Construct, C/C++, predetermined, p.4]
1140   //  Static data members are shared.
1141   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1142   // in a Construct, C/C++, predetermined, p.7]
1143   //  Variables with static storage duration that are declared in a scope
1144   //  inside the construct are shared.
1145   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1146   if (VD && VD->isStaticDataMember()) {
1147     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1148     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1149       return DVar;
1150 
1151     DVar.CKind = OMPC_shared;
1152     return DVar;
1153   }
1154 
1155   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1156   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1157   Type = SemaRef.getASTContext().getBaseElementType(Type);
1158   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1159   // in a Construct, C/C++, predetermined, p.6]
1160   //  Variables with const qualified type having no mutable member are
1161   //  shared.
1162   const CXXRecordDecl *RD =
1163       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1164   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1165     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1166       RD = CTD->getTemplatedDecl();
1167   if (IsConstant &&
1168       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1169         RD->hasMutableFields())) {
1170     // Variables with const-qualified type having no mutable member may be
1171     // listed in a firstprivate clause, even if they are static data members.
1172     DSAVarData DVarTemp =
1173         hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
1174                MatchesAlways, FromParent);
1175     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1176       return DVarTemp;
1177 
1178     DVar.CKind = OMPC_shared;
1179     return DVar;
1180   }
1181 
1182   // Explicitly specified attributes and local variables with predetermined
1183   // attributes.
1184   iterator I = Stack.back().first.rbegin();
1185   iterator EndI = Stack.back().first.rend();
1186   if (FromParent && I != EndI)
1187     std::advance(I, 1);
1188   auto It = I->SharingMap.find(D);
1189   if (It != I->SharingMap.end()) {
1190     const DSAInfo &Data = It->getSecond();
1191     DVar.RefExpr = Data.RefExpr.getPointer();
1192     DVar.PrivateCopy = Data.PrivateCopy;
1193     DVar.CKind = Data.Attributes;
1194     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1195     DVar.DKind = I->Directive;
1196   }
1197 
1198   return DVar;
1199 }
1200 
1201 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1202                                                         bool FromParent) const {
1203   if (isStackEmpty()) {
1204     iterator I;
1205     return getDSA(I, D);
1206   }
1207   D = getCanonicalDecl(D);
1208   iterator StartI = Stack.back().first.rbegin();
1209   iterator EndI = Stack.back().first.rend();
1210   if (FromParent && StartI != EndI)
1211     std::advance(StartI, 1);
1212   return getDSA(StartI, D);
1213 }
1214 
1215 const DSAStackTy::DSAVarData
1216 DSAStackTy::hasDSA(ValueDecl *D,
1217                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1218                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1219                    bool FromParent) const {
1220   if (isStackEmpty())
1221     return {};
1222   D = getCanonicalDecl(D);
1223   iterator I = Stack.back().first.rbegin();
1224   iterator EndI = Stack.back().first.rend();
1225   if (FromParent && I != EndI)
1226     std::advance(I, 1);
1227   for (; I != EndI; std::advance(I, 1)) {
1228     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1229       continue;
1230     iterator NewI = I;
1231     DSAVarData DVar = getDSA(NewI, D);
1232     if (I == NewI && CPred(DVar.CKind))
1233       return DVar;
1234   }
1235   return {};
1236 }
1237 
1238 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1239     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1240     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1241     bool FromParent) const {
1242   if (isStackEmpty())
1243     return {};
1244   D = getCanonicalDecl(D);
1245   iterator StartI = Stack.back().first.rbegin();
1246   iterator EndI = Stack.back().first.rend();
1247   if (FromParent && StartI != EndI)
1248     std::advance(StartI, 1);
1249   if (StartI == EndI || !DPred(StartI->Directive))
1250     return {};
1251   iterator NewI = StartI;
1252   DSAVarData DVar = getDSA(NewI, D);
1253   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1254 }
1255 
1256 bool DSAStackTy::hasExplicitDSA(
1257     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1258     unsigned Level, bool NotLastprivate) const {
1259   if (isStackEmpty())
1260     return false;
1261   D = getCanonicalDecl(D);
1262   auto StartI = Stack.back().first.begin();
1263   auto EndI = Stack.back().first.end();
1264   if (std::distance(StartI, EndI) <= (int)Level)
1265     return false;
1266   std::advance(StartI, Level);
1267   auto I = StartI->SharingMap.find(D);
1268   return (I != StartI->SharingMap.end()) &&
1269          I->getSecond().RefExpr.getPointer() &&
1270          CPred(I->getSecond().Attributes) &&
1271          (!NotLastprivate || !I->getSecond().RefExpr.getInt());
1272 }
1273 
1274 bool DSAStackTy::hasExplicitDirective(
1275     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1276     unsigned Level) const {
1277   if (isStackEmpty())
1278     return false;
1279   auto StartI = Stack.back().first.begin();
1280   auto EndI = Stack.back().first.end();
1281   if (std::distance(StartI, EndI) <= (int)Level)
1282     return false;
1283   std::advance(StartI, Level);
1284   return DPred(StartI->Directive);
1285 }
1286 
1287 bool DSAStackTy::hasDirective(
1288     const llvm::function_ref<bool(OpenMPDirectiveKind,
1289                                   const DeclarationNameInfo &, SourceLocation)>
1290         DPred,
1291     bool FromParent) const {
1292   // We look only in the enclosing region.
1293   if (isStackEmpty())
1294     return false;
1295   auto StartI = std::next(Stack.back().first.rbegin());
1296   auto EndI = Stack.back().first.rend();
1297   if (FromParent && StartI != EndI)
1298     StartI = std::next(StartI);
1299   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1300     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1301       return true;
1302   }
1303   return false;
1304 }
1305 
1306 void Sema::InitDataSharingAttributesStack() {
1307   VarDataSharingAttributesStack = new DSAStackTy(*this);
1308 }
1309 
1310 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1311 
1312 void Sema::pushOpenMPFunctionRegion() {
1313   DSAStack->pushFunction();
1314 }
1315 
1316 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1317   DSAStack->popFunction(OldFSI);
1318 }
1319 
1320 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1321   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1322 
1323   ASTContext &Ctx = getASTContext();
1324   bool IsByRef = true;
1325 
1326   // Find the directive that is associated with the provided scope.
1327   D = cast<ValueDecl>(D->getCanonicalDecl());
1328   QualType Ty = D->getType();
1329 
1330   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1331     // This table summarizes how a given variable should be passed to the device
1332     // given its type and the clauses where it appears. This table is based on
1333     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1334     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1335     //
1336     // =========================================================================
1337     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1338     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1339     // =========================================================================
1340     // | scl  |               |     |       |       -       |          | bycopy|
1341     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1342     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1343     // | scl  |       x       |     |       |       -       |          | byref |
1344     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1345     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1346     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1347     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1348     //
1349     // | agg  |      n.a.     |     |       |       -       |          | byref |
1350     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1351     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1352     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1353     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1354     //
1355     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1356     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1357     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1358     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1359     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1360     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1361     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1362     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1363     // =========================================================================
1364     // Legend:
1365     //  scl - scalar
1366     //  ptr - pointer
1367     //  agg - aggregate
1368     //  x - applies
1369     //  - - invalid in this combination
1370     //  [] - mapped with an array section
1371     //  byref - should be mapped by reference
1372     //  byval - should be mapped by value
1373     //  null - initialize a local variable to null on the device
1374     //
1375     // Observations:
1376     //  - All scalar declarations that show up in a map clause have to be passed
1377     //    by reference, because they may have been mapped in the enclosing data
1378     //    environment.
1379     //  - If the scalar value does not fit the size of uintptr, it has to be
1380     //    passed by reference, regardless the result in the table above.
1381     //  - For pointers mapped by value that have either an implicit map or an
1382     //    array section, the runtime library may pass the NULL value to the
1383     //    device instead of the value passed to it by the compiler.
1384 
1385     if (Ty->isReferenceType())
1386       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1387 
1388     // Locate map clauses and see if the variable being captured is referred to
1389     // in any of those clauses. Here we only care about variables, not fields,
1390     // because fields are part of aggregates.
1391     bool IsVariableUsedInMapClause = false;
1392     bool IsVariableAssociatedWithSection = false;
1393 
1394     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1395         D, Level,
1396         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1397             OMPClauseMappableExprCommon::MappableExprComponentListRef
1398                 MapExprComponents,
1399             OpenMPClauseKind WhereFoundClauseKind) {
1400           // Only the map clause information influences how a variable is
1401           // captured. E.g. is_device_ptr does not require changing the default
1402           // behavior.
1403           if (WhereFoundClauseKind != OMPC_map)
1404             return false;
1405 
1406           auto EI = MapExprComponents.rbegin();
1407           auto EE = MapExprComponents.rend();
1408 
1409           assert(EI != EE && "Invalid map expression!");
1410 
1411           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1412             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1413 
1414           ++EI;
1415           if (EI == EE)
1416             return false;
1417 
1418           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1419               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1420               isa<MemberExpr>(EI->getAssociatedExpression())) {
1421             IsVariableAssociatedWithSection = true;
1422             // There is nothing more we need to know about this variable.
1423             return true;
1424           }
1425 
1426           // Keep looking for more map info.
1427           return false;
1428         });
1429 
1430     if (IsVariableUsedInMapClause) {
1431       // If variable is identified in a map clause it is always captured by
1432       // reference except if it is a pointer that is dereferenced somehow.
1433       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1434     } else {
1435       // By default, all the data that has a scalar type is mapped by copy
1436       // (except for reduction variables).
1437       IsByRef =
1438           !Ty->isScalarType() ||
1439           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1440           DSAStack->hasExplicitDSA(
1441               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1442     }
1443   }
1444 
1445   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1446     IsByRef =
1447         !DSAStack->hasExplicitDSA(
1448             D,
1449             [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1450             Level, /*NotLastprivate=*/true) &&
1451         // If the variable is artificial and must be captured by value - try to
1452         // capture by value.
1453         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1454           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1455   }
1456 
1457   // When passing data by copy, we need to make sure it fits the uintptr size
1458   // and alignment, because the runtime library only deals with uintptr types.
1459   // If it does not fit the uintptr size, we need to pass the data by reference
1460   // instead.
1461   if (!IsByRef &&
1462       (Ctx.getTypeSizeInChars(Ty) >
1463            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1464        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1465     IsByRef = true;
1466   }
1467 
1468   return IsByRef;
1469 }
1470 
1471 unsigned Sema::getOpenMPNestingLevel() const {
1472   assert(getLangOpts().OpenMP);
1473   return DSAStack->getNestingLevel();
1474 }
1475 
1476 bool Sema::isInOpenMPTargetExecutionDirective() const {
1477   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1478           !DSAStack->isClauseParsingMode()) ||
1479          DSAStack->hasDirective(
1480              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1481                 SourceLocation) -> bool {
1482                return isOpenMPTargetExecutionDirective(K);
1483              },
1484              false);
1485 }
1486 
1487 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
1488   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1489   D = getCanonicalDecl(D);
1490 
1491   // If we are attempting to capture a global variable in a directive with
1492   // 'target' we return true so that this global is also mapped to the device.
1493   //
1494   auto *VD = dyn_cast<VarDecl>(D);
1495   if (VD && !VD->hasLocalStorage()) {
1496     if (isInOpenMPDeclareTargetContext() &&
1497         (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1498       // Try to mark variable as declare target if it is used in capturing
1499       // regions.
1500       if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1501         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1502       return nullptr;
1503     } else if (isInOpenMPTargetExecutionDirective()) {
1504       // If the declaration is enclosed in a 'declare target' directive,
1505       // then it should not be captured.
1506       //
1507       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1508         return nullptr;
1509       return VD;
1510     }
1511   }
1512 
1513   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1514       (!DSAStack->isClauseParsingMode() ||
1515        DSAStack->getParentDirective() != OMPD_unknown)) {
1516     auto &&Info = DSAStack->isLoopControlVariable(D);
1517     if (Info.first ||
1518         (VD && VD->hasLocalStorage() &&
1519          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1520         (VD && DSAStack->isForceVarCapturing()))
1521       return VD ? VD : Info.second;
1522     DSAStackTy::DSAVarData DVarPrivate =
1523         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1524     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1525       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1526     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1527                                    [](OpenMPDirectiveKind) { return true; },
1528                                    DSAStack->isClauseParsingMode());
1529     if (DVarPrivate.CKind != OMPC_unknown)
1530       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1531   }
1532   return nullptr;
1533 }
1534 
1535 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1536                                         unsigned Level) const {
1537   SmallVector<OpenMPDirectiveKind, 4> Regions;
1538   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1539   FunctionScopesIndex -= Regions.size();
1540 }
1541 
1542 void Sema::startOpenMPLoop() {
1543   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1544   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1545     DSAStack->loopInit();
1546 }
1547 
1548 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1549   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1550   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1551     if (DSAStack->getAssociatedLoops() > 0 &&
1552         !DSAStack->isLoopStarted()) {
1553       DSAStack->resetPossibleLoopCounter(D);
1554       DSAStack->loopStart();
1555       return true;
1556     }
1557     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1558          DSAStack->isLoopControlVariable(D).first) &&
1559         !DSAStack->hasExplicitDSA(
1560             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1561         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1562       return true;
1563   }
1564   return DSAStack->hasExplicitDSA(
1565              D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1566          (DSAStack->isClauseParsingMode() &&
1567           DSAStack->getClauseParsingMode() == OMPC_private) ||
1568          // Consider taskgroup reduction descriptor variable a private to avoid
1569          // possible capture in the region.
1570          (DSAStack->hasExplicitDirective(
1571               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1572               Level) &&
1573           DSAStack->isTaskgroupReductionRef(D, Level));
1574 }
1575 
1576 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1577                                 unsigned Level) {
1578   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1579   D = getCanonicalDecl(D);
1580   OpenMPClauseKind OMPC = OMPC_unknown;
1581   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1582     const unsigned NewLevel = I - 1;
1583     if (DSAStack->hasExplicitDSA(D,
1584                                  [&OMPC](const OpenMPClauseKind K) {
1585                                    if (isOpenMPPrivate(K)) {
1586                                      OMPC = K;
1587                                      return true;
1588                                    }
1589                                    return false;
1590                                  },
1591                                  NewLevel))
1592       break;
1593     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1594             D, NewLevel,
1595             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1596                OpenMPClauseKind) { return true; })) {
1597       OMPC = OMPC_map;
1598       break;
1599     }
1600     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1601                                        NewLevel)) {
1602       OMPC = OMPC_map;
1603       if (D->getType()->isScalarType() &&
1604           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1605               DefaultMapAttributes::DMA_tofrom_scalar)
1606         OMPC = OMPC_firstprivate;
1607       break;
1608     }
1609   }
1610   if (OMPC != OMPC_unknown)
1611     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1612 }
1613 
1614 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1615                                       unsigned Level) const {
1616   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1617   // Return true if the current level is no longer enclosed in a target region.
1618 
1619   const auto *VD = dyn_cast<VarDecl>(D);
1620   return VD && !VD->hasLocalStorage() &&
1621          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1622                                         Level);
1623 }
1624 
1625 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1626 
1627 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1628                                const DeclarationNameInfo &DirName,
1629                                Scope *CurScope, SourceLocation Loc) {
1630   DSAStack->push(DKind, DirName, CurScope, Loc);
1631   PushExpressionEvaluationContext(
1632       ExpressionEvaluationContext::PotentiallyEvaluated);
1633 }
1634 
1635 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1636   DSAStack->setClauseParsingMode(K);
1637 }
1638 
1639 void Sema::EndOpenMPClause() {
1640   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1641 }
1642 
1643 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1644   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1645   //  A variable of class type (or array thereof) that appears in a lastprivate
1646   //  clause requires an accessible, unambiguous default constructor for the
1647   //  class type, unless the list item is also specified in a firstprivate
1648   //  clause.
1649   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1650     for (OMPClause *C : D->clauses()) {
1651       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1652         SmallVector<Expr *, 8> PrivateCopies;
1653         for (Expr *DE : Clause->varlists()) {
1654           if (DE->isValueDependent() || DE->isTypeDependent()) {
1655             PrivateCopies.push_back(nullptr);
1656             continue;
1657           }
1658           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1659           auto *VD = cast<VarDecl>(DRE->getDecl());
1660           QualType Type = VD->getType().getNonReferenceType();
1661           const DSAStackTy::DSAVarData DVar =
1662               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1663           if (DVar.CKind == OMPC_lastprivate) {
1664             // Generate helper private variable and initialize it with the
1665             // default value. The address of the original variable is replaced
1666             // by the address of the new private variable in CodeGen. This new
1667             // variable is not added to IdResolver, so the code in the OpenMP
1668             // region uses original variable for proper diagnostics.
1669             VarDecl *VDPrivate = buildVarDecl(
1670                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1671                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1672             ActOnUninitializedDecl(VDPrivate);
1673             if (VDPrivate->isInvalidDecl())
1674               continue;
1675             PrivateCopies.push_back(buildDeclRefExpr(
1676                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1677           } else {
1678             // The variable is also a firstprivate, so initialization sequence
1679             // for private copy is generated already.
1680             PrivateCopies.push_back(nullptr);
1681           }
1682         }
1683         // Set initializers to private copies if no errors were found.
1684         if (PrivateCopies.size() == Clause->varlist_size())
1685           Clause->setPrivateCopies(PrivateCopies);
1686       }
1687     }
1688   }
1689 
1690   DSAStack->pop();
1691   DiscardCleanupsInEvaluationContext();
1692   PopExpressionEvaluationContext();
1693 }
1694 
1695 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1696                                      Expr *NumIterations, Sema &SemaRef,
1697                                      Scope *S, DSAStackTy *Stack);
1698 
1699 namespace {
1700 
1701 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1702 private:
1703   Sema &SemaRef;
1704 
1705 public:
1706   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1707   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1708     NamedDecl *ND = Candidate.getCorrectionDecl();
1709     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1710       return VD->hasGlobalStorage() &&
1711              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1712                                    SemaRef.getCurScope());
1713     }
1714     return false;
1715   }
1716 };
1717 
1718 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1719 private:
1720   Sema &SemaRef;
1721 
1722 public:
1723   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1724   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1725     NamedDecl *ND = Candidate.getCorrectionDecl();
1726     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1727       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1728                                    SemaRef.getCurScope());
1729     }
1730     return false;
1731   }
1732 };
1733 
1734 } // namespace
1735 
1736 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1737                                          CXXScopeSpec &ScopeSpec,
1738                                          const DeclarationNameInfo &Id) {
1739   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1740   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1741 
1742   if (Lookup.isAmbiguous())
1743     return ExprError();
1744 
1745   VarDecl *VD;
1746   if (!Lookup.isSingleResult()) {
1747     if (TypoCorrection Corrected = CorrectTypo(
1748             Id, LookupOrdinaryName, CurScope, nullptr,
1749             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1750       diagnoseTypo(Corrected,
1751                    PDiag(Lookup.empty()
1752                              ? diag::err_undeclared_var_use_suggest
1753                              : diag::err_omp_expected_var_arg_suggest)
1754                        << Id.getName());
1755       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1756     } else {
1757       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1758                                        : diag::err_omp_expected_var_arg)
1759           << Id.getName();
1760       return ExprError();
1761     }
1762   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1763     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1764     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1765     return ExprError();
1766   }
1767   Lookup.suppressDiagnostics();
1768 
1769   // OpenMP [2.9.2, Syntax, C/C++]
1770   //   Variables must be file-scope, namespace-scope, or static block-scope.
1771   if (!VD->hasGlobalStorage()) {
1772     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1773         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1774     bool IsDecl =
1775         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1776     Diag(VD->getLocation(),
1777          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1778         << VD;
1779     return ExprError();
1780   }
1781 
1782   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1783   NamedDecl *ND = CanonicalVD;
1784   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1785   //   A threadprivate directive for file-scope variables must appear outside
1786   //   any definition or declaration.
1787   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1788       !getCurLexicalContext()->isTranslationUnit()) {
1789     Diag(Id.getLoc(), diag::err_omp_var_scope)
1790         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1791     bool IsDecl =
1792         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1793     Diag(VD->getLocation(),
1794          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1795         << VD;
1796     return ExprError();
1797   }
1798   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1799   //   A threadprivate directive for static class member variables must appear
1800   //   in the class definition, in the same scope in which the member
1801   //   variables are declared.
1802   if (CanonicalVD->isStaticDataMember() &&
1803       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1804     Diag(Id.getLoc(), diag::err_omp_var_scope)
1805         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1806     bool IsDecl =
1807         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1808     Diag(VD->getLocation(),
1809          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1810         << VD;
1811     return ExprError();
1812   }
1813   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1814   //   A threadprivate directive for namespace-scope variables must appear
1815   //   outside any definition or declaration other than the namespace
1816   //   definition itself.
1817   if (CanonicalVD->getDeclContext()->isNamespace() &&
1818       (!getCurLexicalContext()->isFileContext() ||
1819        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1820     Diag(Id.getLoc(), diag::err_omp_var_scope)
1821         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1822     bool IsDecl =
1823         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1824     Diag(VD->getLocation(),
1825          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1826         << VD;
1827     return ExprError();
1828   }
1829   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1830   //   A threadprivate directive for static block-scope variables must appear
1831   //   in the scope of the variable and not in a nested scope.
1832   if (CanonicalVD->isStaticLocal() && CurScope &&
1833       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1834     Diag(Id.getLoc(), diag::err_omp_var_scope)
1835         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1836     bool IsDecl =
1837         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1838     Diag(VD->getLocation(),
1839          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1840         << VD;
1841     return ExprError();
1842   }
1843 
1844   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1845   //   A threadprivate directive must lexically precede all references to any
1846   //   of the variables in its list.
1847   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1848     Diag(Id.getLoc(), diag::err_omp_var_used)
1849         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1850     return ExprError();
1851   }
1852 
1853   QualType ExprType = VD->getType().getNonReferenceType();
1854   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1855                              SourceLocation(), VD,
1856                              /*RefersToEnclosingVariableOrCapture=*/false,
1857                              Id.getLoc(), ExprType, VK_LValue);
1858 }
1859 
1860 Sema::DeclGroupPtrTy
1861 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1862                                         ArrayRef<Expr *> VarList) {
1863   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1864     CurContext->addDecl(D);
1865     return DeclGroupPtrTy::make(DeclGroupRef(D));
1866   }
1867   return nullptr;
1868 }
1869 
1870 namespace {
1871 class LocalVarRefChecker final
1872     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1873   Sema &SemaRef;
1874 
1875 public:
1876   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1877     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1878       if (VD->hasLocalStorage()) {
1879         SemaRef.Diag(E->getBeginLoc(),
1880                      diag::err_omp_local_var_in_threadprivate_init)
1881             << E->getSourceRange();
1882         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1883             << VD << VD->getSourceRange();
1884         return true;
1885       }
1886     }
1887     return false;
1888   }
1889   bool VisitStmt(const Stmt *S) {
1890     for (const Stmt *Child : S->children()) {
1891       if (Child && Visit(Child))
1892         return true;
1893     }
1894     return false;
1895   }
1896   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1897 };
1898 } // namespace
1899 
1900 OMPThreadPrivateDecl *
1901 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1902   SmallVector<Expr *, 8> Vars;
1903   for (Expr *RefExpr : VarList) {
1904     auto *DE = cast<DeclRefExpr>(RefExpr);
1905     auto *VD = cast<VarDecl>(DE->getDecl());
1906     SourceLocation ILoc = DE->getExprLoc();
1907 
1908     // Mark variable as used.
1909     VD->setReferenced();
1910     VD->markUsed(Context);
1911 
1912     QualType QType = VD->getType();
1913     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1914       // It will be analyzed later.
1915       Vars.push_back(DE);
1916       continue;
1917     }
1918 
1919     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1920     //   A threadprivate variable must not have an incomplete type.
1921     if (RequireCompleteType(ILoc, VD->getType(),
1922                             diag::err_omp_threadprivate_incomplete_type)) {
1923       continue;
1924     }
1925 
1926     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1927     //   A threadprivate variable must not have a reference type.
1928     if (VD->getType()->isReferenceType()) {
1929       Diag(ILoc, diag::err_omp_ref_type_arg)
1930           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1931       bool IsDecl =
1932           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1933       Diag(VD->getLocation(),
1934            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1935           << VD;
1936       continue;
1937     }
1938 
1939     // Check if this is a TLS variable. If TLS is not being supported, produce
1940     // the corresponding diagnostic.
1941     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1942          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1943            getLangOpts().OpenMPUseTLS &&
1944            getASTContext().getTargetInfo().isTLSSupported())) ||
1945         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1946          !VD->isLocalVarDecl())) {
1947       Diag(ILoc, diag::err_omp_var_thread_local)
1948           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1949       bool IsDecl =
1950           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1951       Diag(VD->getLocation(),
1952            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1953           << VD;
1954       continue;
1955     }
1956 
1957     // Check if initial value of threadprivate variable reference variable with
1958     // local storage (it is not supported by runtime).
1959     if (const Expr *Init = VD->getAnyInitializer()) {
1960       LocalVarRefChecker Checker(*this);
1961       if (Checker.Visit(Init))
1962         continue;
1963     }
1964 
1965     Vars.push_back(RefExpr);
1966     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1967     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1968         Context, SourceRange(Loc, Loc)));
1969     if (ASTMutationListener *ML = Context.getASTMutationListener())
1970       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1971   }
1972   OMPThreadPrivateDecl *D = nullptr;
1973   if (!Vars.empty()) {
1974     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1975                                      Vars);
1976     D->setAccess(AS_public);
1977   }
1978   return D;
1979 }
1980 
1981 Sema::DeclGroupPtrTy
1982 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
1983                                    ArrayRef<OMPClause *> ClauseList) {
1984   OMPRequiresDecl *D = nullptr;
1985   if (!CurContext->isFileContext()) {
1986     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
1987   } else {
1988     D = CheckOMPRequiresDecl(Loc, ClauseList);
1989     if (D) {
1990       CurContext->addDecl(D);
1991       DSAStack->addRequiresDecl(D);
1992     }
1993   }
1994   return DeclGroupPtrTy::make(DeclGroupRef(D));
1995 }
1996 
1997 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
1998                                             ArrayRef<OMPClause *> ClauseList) {
1999   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2000     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2001                                    ClauseList);
2002   return nullptr;
2003 }
2004 
2005 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2006                               const ValueDecl *D,
2007                               const DSAStackTy::DSAVarData &DVar,
2008                               bool IsLoopIterVar = false) {
2009   if (DVar.RefExpr) {
2010     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2011         << getOpenMPClauseName(DVar.CKind);
2012     return;
2013   }
2014   enum {
2015     PDSA_StaticMemberShared,
2016     PDSA_StaticLocalVarShared,
2017     PDSA_LoopIterVarPrivate,
2018     PDSA_LoopIterVarLinear,
2019     PDSA_LoopIterVarLastprivate,
2020     PDSA_ConstVarShared,
2021     PDSA_GlobalVarShared,
2022     PDSA_TaskVarFirstprivate,
2023     PDSA_LocalVarPrivate,
2024     PDSA_Implicit
2025   } Reason = PDSA_Implicit;
2026   bool ReportHint = false;
2027   auto ReportLoc = D->getLocation();
2028   auto *VD = dyn_cast<VarDecl>(D);
2029   if (IsLoopIterVar) {
2030     if (DVar.CKind == OMPC_private)
2031       Reason = PDSA_LoopIterVarPrivate;
2032     else if (DVar.CKind == OMPC_lastprivate)
2033       Reason = PDSA_LoopIterVarLastprivate;
2034     else
2035       Reason = PDSA_LoopIterVarLinear;
2036   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2037              DVar.CKind == OMPC_firstprivate) {
2038     Reason = PDSA_TaskVarFirstprivate;
2039     ReportLoc = DVar.ImplicitDSALoc;
2040   } else if (VD && VD->isStaticLocal())
2041     Reason = PDSA_StaticLocalVarShared;
2042   else if (VD && VD->isStaticDataMember())
2043     Reason = PDSA_StaticMemberShared;
2044   else if (VD && VD->isFileVarDecl())
2045     Reason = PDSA_GlobalVarShared;
2046   else if (D->getType().isConstant(SemaRef.getASTContext()))
2047     Reason = PDSA_ConstVarShared;
2048   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2049     ReportHint = true;
2050     Reason = PDSA_LocalVarPrivate;
2051   }
2052   if (Reason != PDSA_Implicit) {
2053     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2054         << Reason << ReportHint
2055         << getOpenMPDirectiveName(Stack->getCurrentDirective());
2056   } else if (DVar.ImplicitDSALoc.isValid()) {
2057     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2058         << getOpenMPClauseName(DVar.CKind);
2059   }
2060 }
2061 
2062 namespace {
2063 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2064   DSAStackTy *Stack;
2065   Sema &SemaRef;
2066   bool ErrorFound = false;
2067   CapturedStmt *CS = nullptr;
2068   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2069   llvm::SmallVector<Expr *, 4> ImplicitMap;
2070   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2071   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2072 
2073   void VisitSubCaptures(OMPExecutableDirective *S) {
2074     // Check implicitly captured variables.
2075     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2076       return;
2077     for (const CapturedStmt::Capture &Cap :
2078          S->getInnermostCapturedStmt()->captures()) {
2079       if (!Cap.capturesVariable())
2080         continue;
2081       VarDecl *VD = Cap.getCapturedVar();
2082       // Do not try to map the variable if it or its sub-component was mapped
2083       // already.
2084       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2085           Stack->checkMappableExprComponentListsForDecl(
2086               VD, /*CurrentRegionOnly=*/true,
2087               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2088                  OpenMPClauseKind) { return true; }))
2089         continue;
2090       DeclRefExpr *DRE = buildDeclRefExpr(
2091           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2092           Cap.getLocation(), /*RefersToCapture=*/true);
2093       Visit(DRE);
2094     }
2095   }
2096 
2097 public:
2098   void VisitDeclRefExpr(DeclRefExpr *E) {
2099     if (E->isTypeDependent() || E->isValueDependent() ||
2100         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2101       return;
2102     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2103       VD = VD->getCanonicalDecl();
2104       // Skip internally declared variables.
2105       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
2106         return;
2107 
2108       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2109       // Check if the variable has explicit DSA set and stop analysis if it so.
2110       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2111         return;
2112 
2113       // Skip internally declared static variables.
2114       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2115           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2116       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2117           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2118         return;
2119 
2120       SourceLocation ELoc = E->getExprLoc();
2121       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2122       // The default(none) clause requires that each variable that is referenced
2123       // in the construct, and does not have a predetermined data-sharing
2124       // attribute, must have its data-sharing attribute explicitly determined
2125       // by being listed in a data-sharing attribute clause.
2126       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2127           isParallelOrTaskRegion(DKind) &&
2128           VarsWithInheritedDSA.count(VD) == 0) {
2129         VarsWithInheritedDSA[VD] = E;
2130         return;
2131       }
2132 
2133       if (isOpenMPTargetExecutionDirective(DKind) &&
2134           !Stack->isLoopControlVariable(VD).first) {
2135         if (!Stack->checkMappableExprComponentListsForDecl(
2136                 VD, /*CurrentRegionOnly=*/true,
2137                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2138                        StackComponents,
2139                    OpenMPClauseKind) {
2140                   // Variable is used if it has been marked as an array, array
2141                   // section or the variable iself.
2142                   return StackComponents.size() == 1 ||
2143                          std::all_of(
2144                              std::next(StackComponents.rbegin()),
2145                              StackComponents.rend(),
2146                              [](const OMPClauseMappableExprCommon::
2147                                     MappableComponent &MC) {
2148                                return MC.getAssociatedDeclaration() ==
2149                                           nullptr &&
2150                                       (isa<OMPArraySectionExpr>(
2151                                            MC.getAssociatedExpression()) ||
2152                                        isa<ArraySubscriptExpr>(
2153                                            MC.getAssociatedExpression()));
2154                              });
2155                 })) {
2156           bool IsFirstprivate = false;
2157           // By default lambdas are captured as firstprivates.
2158           if (const auto *RD =
2159                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2160             IsFirstprivate = RD->isLambda();
2161           IsFirstprivate =
2162               IsFirstprivate ||
2163               (VD->getType().getNonReferenceType()->isScalarType() &&
2164                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2165           if (IsFirstprivate)
2166             ImplicitFirstprivate.emplace_back(E);
2167           else
2168             ImplicitMap.emplace_back(E);
2169           return;
2170         }
2171       }
2172 
2173       // OpenMP [2.9.3.6, Restrictions, p.2]
2174       //  A list item that appears in a reduction clause of the innermost
2175       //  enclosing worksharing or parallel construct may not be accessed in an
2176       //  explicit task.
2177       DVar = Stack->hasInnermostDSA(
2178           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2179           [](OpenMPDirectiveKind K) {
2180             return isOpenMPParallelDirective(K) ||
2181                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2182           },
2183           /*FromParent=*/true);
2184       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2185         ErrorFound = true;
2186         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2187         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2188         return;
2189       }
2190 
2191       // Define implicit data-sharing attributes for task.
2192       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2193       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2194           !Stack->isLoopControlVariable(VD).first)
2195         ImplicitFirstprivate.push_back(E);
2196     }
2197   }
2198   void VisitMemberExpr(MemberExpr *E) {
2199     if (E->isTypeDependent() || E->isValueDependent() ||
2200         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2201       return;
2202     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2203     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2204     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2205       if (!FD)
2206         return;
2207       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2208       // Check if the variable has explicit DSA set and stop analysis if it
2209       // so.
2210       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2211         return;
2212 
2213       if (isOpenMPTargetExecutionDirective(DKind) &&
2214           !Stack->isLoopControlVariable(FD).first &&
2215           !Stack->checkMappableExprComponentListsForDecl(
2216               FD, /*CurrentRegionOnly=*/true,
2217               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2218                      StackComponents,
2219                  OpenMPClauseKind) {
2220                 return isa<CXXThisExpr>(
2221                     cast<MemberExpr>(
2222                         StackComponents.back().getAssociatedExpression())
2223                         ->getBase()
2224                         ->IgnoreParens());
2225               })) {
2226         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2227         //  A bit-field cannot appear in a map clause.
2228         //
2229         if (FD->isBitField())
2230           return;
2231         ImplicitMap.emplace_back(E);
2232         return;
2233       }
2234 
2235       SourceLocation ELoc = E->getExprLoc();
2236       // OpenMP [2.9.3.6, Restrictions, p.2]
2237       //  A list item that appears in a reduction clause of the innermost
2238       //  enclosing worksharing or parallel construct may not be accessed in
2239       //  an  explicit task.
2240       DVar = Stack->hasInnermostDSA(
2241           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2242           [](OpenMPDirectiveKind K) {
2243             return isOpenMPParallelDirective(K) ||
2244                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2245           },
2246           /*FromParent=*/true);
2247       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2248         ErrorFound = true;
2249         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2250         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2251         return;
2252       }
2253 
2254       // Define implicit data-sharing attributes for task.
2255       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2256       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2257           !Stack->isLoopControlVariable(FD).first) {
2258         // Check if there is a captured expression for the current field in the
2259         // region. Do not mark it as firstprivate unless there is no captured
2260         // expression.
2261         // TODO: try to make it firstprivate.
2262         if (DVar.CKind != OMPC_unknown)
2263           ImplicitFirstprivate.push_back(E);
2264       }
2265       return;
2266     }
2267     if (isOpenMPTargetExecutionDirective(DKind)) {
2268       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2269       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2270                                         /*NoDiagnose=*/true))
2271         return;
2272       const auto *VD = cast<ValueDecl>(
2273           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2274       if (!Stack->checkMappableExprComponentListsForDecl(
2275               VD, /*CurrentRegionOnly=*/true,
2276               [&CurComponents](
2277                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2278                       StackComponents,
2279                   OpenMPClauseKind) {
2280                 auto CCI = CurComponents.rbegin();
2281                 auto CCE = CurComponents.rend();
2282                 for (const auto &SC : llvm::reverse(StackComponents)) {
2283                   // Do both expressions have the same kind?
2284                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2285                       SC.getAssociatedExpression()->getStmtClass())
2286                     if (!(isa<OMPArraySectionExpr>(
2287                               SC.getAssociatedExpression()) &&
2288                           isa<ArraySubscriptExpr>(
2289                               CCI->getAssociatedExpression())))
2290                       return false;
2291 
2292                   const Decl *CCD = CCI->getAssociatedDeclaration();
2293                   const Decl *SCD = SC.getAssociatedDeclaration();
2294                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2295                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2296                   if (SCD != CCD)
2297                     return false;
2298                   std::advance(CCI, 1);
2299                   if (CCI == CCE)
2300                     break;
2301                 }
2302                 return true;
2303               })) {
2304         Visit(E->getBase());
2305       }
2306     } else {
2307       Visit(E->getBase());
2308     }
2309   }
2310   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2311     for (OMPClause *C : S->clauses()) {
2312       // Skip analysis of arguments of implicitly defined firstprivate clause
2313       // for task|target directives.
2314       // Skip analysis of arguments of implicitly defined map clause for target
2315       // directives.
2316       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2317                  C->isImplicit())) {
2318         for (Stmt *CC : C->children()) {
2319           if (CC)
2320             Visit(CC);
2321         }
2322       }
2323     }
2324     // Check implicitly captured variables.
2325     VisitSubCaptures(S);
2326   }
2327   void VisitStmt(Stmt *S) {
2328     for (Stmt *C : S->children()) {
2329       if (C) {
2330         if (auto *OED = dyn_cast<OMPExecutableDirective>(C)) {
2331           // Check implicitly captured variables in the task-based directives to
2332           // check if they must be firstprivatized.
2333           VisitSubCaptures(OED);
2334         } else {
2335           Visit(C);
2336         }
2337       }
2338     }
2339   }
2340 
2341   bool isErrorFound() const { return ErrorFound; }
2342   ArrayRef<Expr *> getImplicitFirstprivate() const {
2343     return ImplicitFirstprivate;
2344   }
2345   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2346   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2347     return VarsWithInheritedDSA;
2348   }
2349 
2350   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2351       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2352 };
2353 } // namespace
2354 
2355 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2356   switch (DKind) {
2357   case OMPD_parallel:
2358   case OMPD_parallel_for:
2359   case OMPD_parallel_for_simd:
2360   case OMPD_parallel_sections:
2361   case OMPD_teams:
2362   case OMPD_teams_distribute:
2363   case OMPD_teams_distribute_simd: {
2364     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2365     QualType KmpInt32PtrTy =
2366         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2367     Sema::CapturedParamNameType Params[] = {
2368         std::make_pair(".global_tid.", KmpInt32PtrTy),
2369         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2370         std::make_pair(StringRef(), QualType()) // __context with shared vars
2371     };
2372     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2373                              Params);
2374     break;
2375   }
2376   case OMPD_target_teams:
2377   case OMPD_target_parallel:
2378   case OMPD_target_parallel_for:
2379   case OMPD_target_parallel_for_simd:
2380   case OMPD_target_teams_distribute:
2381   case OMPD_target_teams_distribute_simd: {
2382     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2383     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2384     QualType KmpInt32PtrTy =
2385         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2386     QualType Args[] = {VoidPtrTy};
2387     FunctionProtoType::ExtProtoInfo EPI;
2388     EPI.Variadic = true;
2389     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2390     Sema::CapturedParamNameType Params[] = {
2391         std::make_pair(".global_tid.", KmpInt32Ty),
2392         std::make_pair(".part_id.", KmpInt32PtrTy),
2393         std::make_pair(".privates.", VoidPtrTy),
2394         std::make_pair(
2395             ".copy_fn.",
2396             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2397         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2398         std::make_pair(StringRef(), QualType()) // __context with shared vars
2399     };
2400     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2401                              Params);
2402     // Mark this captured region as inlined, because we don't use outlined
2403     // function directly.
2404     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2405         AlwaysInlineAttr::CreateImplicit(
2406             Context, AlwaysInlineAttr::Keyword_forceinline));
2407     Sema::CapturedParamNameType ParamsTarget[] = {
2408         std::make_pair(StringRef(), QualType()) // __context with shared vars
2409     };
2410     // Start a captured region for 'target' with no implicit parameters.
2411     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2412                              ParamsTarget);
2413     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2414         std::make_pair(".global_tid.", KmpInt32PtrTy),
2415         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2416         std::make_pair(StringRef(), QualType()) // __context with shared vars
2417     };
2418     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2419     // the same implicit parameters.
2420     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2421                              ParamsTeamsOrParallel);
2422     break;
2423   }
2424   case OMPD_target:
2425   case OMPD_target_simd: {
2426     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2427     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2428     QualType KmpInt32PtrTy =
2429         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2430     QualType Args[] = {VoidPtrTy};
2431     FunctionProtoType::ExtProtoInfo EPI;
2432     EPI.Variadic = true;
2433     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2434     Sema::CapturedParamNameType Params[] = {
2435         std::make_pair(".global_tid.", KmpInt32Ty),
2436         std::make_pair(".part_id.", KmpInt32PtrTy),
2437         std::make_pair(".privates.", VoidPtrTy),
2438         std::make_pair(
2439             ".copy_fn.",
2440             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2441         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2442         std::make_pair(StringRef(), QualType()) // __context with shared vars
2443     };
2444     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2445                              Params);
2446     // Mark this captured region as inlined, because we don't use outlined
2447     // function directly.
2448     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2449         AlwaysInlineAttr::CreateImplicit(
2450             Context, AlwaysInlineAttr::Keyword_forceinline));
2451     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2452                              std::make_pair(StringRef(), QualType()));
2453     break;
2454   }
2455   case OMPD_simd:
2456   case OMPD_for:
2457   case OMPD_for_simd:
2458   case OMPD_sections:
2459   case OMPD_section:
2460   case OMPD_single:
2461   case OMPD_master:
2462   case OMPD_critical:
2463   case OMPD_taskgroup:
2464   case OMPD_distribute:
2465   case OMPD_distribute_simd:
2466   case OMPD_ordered:
2467   case OMPD_atomic:
2468   case OMPD_target_data: {
2469     Sema::CapturedParamNameType Params[] = {
2470         std::make_pair(StringRef(), QualType()) // __context with shared vars
2471     };
2472     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2473                              Params);
2474     break;
2475   }
2476   case OMPD_task: {
2477     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2478     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2479     QualType KmpInt32PtrTy =
2480         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2481     QualType Args[] = {VoidPtrTy};
2482     FunctionProtoType::ExtProtoInfo EPI;
2483     EPI.Variadic = true;
2484     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2485     Sema::CapturedParamNameType Params[] = {
2486         std::make_pair(".global_tid.", KmpInt32Ty),
2487         std::make_pair(".part_id.", KmpInt32PtrTy),
2488         std::make_pair(".privates.", VoidPtrTy),
2489         std::make_pair(
2490             ".copy_fn.",
2491             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2492         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2493         std::make_pair(StringRef(), QualType()) // __context with shared vars
2494     };
2495     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2496                              Params);
2497     // Mark this captured region as inlined, because we don't use outlined
2498     // function directly.
2499     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2500         AlwaysInlineAttr::CreateImplicit(
2501             Context, AlwaysInlineAttr::Keyword_forceinline));
2502     break;
2503   }
2504   case OMPD_taskloop:
2505   case OMPD_taskloop_simd: {
2506     QualType KmpInt32Ty =
2507         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2508             .withConst();
2509     QualType KmpUInt64Ty =
2510         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2511             .withConst();
2512     QualType KmpInt64Ty =
2513         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2514             .withConst();
2515     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2516     QualType KmpInt32PtrTy =
2517         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2518     QualType Args[] = {VoidPtrTy};
2519     FunctionProtoType::ExtProtoInfo EPI;
2520     EPI.Variadic = true;
2521     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2522     Sema::CapturedParamNameType Params[] = {
2523         std::make_pair(".global_tid.", KmpInt32Ty),
2524         std::make_pair(".part_id.", KmpInt32PtrTy),
2525         std::make_pair(".privates.", VoidPtrTy),
2526         std::make_pair(
2527             ".copy_fn.",
2528             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2529         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2530         std::make_pair(".lb.", KmpUInt64Ty),
2531         std::make_pair(".ub.", KmpUInt64Ty),
2532         std::make_pair(".st.", KmpInt64Ty),
2533         std::make_pair(".liter.", KmpInt32Ty),
2534         std::make_pair(".reductions.", VoidPtrTy),
2535         std::make_pair(StringRef(), QualType()) // __context with shared vars
2536     };
2537     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2538                              Params);
2539     // Mark this captured region as inlined, because we don't use outlined
2540     // function directly.
2541     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2542         AlwaysInlineAttr::CreateImplicit(
2543             Context, AlwaysInlineAttr::Keyword_forceinline));
2544     break;
2545   }
2546   case OMPD_distribute_parallel_for_simd:
2547   case OMPD_distribute_parallel_for: {
2548     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2549     QualType KmpInt32PtrTy =
2550         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2551     Sema::CapturedParamNameType Params[] = {
2552         std::make_pair(".global_tid.", KmpInt32PtrTy),
2553         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2554         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2555         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2556         std::make_pair(StringRef(), QualType()) // __context with shared vars
2557     };
2558     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2559                              Params);
2560     break;
2561   }
2562   case OMPD_target_teams_distribute_parallel_for:
2563   case OMPD_target_teams_distribute_parallel_for_simd: {
2564     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2565     QualType KmpInt32PtrTy =
2566         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2567     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2568 
2569     QualType Args[] = {VoidPtrTy};
2570     FunctionProtoType::ExtProtoInfo EPI;
2571     EPI.Variadic = true;
2572     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2573     Sema::CapturedParamNameType Params[] = {
2574         std::make_pair(".global_tid.", KmpInt32Ty),
2575         std::make_pair(".part_id.", KmpInt32PtrTy),
2576         std::make_pair(".privates.", VoidPtrTy),
2577         std::make_pair(
2578             ".copy_fn.",
2579             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2580         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2581         std::make_pair(StringRef(), QualType()) // __context with shared vars
2582     };
2583     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2584                              Params);
2585     // Mark this captured region as inlined, because we don't use outlined
2586     // function directly.
2587     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2588         AlwaysInlineAttr::CreateImplicit(
2589             Context, AlwaysInlineAttr::Keyword_forceinline));
2590     Sema::CapturedParamNameType ParamsTarget[] = {
2591         std::make_pair(StringRef(), QualType()) // __context with shared vars
2592     };
2593     // Start a captured region for 'target' with no implicit parameters.
2594     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2595                              ParamsTarget);
2596 
2597     Sema::CapturedParamNameType ParamsTeams[] = {
2598         std::make_pair(".global_tid.", KmpInt32PtrTy),
2599         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2600         std::make_pair(StringRef(), QualType()) // __context with shared vars
2601     };
2602     // Start a captured region for 'target' with no implicit parameters.
2603     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2604                              ParamsTeams);
2605 
2606     Sema::CapturedParamNameType ParamsParallel[] = {
2607         std::make_pair(".global_tid.", KmpInt32PtrTy),
2608         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2609         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2610         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2611         std::make_pair(StringRef(), QualType()) // __context with shared vars
2612     };
2613     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2614     // the same implicit parameters.
2615     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2616                              ParamsParallel);
2617     break;
2618   }
2619 
2620   case OMPD_teams_distribute_parallel_for:
2621   case OMPD_teams_distribute_parallel_for_simd: {
2622     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2623     QualType KmpInt32PtrTy =
2624         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2625 
2626     Sema::CapturedParamNameType ParamsTeams[] = {
2627         std::make_pair(".global_tid.", KmpInt32PtrTy),
2628         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2629         std::make_pair(StringRef(), QualType()) // __context with shared vars
2630     };
2631     // Start a captured region for 'target' with no implicit parameters.
2632     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2633                              ParamsTeams);
2634 
2635     Sema::CapturedParamNameType ParamsParallel[] = {
2636         std::make_pair(".global_tid.", KmpInt32PtrTy),
2637         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2638         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2639         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2640         std::make_pair(StringRef(), QualType()) // __context with shared vars
2641     };
2642     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2643     // the same implicit parameters.
2644     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2645                              ParamsParallel);
2646     break;
2647   }
2648   case OMPD_target_update:
2649   case OMPD_target_enter_data:
2650   case OMPD_target_exit_data: {
2651     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2652     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2653     QualType KmpInt32PtrTy =
2654         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2655     QualType Args[] = {VoidPtrTy};
2656     FunctionProtoType::ExtProtoInfo EPI;
2657     EPI.Variadic = true;
2658     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2659     Sema::CapturedParamNameType Params[] = {
2660         std::make_pair(".global_tid.", KmpInt32Ty),
2661         std::make_pair(".part_id.", KmpInt32PtrTy),
2662         std::make_pair(".privates.", VoidPtrTy),
2663         std::make_pair(
2664             ".copy_fn.",
2665             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2666         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2667         std::make_pair(StringRef(), QualType()) // __context with shared vars
2668     };
2669     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2670                              Params);
2671     // Mark this captured region as inlined, because we don't use outlined
2672     // function directly.
2673     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2674         AlwaysInlineAttr::CreateImplicit(
2675             Context, AlwaysInlineAttr::Keyword_forceinline));
2676     break;
2677   }
2678   case OMPD_threadprivate:
2679   case OMPD_taskyield:
2680   case OMPD_barrier:
2681   case OMPD_taskwait:
2682   case OMPD_cancellation_point:
2683   case OMPD_cancel:
2684   case OMPD_flush:
2685   case OMPD_declare_reduction:
2686   case OMPD_declare_simd:
2687   case OMPD_declare_target:
2688   case OMPD_end_declare_target:
2689   case OMPD_requires:
2690     llvm_unreachable("OpenMP Directive is not allowed");
2691   case OMPD_unknown:
2692     llvm_unreachable("Unknown OpenMP directive");
2693   }
2694 }
2695 
2696 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2697   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2698   getOpenMPCaptureRegions(CaptureRegions, DKind);
2699   return CaptureRegions.size();
2700 }
2701 
2702 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2703                                              Expr *CaptureExpr, bool WithInit,
2704                                              bool AsExpression) {
2705   assert(CaptureExpr);
2706   ASTContext &C = S.getASTContext();
2707   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2708   QualType Ty = Init->getType();
2709   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2710     if (S.getLangOpts().CPlusPlus) {
2711       Ty = C.getLValueReferenceType(Ty);
2712     } else {
2713       Ty = C.getPointerType(Ty);
2714       ExprResult Res =
2715           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2716       if (!Res.isUsable())
2717         return nullptr;
2718       Init = Res.get();
2719     }
2720     WithInit = true;
2721   }
2722   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2723                                           CaptureExpr->getBeginLoc());
2724   if (!WithInit)
2725     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
2726   S.CurContext->addHiddenDecl(CED);
2727   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2728   return CED;
2729 }
2730 
2731 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2732                                  bool WithInit) {
2733   OMPCapturedExprDecl *CD;
2734   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
2735     CD = cast<OMPCapturedExprDecl>(VD);
2736   else
2737     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2738                           /*AsExpression=*/false);
2739   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2740                           CaptureExpr->getExprLoc());
2741 }
2742 
2743 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2744   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2745   if (!Ref) {
2746     OMPCapturedExprDecl *CD = buildCaptureDecl(
2747         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2748         /*WithInit=*/true, /*AsExpression=*/true);
2749     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2750                            CaptureExpr->getExprLoc());
2751   }
2752   ExprResult Res = Ref;
2753   if (!S.getLangOpts().CPlusPlus &&
2754       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2755       Ref->getType()->isPointerType()) {
2756     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2757     if (!Res.isUsable())
2758       return ExprError();
2759   }
2760   return S.DefaultLvalueConversion(Res.get());
2761 }
2762 
2763 namespace {
2764 // OpenMP directives parsed in this section are represented as a
2765 // CapturedStatement with an associated statement.  If a syntax error
2766 // is detected during the parsing of the associated statement, the
2767 // compiler must abort processing and close the CapturedStatement.
2768 //
2769 // Combined directives such as 'target parallel' have more than one
2770 // nested CapturedStatements.  This RAII ensures that we unwind out
2771 // of all the nested CapturedStatements when an error is found.
2772 class CaptureRegionUnwinderRAII {
2773 private:
2774   Sema &S;
2775   bool &ErrorFound;
2776   OpenMPDirectiveKind DKind = OMPD_unknown;
2777 
2778 public:
2779   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2780                             OpenMPDirectiveKind DKind)
2781       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2782   ~CaptureRegionUnwinderRAII() {
2783     if (ErrorFound) {
2784       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2785       while (--ThisCaptureLevel >= 0)
2786         S.ActOnCapturedRegionError();
2787     }
2788   }
2789 };
2790 } // namespace
2791 
2792 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2793                                       ArrayRef<OMPClause *> Clauses) {
2794   bool ErrorFound = false;
2795   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2796       *this, ErrorFound, DSAStack->getCurrentDirective());
2797   if (!S.isUsable()) {
2798     ErrorFound = true;
2799     return StmtError();
2800   }
2801 
2802   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2803   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2804   OMPOrderedClause *OC = nullptr;
2805   OMPScheduleClause *SC = nullptr;
2806   SmallVector<const OMPLinearClause *, 4> LCs;
2807   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
2808   // This is required for proper codegen.
2809   for (OMPClause *Clause : Clauses) {
2810     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2811         Clause->getClauseKind() == OMPC_in_reduction) {
2812       // Capture taskgroup task_reduction descriptors inside the tasking regions
2813       // with the corresponding in_reduction items.
2814       auto *IRC = cast<OMPInReductionClause>(Clause);
2815       for (Expr *E : IRC->taskgroup_descriptors())
2816         if (E)
2817           MarkDeclarationsReferencedInExpr(E);
2818     }
2819     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2820         Clause->getClauseKind() == OMPC_copyprivate ||
2821         (getLangOpts().OpenMPUseTLS &&
2822          getASTContext().getTargetInfo().isTLSSupported() &&
2823          Clause->getClauseKind() == OMPC_copyin)) {
2824       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2825       // Mark all variables in private list clauses as used in inner region.
2826       for (Stmt *VarRef : Clause->children()) {
2827         if (auto *E = cast_or_null<Expr>(VarRef)) {
2828           MarkDeclarationsReferencedInExpr(E);
2829         }
2830       }
2831       DSAStack->setForceVarCapturing(/*V=*/false);
2832     } else if (CaptureRegions.size() > 1 ||
2833                CaptureRegions.back() != OMPD_unknown) {
2834       if (auto *C = OMPClauseWithPreInit::get(Clause))
2835         PICs.push_back(C);
2836       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2837         if (Expr *E = C->getPostUpdateExpr())
2838           MarkDeclarationsReferencedInExpr(E);
2839       }
2840     }
2841     if (Clause->getClauseKind() == OMPC_schedule)
2842       SC = cast<OMPScheduleClause>(Clause);
2843     else if (Clause->getClauseKind() == OMPC_ordered)
2844       OC = cast<OMPOrderedClause>(Clause);
2845     else if (Clause->getClauseKind() == OMPC_linear)
2846       LCs.push_back(cast<OMPLinearClause>(Clause));
2847   }
2848   // OpenMP, 2.7.1 Loop Construct, Restrictions
2849   // The nonmonotonic modifier cannot be specified if an ordered clause is
2850   // specified.
2851   if (SC &&
2852       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2853        SC->getSecondScheduleModifier() ==
2854            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2855       OC) {
2856     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2857              ? SC->getFirstScheduleModifierLoc()
2858              : SC->getSecondScheduleModifierLoc(),
2859          diag::err_omp_schedule_nonmonotonic_ordered)
2860         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2861     ErrorFound = true;
2862   }
2863   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2864     for (const OMPLinearClause *C : LCs) {
2865       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
2866           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2867     }
2868     ErrorFound = true;
2869   }
2870   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2871       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2872       OC->getNumForLoops()) {
2873     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
2874         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2875     ErrorFound = true;
2876   }
2877   if (ErrorFound) {
2878     return StmtError();
2879   }
2880   StmtResult SR = S;
2881   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2882     // Mark all variables in private list clauses as used in inner region.
2883     // Required for proper codegen of combined directives.
2884     // TODO: add processing for other clauses.
2885     if (ThisCaptureRegion != OMPD_unknown) {
2886       for (const clang::OMPClauseWithPreInit *C : PICs) {
2887         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2888         // Find the particular capture region for the clause if the
2889         // directive is a combined one with multiple capture regions.
2890         // If the directive is not a combined one, the capture region
2891         // associated with the clause is OMPD_unknown and is generated
2892         // only once.
2893         if (CaptureRegion == ThisCaptureRegion ||
2894             CaptureRegion == OMPD_unknown) {
2895           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2896             for (Decl *D : DS->decls())
2897               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2898           }
2899         }
2900       }
2901     }
2902     SR = ActOnCapturedRegionEnd(SR.get());
2903   }
2904   return SR;
2905 }
2906 
2907 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2908                               OpenMPDirectiveKind CancelRegion,
2909                               SourceLocation StartLoc) {
2910   // CancelRegion is only needed for cancel and cancellation_point.
2911   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2912     return false;
2913 
2914   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2915       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2916     return false;
2917 
2918   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2919       << getOpenMPDirectiveName(CancelRegion);
2920   return true;
2921 }
2922 
2923 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
2924                                   OpenMPDirectiveKind CurrentRegion,
2925                                   const DeclarationNameInfo &CurrentName,
2926                                   OpenMPDirectiveKind CancelRegion,
2927                                   SourceLocation StartLoc) {
2928   if (Stack->getCurScope()) {
2929     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
2930     OpenMPDirectiveKind OffendingRegion = ParentRegion;
2931     bool NestingProhibited = false;
2932     bool CloseNesting = true;
2933     bool OrphanSeen = false;
2934     enum {
2935       NoRecommend,
2936       ShouldBeInParallelRegion,
2937       ShouldBeInOrderedRegion,
2938       ShouldBeInTargetRegion,
2939       ShouldBeInTeamsRegion
2940     } Recommend = NoRecommend;
2941     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2942       // OpenMP [2.16, Nesting of Regions]
2943       // OpenMP constructs may not be nested inside a simd region.
2944       // OpenMP [2.8.1,simd Construct, Restrictions]
2945       // An ordered construct with the simd clause is the only OpenMP
2946       // construct that can appear in the simd region.
2947       // Allowing a SIMD construct nested in another SIMD construct is an
2948       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2949       // message.
2950       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2951                                  ? diag::err_omp_prohibited_region_simd
2952                                  : diag::warn_omp_nesting_simd);
2953       return CurrentRegion != OMPD_simd;
2954     }
2955     if (ParentRegion == OMPD_atomic) {
2956       // OpenMP [2.16, Nesting of Regions]
2957       // OpenMP constructs may not be nested inside an atomic region.
2958       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2959       return true;
2960     }
2961     if (CurrentRegion == OMPD_section) {
2962       // OpenMP [2.7.2, sections Construct, Restrictions]
2963       // Orphaned section directives are prohibited. That is, the section
2964       // directives must appear within the sections construct and must not be
2965       // encountered elsewhere in the sections region.
2966       if (ParentRegion != OMPD_sections &&
2967           ParentRegion != OMPD_parallel_sections) {
2968         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2969             << (ParentRegion != OMPD_unknown)
2970             << getOpenMPDirectiveName(ParentRegion);
2971         return true;
2972       }
2973       return false;
2974     }
2975     // Allow some constructs (except teams) to be orphaned (they could be
2976     // used in functions, called from OpenMP regions with the required
2977     // preconditions).
2978     if (ParentRegion == OMPD_unknown &&
2979         !isOpenMPNestingTeamsDirective(CurrentRegion))
2980       return false;
2981     if (CurrentRegion == OMPD_cancellation_point ||
2982         CurrentRegion == OMPD_cancel) {
2983       // OpenMP [2.16, Nesting of Regions]
2984       // A cancellation point construct for which construct-type-clause is
2985       // taskgroup must be nested inside a task construct. A cancellation
2986       // point construct for which construct-type-clause is not taskgroup must
2987       // be closely nested inside an OpenMP construct that matches the type
2988       // specified in construct-type-clause.
2989       // A cancel construct for which construct-type-clause is taskgroup must be
2990       // nested inside a task construct. A cancel construct for which
2991       // construct-type-clause is not taskgroup must be closely nested inside an
2992       // OpenMP construct that matches the type specified in
2993       // construct-type-clause.
2994       NestingProhibited =
2995           !((CancelRegion == OMPD_parallel &&
2996              (ParentRegion == OMPD_parallel ||
2997               ParentRegion == OMPD_target_parallel)) ||
2998             (CancelRegion == OMPD_for &&
2999              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3000               ParentRegion == OMPD_target_parallel_for ||
3001               ParentRegion == OMPD_distribute_parallel_for ||
3002               ParentRegion == OMPD_teams_distribute_parallel_for ||
3003               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3004             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3005             (CancelRegion == OMPD_sections &&
3006              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3007               ParentRegion == OMPD_parallel_sections)));
3008     } else if (CurrentRegion == OMPD_master) {
3009       // OpenMP [2.16, Nesting of Regions]
3010       // A master region may not be closely nested inside a worksharing,
3011       // atomic, or explicit task region.
3012       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3013                           isOpenMPTaskingDirective(ParentRegion);
3014     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3015       // OpenMP [2.16, Nesting of Regions]
3016       // A critical region may not be nested (closely or otherwise) inside a
3017       // critical region with the same name. Note that this restriction is not
3018       // sufficient to prevent deadlock.
3019       SourceLocation PreviousCriticalLoc;
3020       bool DeadLock = Stack->hasDirective(
3021           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3022                                               const DeclarationNameInfo &DNI,
3023                                               SourceLocation Loc) {
3024             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3025               PreviousCriticalLoc = Loc;
3026               return true;
3027             }
3028             return false;
3029           },
3030           false /* skip top directive */);
3031       if (DeadLock) {
3032         SemaRef.Diag(StartLoc,
3033                      diag::err_omp_prohibited_region_critical_same_name)
3034             << CurrentName.getName();
3035         if (PreviousCriticalLoc.isValid())
3036           SemaRef.Diag(PreviousCriticalLoc,
3037                        diag::note_omp_previous_critical_region);
3038         return true;
3039       }
3040     } else if (CurrentRegion == OMPD_barrier) {
3041       // OpenMP [2.16, Nesting of Regions]
3042       // A barrier region may not be closely nested inside a worksharing,
3043       // explicit task, critical, ordered, atomic, or master region.
3044       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3045                           isOpenMPTaskingDirective(ParentRegion) ||
3046                           ParentRegion == OMPD_master ||
3047                           ParentRegion == OMPD_critical ||
3048                           ParentRegion == OMPD_ordered;
3049     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3050                !isOpenMPParallelDirective(CurrentRegion) &&
3051                !isOpenMPTeamsDirective(CurrentRegion)) {
3052       // OpenMP [2.16, Nesting of Regions]
3053       // A worksharing region may not be closely nested inside a worksharing,
3054       // explicit task, critical, ordered, atomic, or master region.
3055       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3056                           isOpenMPTaskingDirective(ParentRegion) ||
3057                           ParentRegion == OMPD_master ||
3058                           ParentRegion == OMPD_critical ||
3059                           ParentRegion == OMPD_ordered;
3060       Recommend = ShouldBeInParallelRegion;
3061     } else if (CurrentRegion == OMPD_ordered) {
3062       // OpenMP [2.16, Nesting of Regions]
3063       // An ordered region may not be closely nested inside a critical,
3064       // atomic, or explicit task region.
3065       // An ordered region must be closely nested inside a loop region (or
3066       // parallel loop region) with an ordered clause.
3067       // OpenMP [2.8.1,simd Construct, Restrictions]
3068       // An ordered construct with the simd clause is the only OpenMP construct
3069       // that can appear in the simd region.
3070       NestingProhibited = ParentRegion == OMPD_critical ||
3071                           isOpenMPTaskingDirective(ParentRegion) ||
3072                           !(isOpenMPSimdDirective(ParentRegion) ||
3073                             Stack->isParentOrderedRegion());
3074       Recommend = ShouldBeInOrderedRegion;
3075     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3076       // OpenMP [2.16, Nesting of Regions]
3077       // If specified, a teams construct must be contained within a target
3078       // construct.
3079       NestingProhibited = ParentRegion != OMPD_target;
3080       OrphanSeen = ParentRegion == OMPD_unknown;
3081       Recommend = ShouldBeInTargetRegion;
3082     }
3083     if (!NestingProhibited &&
3084         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3085         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3086         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3087       // OpenMP [2.16, Nesting of Regions]
3088       // distribute, parallel, parallel sections, parallel workshare, and the
3089       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3090       // constructs that can be closely nested in the teams region.
3091       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3092                           !isOpenMPDistributeDirective(CurrentRegion);
3093       Recommend = ShouldBeInParallelRegion;
3094     }
3095     if (!NestingProhibited &&
3096         isOpenMPNestingDistributeDirective(CurrentRegion)) {
3097       // OpenMP 4.5 [2.17 Nesting of Regions]
3098       // The region associated with the distribute construct must be strictly
3099       // nested inside a teams region
3100       NestingProhibited =
3101           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3102       Recommend = ShouldBeInTeamsRegion;
3103     }
3104     if (!NestingProhibited &&
3105         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3106          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3107       // OpenMP 4.5 [2.17 Nesting of Regions]
3108       // If a target, target update, target data, target enter data, or
3109       // target exit data construct is encountered during execution of a
3110       // target region, the behavior is unspecified.
3111       NestingProhibited = Stack->hasDirective(
3112           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3113                              SourceLocation) {
3114             if (isOpenMPTargetExecutionDirective(K)) {
3115               OffendingRegion = K;
3116               return true;
3117             }
3118             return false;
3119           },
3120           false /* don't skip top directive */);
3121       CloseNesting = false;
3122     }
3123     if (NestingProhibited) {
3124       if (OrphanSeen) {
3125         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3126             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3127       } else {
3128         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3129             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3130             << Recommend << getOpenMPDirectiveName(CurrentRegion);
3131       }
3132       return true;
3133     }
3134   }
3135   return false;
3136 }
3137 
3138 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3139                            ArrayRef<OMPClause *> Clauses,
3140                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3141   bool ErrorFound = false;
3142   unsigned NamedModifiersNumber = 0;
3143   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3144       OMPD_unknown + 1);
3145   SmallVector<SourceLocation, 4> NameModifierLoc;
3146   for (const OMPClause *C : Clauses) {
3147     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3148       // At most one if clause without a directive-name-modifier can appear on
3149       // the directive.
3150       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3151       if (FoundNameModifiers[CurNM]) {
3152         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3153             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3154             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3155         ErrorFound = true;
3156       } else if (CurNM != OMPD_unknown) {
3157         NameModifierLoc.push_back(IC->getNameModifierLoc());
3158         ++NamedModifiersNumber;
3159       }
3160       FoundNameModifiers[CurNM] = IC;
3161       if (CurNM == OMPD_unknown)
3162         continue;
3163       // Check if the specified name modifier is allowed for the current
3164       // directive.
3165       // At most one if clause with the particular directive-name-modifier can
3166       // appear on the directive.
3167       bool MatchFound = false;
3168       for (auto NM : AllowedNameModifiers) {
3169         if (CurNM == NM) {
3170           MatchFound = true;
3171           break;
3172         }
3173       }
3174       if (!MatchFound) {
3175         S.Diag(IC->getNameModifierLoc(),
3176                diag::err_omp_wrong_if_directive_name_modifier)
3177             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3178         ErrorFound = true;
3179       }
3180     }
3181   }
3182   // If any if clause on the directive includes a directive-name-modifier then
3183   // all if clauses on the directive must include a directive-name-modifier.
3184   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3185     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3186       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3187              diag::err_omp_no_more_if_clause);
3188     } else {
3189       std::string Values;
3190       std::string Sep(", ");
3191       unsigned AllowedCnt = 0;
3192       unsigned TotalAllowedNum =
3193           AllowedNameModifiers.size() - NamedModifiersNumber;
3194       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3195            ++Cnt) {
3196         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3197         if (!FoundNameModifiers[NM]) {
3198           Values += "'";
3199           Values += getOpenMPDirectiveName(NM);
3200           Values += "'";
3201           if (AllowedCnt + 2 == TotalAllowedNum)
3202             Values += " or ";
3203           else if (AllowedCnt + 1 != TotalAllowedNum)
3204             Values += Sep;
3205           ++AllowedCnt;
3206         }
3207       }
3208       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3209              diag::err_omp_unnamed_if_clause)
3210           << (TotalAllowedNum > 1) << Values;
3211     }
3212     for (SourceLocation Loc : NameModifierLoc) {
3213       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3214     }
3215     ErrorFound = true;
3216   }
3217   return ErrorFound;
3218 }
3219 
3220 StmtResult Sema::ActOnOpenMPExecutableDirective(
3221     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3222     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3223     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3224   StmtResult Res = StmtError();
3225   // First check CancelRegion which is then used in checkNestingOfRegions.
3226   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3227       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3228                             StartLoc))
3229     return StmtError();
3230 
3231   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3232   VarsWithInheritedDSAType VarsWithInheritedDSA;
3233   bool ErrorFound = false;
3234   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3235   if (AStmt && !CurContext->isDependentContext()) {
3236     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3237 
3238     // Check default data sharing attributes for referenced variables.
3239     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3240     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3241     Stmt *S = AStmt;
3242     while (--ThisCaptureLevel >= 0)
3243       S = cast<CapturedStmt>(S)->getCapturedStmt();
3244     DSAChecker.Visit(S);
3245     if (DSAChecker.isErrorFound())
3246       return StmtError();
3247     // Generate list of implicitly defined firstprivate variables.
3248     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3249 
3250     SmallVector<Expr *, 4> ImplicitFirstprivates(
3251         DSAChecker.getImplicitFirstprivate().begin(),
3252         DSAChecker.getImplicitFirstprivate().end());
3253     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3254                                         DSAChecker.getImplicitMap().end());
3255     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3256     for (OMPClause *C : Clauses) {
3257       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3258         for (Expr *E : IRC->taskgroup_descriptors())
3259           if (E)
3260             ImplicitFirstprivates.emplace_back(E);
3261       }
3262     }
3263     if (!ImplicitFirstprivates.empty()) {
3264       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3265               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3266               SourceLocation())) {
3267         ClausesWithImplicit.push_back(Implicit);
3268         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3269                      ImplicitFirstprivates.size();
3270       } else {
3271         ErrorFound = true;
3272       }
3273     }
3274     if (!ImplicitMaps.empty()) {
3275       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3276               OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3277               SourceLocation(), SourceLocation(), ImplicitMaps,
3278               SourceLocation(), SourceLocation(), SourceLocation())) {
3279         ClausesWithImplicit.emplace_back(Implicit);
3280         ErrorFound |=
3281             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3282       } else {
3283         ErrorFound = true;
3284       }
3285     }
3286   }
3287 
3288   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3289   switch (Kind) {
3290   case OMPD_parallel:
3291     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3292                                        EndLoc);
3293     AllowedNameModifiers.push_back(OMPD_parallel);
3294     break;
3295   case OMPD_simd:
3296     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3297                                    VarsWithInheritedDSA);
3298     break;
3299   case OMPD_for:
3300     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3301                                   VarsWithInheritedDSA);
3302     break;
3303   case OMPD_for_simd:
3304     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3305                                       EndLoc, VarsWithInheritedDSA);
3306     break;
3307   case OMPD_sections:
3308     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3309                                        EndLoc);
3310     break;
3311   case OMPD_section:
3312     assert(ClausesWithImplicit.empty() &&
3313            "No clauses are allowed for 'omp section' directive");
3314     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3315     break;
3316   case OMPD_single:
3317     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3318                                      EndLoc);
3319     break;
3320   case OMPD_master:
3321     assert(ClausesWithImplicit.empty() &&
3322            "No clauses are allowed for 'omp master' directive");
3323     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3324     break;
3325   case OMPD_critical:
3326     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3327                                        StartLoc, EndLoc);
3328     break;
3329   case OMPD_parallel_for:
3330     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3331                                           EndLoc, VarsWithInheritedDSA);
3332     AllowedNameModifiers.push_back(OMPD_parallel);
3333     break;
3334   case OMPD_parallel_for_simd:
3335     Res = ActOnOpenMPParallelForSimdDirective(
3336         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3337     AllowedNameModifiers.push_back(OMPD_parallel);
3338     break;
3339   case OMPD_parallel_sections:
3340     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3341                                                StartLoc, EndLoc);
3342     AllowedNameModifiers.push_back(OMPD_parallel);
3343     break;
3344   case OMPD_task:
3345     Res =
3346         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3347     AllowedNameModifiers.push_back(OMPD_task);
3348     break;
3349   case OMPD_taskyield:
3350     assert(ClausesWithImplicit.empty() &&
3351            "No clauses are allowed for 'omp taskyield' directive");
3352     assert(AStmt == nullptr &&
3353            "No associated statement allowed for 'omp taskyield' directive");
3354     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3355     break;
3356   case OMPD_barrier:
3357     assert(ClausesWithImplicit.empty() &&
3358            "No clauses are allowed for 'omp barrier' directive");
3359     assert(AStmt == nullptr &&
3360            "No associated statement allowed for 'omp barrier' directive");
3361     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3362     break;
3363   case OMPD_taskwait:
3364     assert(ClausesWithImplicit.empty() &&
3365            "No clauses are allowed for 'omp taskwait' directive");
3366     assert(AStmt == nullptr &&
3367            "No associated statement allowed for 'omp taskwait' directive");
3368     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3369     break;
3370   case OMPD_taskgroup:
3371     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3372                                         EndLoc);
3373     break;
3374   case OMPD_flush:
3375     assert(AStmt == nullptr &&
3376            "No associated statement allowed for 'omp flush' directive");
3377     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3378     break;
3379   case OMPD_ordered:
3380     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3381                                       EndLoc);
3382     break;
3383   case OMPD_atomic:
3384     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3385                                      EndLoc);
3386     break;
3387   case OMPD_teams:
3388     Res =
3389         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3390     break;
3391   case OMPD_target:
3392     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3393                                      EndLoc);
3394     AllowedNameModifiers.push_back(OMPD_target);
3395     break;
3396   case OMPD_target_parallel:
3397     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3398                                              StartLoc, EndLoc);
3399     AllowedNameModifiers.push_back(OMPD_target);
3400     AllowedNameModifiers.push_back(OMPD_parallel);
3401     break;
3402   case OMPD_target_parallel_for:
3403     Res = ActOnOpenMPTargetParallelForDirective(
3404         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3405     AllowedNameModifiers.push_back(OMPD_target);
3406     AllowedNameModifiers.push_back(OMPD_parallel);
3407     break;
3408   case OMPD_cancellation_point:
3409     assert(ClausesWithImplicit.empty() &&
3410            "No clauses are allowed for 'omp cancellation point' directive");
3411     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3412                                "cancellation point' directive");
3413     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3414     break;
3415   case OMPD_cancel:
3416     assert(AStmt == nullptr &&
3417            "No associated statement allowed for 'omp cancel' directive");
3418     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3419                                      CancelRegion);
3420     AllowedNameModifiers.push_back(OMPD_cancel);
3421     break;
3422   case OMPD_target_data:
3423     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3424                                          EndLoc);
3425     AllowedNameModifiers.push_back(OMPD_target_data);
3426     break;
3427   case OMPD_target_enter_data:
3428     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3429                                               EndLoc, AStmt);
3430     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3431     break;
3432   case OMPD_target_exit_data:
3433     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3434                                              EndLoc, AStmt);
3435     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3436     break;
3437   case OMPD_taskloop:
3438     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3439                                        EndLoc, VarsWithInheritedDSA);
3440     AllowedNameModifiers.push_back(OMPD_taskloop);
3441     break;
3442   case OMPD_taskloop_simd:
3443     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3444                                            EndLoc, VarsWithInheritedDSA);
3445     AllowedNameModifiers.push_back(OMPD_taskloop);
3446     break;
3447   case OMPD_distribute:
3448     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3449                                          EndLoc, VarsWithInheritedDSA);
3450     break;
3451   case OMPD_target_update:
3452     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3453                                            EndLoc, AStmt);
3454     AllowedNameModifiers.push_back(OMPD_target_update);
3455     break;
3456   case OMPD_distribute_parallel_for:
3457     Res = ActOnOpenMPDistributeParallelForDirective(
3458         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3459     AllowedNameModifiers.push_back(OMPD_parallel);
3460     break;
3461   case OMPD_distribute_parallel_for_simd:
3462     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3463         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3464     AllowedNameModifiers.push_back(OMPD_parallel);
3465     break;
3466   case OMPD_distribute_simd:
3467     Res = ActOnOpenMPDistributeSimdDirective(
3468         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3469     break;
3470   case OMPD_target_parallel_for_simd:
3471     Res = ActOnOpenMPTargetParallelForSimdDirective(
3472         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3473     AllowedNameModifiers.push_back(OMPD_target);
3474     AllowedNameModifiers.push_back(OMPD_parallel);
3475     break;
3476   case OMPD_target_simd:
3477     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3478                                          EndLoc, VarsWithInheritedDSA);
3479     AllowedNameModifiers.push_back(OMPD_target);
3480     break;
3481   case OMPD_teams_distribute:
3482     Res = ActOnOpenMPTeamsDistributeDirective(
3483         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3484     break;
3485   case OMPD_teams_distribute_simd:
3486     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3487         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3488     break;
3489   case OMPD_teams_distribute_parallel_for_simd:
3490     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3491         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3492     AllowedNameModifiers.push_back(OMPD_parallel);
3493     break;
3494   case OMPD_teams_distribute_parallel_for:
3495     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3496         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3497     AllowedNameModifiers.push_back(OMPD_parallel);
3498     break;
3499   case OMPD_target_teams:
3500     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3501                                           EndLoc);
3502     AllowedNameModifiers.push_back(OMPD_target);
3503     break;
3504   case OMPD_target_teams_distribute:
3505     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3506         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3507     AllowedNameModifiers.push_back(OMPD_target);
3508     break;
3509   case OMPD_target_teams_distribute_parallel_for:
3510     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3511         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3512     AllowedNameModifiers.push_back(OMPD_target);
3513     AllowedNameModifiers.push_back(OMPD_parallel);
3514     break;
3515   case OMPD_target_teams_distribute_parallel_for_simd:
3516     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3517         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3518     AllowedNameModifiers.push_back(OMPD_target);
3519     AllowedNameModifiers.push_back(OMPD_parallel);
3520     break;
3521   case OMPD_target_teams_distribute_simd:
3522     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3523         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3524     AllowedNameModifiers.push_back(OMPD_target);
3525     break;
3526   case OMPD_declare_target:
3527   case OMPD_end_declare_target:
3528   case OMPD_threadprivate:
3529   case OMPD_declare_reduction:
3530   case OMPD_declare_simd:
3531   case OMPD_requires:
3532     llvm_unreachable("OpenMP Directive is not allowed");
3533   case OMPD_unknown:
3534     llvm_unreachable("Unknown OpenMP directive");
3535   }
3536 
3537   for (const auto &P : VarsWithInheritedDSA) {
3538     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3539         << P.first << P.second->getSourceRange();
3540   }
3541   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3542 
3543   if (!AllowedNameModifiers.empty())
3544     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3545                  ErrorFound;
3546 
3547   if (ErrorFound)
3548     return StmtError();
3549   return Res;
3550 }
3551 
3552 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3553     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3554     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3555     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3556     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3557   assert(Aligneds.size() == Alignments.size());
3558   assert(Linears.size() == LinModifiers.size());
3559   assert(Linears.size() == Steps.size());
3560   if (!DG || DG.get().isNull())
3561     return DeclGroupPtrTy();
3562 
3563   if (!DG.get().isSingleDecl()) {
3564     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3565     return DG;
3566   }
3567   Decl *ADecl = DG.get().getSingleDecl();
3568   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3569     ADecl = FTD->getTemplatedDecl();
3570 
3571   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3572   if (!FD) {
3573     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3574     return DeclGroupPtrTy();
3575   }
3576 
3577   // OpenMP [2.8.2, declare simd construct, Description]
3578   // The parameter of the simdlen clause must be a constant positive integer
3579   // expression.
3580   ExprResult SL;
3581   if (Simdlen)
3582     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3583   // OpenMP [2.8.2, declare simd construct, Description]
3584   // The special this pointer can be used as if was one of the arguments to the
3585   // function in any of the linear, aligned, or uniform clauses.
3586   // The uniform clause declares one or more arguments to have an invariant
3587   // value for all concurrent invocations of the function in the execution of a
3588   // single SIMD loop.
3589   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3590   const Expr *UniformedLinearThis = nullptr;
3591   for (const Expr *E : Uniforms) {
3592     E = E->IgnoreParenImpCasts();
3593     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3594       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3595         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3596             FD->getParamDecl(PVD->getFunctionScopeIndex())
3597                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3598           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
3599           continue;
3600         }
3601     if (isa<CXXThisExpr>(E)) {
3602       UniformedLinearThis = E;
3603       continue;
3604     }
3605     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3606         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3607   }
3608   // OpenMP [2.8.2, declare simd construct, Description]
3609   // The aligned clause declares that the object to which each list item points
3610   // is aligned to the number of bytes expressed in the optional parameter of
3611   // the aligned clause.
3612   // The special this pointer can be used as if was one of the arguments to the
3613   // function in any of the linear, aligned, or uniform clauses.
3614   // The type of list items appearing in the aligned clause must be array,
3615   // pointer, reference to array, or reference to pointer.
3616   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3617   const Expr *AlignedThis = nullptr;
3618   for (const Expr *E : Aligneds) {
3619     E = E->IgnoreParenImpCasts();
3620     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3621       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3622         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3623         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3624             FD->getParamDecl(PVD->getFunctionScopeIndex())
3625                     ->getCanonicalDecl() == CanonPVD) {
3626           // OpenMP  [2.8.1, simd construct, Restrictions]
3627           // A list-item cannot appear in more than one aligned clause.
3628           if (AlignedArgs.count(CanonPVD) > 0) {
3629             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3630                 << 1 << E->getSourceRange();
3631             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3632                  diag::note_omp_explicit_dsa)
3633                 << getOpenMPClauseName(OMPC_aligned);
3634             continue;
3635           }
3636           AlignedArgs[CanonPVD] = E;
3637           QualType QTy = PVD->getType()
3638                              .getNonReferenceType()
3639                              .getUnqualifiedType()
3640                              .getCanonicalType();
3641           const Type *Ty = QTy.getTypePtrOrNull();
3642           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3643             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3644                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3645             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3646           }
3647           continue;
3648         }
3649       }
3650     if (isa<CXXThisExpr>(E)) {
3651       if (AlignedThis) {
3652         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3653             << 2 << E->getSourceRange();
3654         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3655             << getOpenMPClauseName(OMPC_aligned);
3656       }
3657       AlignedThis = E;
3658       continue;
3659     }
3660     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3661         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3662   }
3663   // The optional parameter of the aligned clause, alignment, must be a constant
3664   // positive integer expression. If no optional parameter is specified,
3665   // implementation-defined default alignments for SIMD instructions on the
3666   // target platforms are assumed.
3667   SmallVector<const Expr *, 4> NewAligns;
3668   for (Expr *E : Alignments) {
3669     ExprResult Align;
3670     if (E)
3671       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3672     NewAligns.push_back(Align.get());
3673   }
3674   // OpenMP [2.8.2, declare simd construct, Description]
3675   // The linear clause declares one or more list items to be private to a SIMD
3676   // lane and to have a linear relationship with respect to the iteration space
3677   // of a loop.
3678   // The special this pointer can be used as if was one of the arguments to the
3679   // function in any of the linear, aligned, or uniform clauses.
3680   // When a linear-step expression is specified in a linear clause it must be
3681   // either a constant integer expression or an integer-typed parameter that is
3682   // specified in a uniform clause on the directive.
3683   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
3684   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3685   auto MI = LinModifiers.begin();
3686   for (const Expr *E : Linears) {
3687     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3688     ++MI;
3689     E = E->IgnoreParenImpCasts();
3690     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3691       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3692         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3693         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3694             FD->getParamDecl(PVD->getFunctionScopeIndex())
3695                     ->getCanonicalDecl() == CanonPVD) {
3696           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3697           // A list-item cannot appear in more than one linear clause.
3698           if (LinearArgs.count(CanonPVD) > 0) {
3699             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3700                 << getOpenMPClauseName(OMPC_linear)
3701                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3702             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3703                  diag::note_omp_explicit_dsa)
3704                 << getOpenMPClauseName(OMPC_linear);
3705             continue;
3706           }
3707           // Each argument can appear in at most one uniform or linear clause.
3708           if (UniformedArgs.count(CanonPVD) > 0) {
3709             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3710                 << getOpenMPClauseName(OMPC_linear)
3711                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3712             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3713                  diag::note_omp_explicit_dsa)
3714                 << getOpenMPClauseName(OMPC_uniform);
3715             continue;
3716           }
3717           LinearArgs[CanonPVD] = E;
3718           if (E->isValueDependent() || E->isTypeDependent() ||
3719               E->isInstantiationDependent() ||
3720               E->containsUnexpandedParameterPack())
3721             continue;
3722           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3723                                       PVD->getOriginalType());
3724           continue;
3725         }
3726       }
3727     if (isa<CXXThisExpr>(E)) {
3728       if (UniformedLinearThis) {
3729         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3730             << getOpenMPClauseName(OMPC_linear)
3731             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3732             << E->getSourceRange();
3733         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3734             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3735                                                    : OMPC_linear);
3736         continue;
3737       }
3738       UniformedLinearThis = E;
3739       if (E->isValueDependent() || E->isTypeDependent() ||
3740           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3741         continue;
3742       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3743                                   E->getType());
3744       continue;
3745     }
3746     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3747         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3748   }
3749   Expr *Step = nullptr;
3750   Expr *NewStep = nullptr;
3751   SmallVector<Expr *, 4> NewSteps;
3752   for (Expr *E : Steps) {
3753     // Skip the same step expression, it was checked already.
3754     if (Step == E || !E) {
3755       NewSteps.push_back(E ? NewStep : nullptr);
3756       continue;
3757     }
3758     Step = E;
3759     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3760       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3761         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3762         if (UniformedArgs.count(CanonPVD) == 0) {
3763           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3764               << Step->getSourceRange();
3765         } else if (E->isValueDependent() || E->isTypeDependent() ||
3766                    E->isInstantiationDependent() ||
3767                    E->containsUnexpandedParameterPack() ||
3768                    CanonPVD->getType()->hasIntegerRepresentation()) {
3769           NewSteps.push_back(Step);
3770         } else {
3771           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3772               << Step->getSourceRange();
3773         }
3774         continue;
3775       }
3776     NewStep = Step;
3777     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3778         !Step->isInstantiationDependent() &&
3779         !Step->containsUnexpandedParameterPack()) {
3780       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3781                     .get();
3782       if (NewStep)
3783         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3784     }
3785     NewSteps.push_back(NewStep);
3786   }
3787   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3788       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3789       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3790       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3791       const_cast<Expr **>(Linears.data()), Linears.size(),
3792       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3793       NewSteps.data(), NewSteps.size(), SR);
3794   ADecl->addAttr(NewAttr);
3795   return ConvertDeclToDeclGroup(ADecl);
3796 }
3797 
3798 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3799                                               Stmt *AStmt,
3800                                               SourceLocation StartLoc,
3801                                               SourceLocation EndLoc) {
3802   if (!AStmt)
3803     return StmtError();
3804 
3805   auto *CS = cast<CapturedStmt>(AStmt);
3806   // 1.2.2 OpenMP Language Terminology
3807   // Structured block - An executable statement with a single entry at the
3808   // top and a single exit at the bottom.
3809   // The point of exit cannot be a branch out of the structured block.
3810   // longjmp() and throw() must not violate the entry/exit criteria.
3811   CS->getCapturedDecl()->setNothrow();
3812 
3813   setFunctionHasBranchProtectedScope();
3814 
3815   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3816                                       DSAStack->isCancelRegion());
3817 }
3818 
3819 namespace {
3820 /// Helper class for checking canonical form of the OpenMP loops and
3821 /// extracting iteration space of each loop in the loop nest, that will be used
3822 /// for IR generation.
3823 class OpenMPIterationSpaceChecker {
3824   /// Reference to Sema.
3825   Sema &SemaRef;
3826   /// A location for diagnostics (when there is no some better location).
3827   SourceLocation DefaultLoc;
3828   /// A location for diagnostics (when increment is not compatible).
3829   SourceLocation ConditionLoc;
3830   /// A source location for referring to loop init later.
3831   SourceRange InitSrcRange;
3832   /// A source location for referring to condition later.
3833   SourceRange ConditionSrcRange;
3834   /// A source location for referring to increment later.
3835   SourceRange IncrementSrcRange;
3836   /// Loop variable.
3837   ValueDecl *LCDecl = nullptr;
3838   /// Reference to loop variable.
3839   Expr *LCRef = nullptr;
3840   /// Lower bound (initializer for the var).
3841   Expr *LB = nullptr;
3842   /// Upper bound.
3843   Expr *UB = nullptr;
3844   /// Loop step (increment).
3845   Expr *Step = nullptr;
3846   /// This flag is true when condition is one of:
3847   ///   Var <  UB
3848   ///   Var <= UB
3849   ///   UB  >  Var
3850   ///   UB  >= Var
3851   bool TestIsLessOp = false;
3852   /// This flag is true when condition is strict ( < or > ).
3853   bool TestIsStrictOp = false;
3854   /// This flag is true when step is subtracted on each iteration.
3855   bool SubtractStep = false;
3856 
3857 public:
3858   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3859       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3860   /// Check init-expr for canonical loop form and save loop counter
3861   /// variable - #Var and its initialization value - #LB.
3862   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
3863   /// Check test-expr for canonical form, save upper-bound (#UB), flags
3864   /// for less/greater and for strict/non-strict comparison.
3865   bool checkAndSetCond(Expr *S);
3866   /// Check incr-expr for canonical loop form and return true if it
3867   /// does not conform, otherwise save loop step (#Step).
3868   bool checkAndSetInc(Expr *S);
3869   /// Return the loop counter variable.
3870   ValueDecl *getLoopDecl() const { return LCDecl; }
3871   /// Return the reference expression to loop counter variable.
3872   Expr *getLoopDeclRefExpr() const { return LCRef; }
3873   /// Source range of the loop init.
3874   SourceRange getInitSrcRange() const { return InitSrcRange; }
3875   /// Source range of the loop condition.
3876   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
3877   /// Source range of the loop increment.
3878   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
3879   /// True if the step should be subtracted.
3880   bool shouldSubtractStep() const { return SubtractStep; }
3881   /// Build the expression to calculate the number of iterations.
3882   Expr *buildNumIterations(
3883       Scope *S, const bool LimitedType,
3884       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3885   /// Build the precondition expression for the loops.
3886   Expr *
3887   buildPreCond(Scope *S, Expr *Cond,
3888                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3889   /// Build reference expression to the counter be used for codegen.
3890   DeclRefExpr *
3891   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3892                   DSAStackTy &DSA) const;
3893   /// Build reference expression to the private counter be used for
3894   /// codegen.
3895   Expr *buildPrivateCounterVar() const;
3896   /// Build initialization of the counter be used for codegen.
3897   Expr *buildCounterInit() const;
3898   /// Build step of the counter be used for codegen.
3899   Expr *buildCounterStep() const;
3900   /// Build loop data with counter value for depend clauses in ordered
3901   /// directives.
3902   Expr *
3903   buildOrderedLoopData(Scope *S, Expr *Counter,
3904                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3905                        SourceLocation Loc, Expr *Inc = nullptr,
3906                        OverloadedOperatorKind OOK = OO_Amp);
3907   /// Return true if any expression is dependent.
3908   bool dependent() const;
3909 
3910 private:
3911   /// Check the right-hand side of an assignment in the increment
3912   /// expression.
3913   bool checkAndSetIncRHS(Expr *RHS);
3914   /// Helper to set loop counter variable and its initializer.
3915   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3916   /// Helper to set upper bound.
3917   bool setUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3918              SourceLocation SL);
3919   /// Helper to set loop increment.
3920   bool setStep(Expr *NewStep, bool Subtract);
3921 };
3922 
3923 bool OpenMPIterationSpaceChecker::dependent() const {
3924   if (!LCDecl) {
3925     assert(!LB && !UB && !Step);
3926     return false;
3927   }
3928   return LCDecl->getType()->isDependentType() ||
3929          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3930          (Step && Step->isValueDependent());
3931 }
3932 
3933 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
3934                                                  Expr *NewLCRefExpr,
3935                                                  Expr *NewLB) {
3936   // State consistency checking to ensure correct usage.
3937   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3938          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3939   if (!NewLCDecl || !NewLB)
3940     return true;
3941   LCDecl = getCanonicalDecl(NewLCDecl);
3942   LCRef = NewLCRefExpr;
3943   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3944     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3945       if ((Ctor->isCopyOrMoveConstructor() ||
3946            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3947           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3948         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3949   LB = NewLB;
3950   return false;
3951 }
3952 
3953 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, bool LessOp, bool StrictOp,
3954                                         SourceRange SR, SourceLocation SL) {
3955   // State consistency checking to ensure correct usage.
3956   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3957          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3958   if (!NewUB)
3959     return true;
3960   UB = NewUB;
3961   TestIsLessOp = LessOp;
3962   TestIsStrictOp = StrictOp;
3963   ConditionSrcRange = SR;
3964   ConditionLoc = SL;
3965   return false;
3966 }
3967 
3968 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
3969   // State consistency checking to ensure correct usage.
3970   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3971   if (!NewStep)
3972     return true;
3973   if (!NewStep->isValueDependent()) {
3974     // Check that the step is integer expression.
3975     SourceLocation StepLoc = NewStep->getBeginLoc();
3976     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3977         StepLoc, getExprAsWritten(NewStep));
3978     if (Val.isInvalid())
3979       return true;
3980     NewStep = Val.get();
3981 
3982     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3983     //  If test-expr is of form var relational-op b and relational-op is < or
3984     //  <= then incr-expr must cause var to increase on each iteration of the
3985     //  loop. If test-expr is of form var relational-op b and relational-op is
3986     //  > or >= then incr-expr must cause var to decrease on each iteration of
3987     //  the loop.
3988     //  If test-expr is of form b relational-op var and relational-op is < or
3989     //  <= then incr-expr must cause var to decrease on each iteration of the
3990     //  loop. If test-expr is of form b relational-op var and relational-op is
3991     //  > or >= then incr-expr must cause var to increase on each iteration of
3992     //  the loop.
3993     llvm::APSInt Result;
3994     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3995     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3996     bool IsConstNeg =
3997         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3998     bool IsConstPos =
3999         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4000     bool IsConstZero = IsConstant && !Result.getBoolValue();
4001     if (UB && (IsConstZero ||
4002                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
4003                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
4004       SemaRef.Diag(NewStep->getExprLoc(),
4005                    diag::err_omp_loop_incr_not_compatible)
4006           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
4007       SemaRef.Diag(ConditionLoc,
4008                    diag::note_omp_loop_cond_requres_compatible_incr)
4009           << TestIsLessOp << ConditionSrcRange;
4010       return true;
4011     }
4012     if (TestIsLessOp == Subtract) {
4013       NewStep =
4014           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4015               .get();
4016       Subtract = !Subtract;
4017     }
4018   }
4019 
4020   Step = NewStep;
4021   SubtractStep = Subtract;
4022   return false;
4023 }
4024 
4025 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4026   // Check init-expr for canonical loop form and save loop counter
4027   // variable - #Var and its initialization value - #LB.
4028   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4029   //   var = lb
4030   //   integer-type var = lb
4031   //   random-access-iterator-type var = lb
4032   //   pointer-type var = lb
4033   //
4034   if (!S) {
4035     if (EmitDiags) {
4036       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4037     }
4038     return true;
4039   }
4040   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4041     if (!ExprTemp->cleanupsHaveSideEffects())
4042       S = ExprTemp->getSubExpr();
4043 
4044   InitSrcRange = S->getSourceRange();
4045   if (Expr *E = dyn_cast<Expr>(S))
4046     S = E->IgnoreParens();
4047   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4048     if (BO->getOpcode() == BO_Assign) {
4049       Expr *LHS = BO->getLHS()->IgnoreParens();
4050       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4051         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4052           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4053             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4054         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
4055       }
4056       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4057         if (ME->isArrow() &&
4058             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4059           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4060       }
4061     }
4062   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4063     if (DS->isSingleDecl()) {
4064       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4065         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4066           // Accept non-canonical init form here but emit ext. warning.
4067           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4068             SemaRef.Diag(S->getBeginLoc(),
4069                          diag::ext_omp_loop_not_canonical_init)
4070                 << S->getSourceRange();
4071           return setLCDeclAndLB(
4072               Var,
4073               buildDeclRefExpr(SemaRef, Var,
4074                                Var->getType().getNonReferenceType(),
4075                                DS->getBeginLoc()),
4076               Var->getInit());
4077         }
4078       }
4079     }
4080   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4081     if (CE->getOperator() == OO_Equal) {
4082       Expr *LHS = CE->getArg(0);
4083       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4084         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4085           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4086             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4087         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
4088       }
4089       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4090         if (ME->isArrow() &&
4091             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4092           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4093       }
4094     }
4095   }
4096 
4097   if (dependent() || SemaRef.CurContext->isDependentContext())
4098     return false;
4099   if (EmitDiags) {
4100     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
4101         << S->getSourceRange();
4102   }
4103   return true;
4104 }
4105 
4106 /// Ignore parenthesizes, implicit casts, copy constructor and return the
4107 /// variable (which may be the loop variable) if possible.
4108 static const ValueDecl *getInitLCDecl(const Expr *E) {
4109   if (!E)
4110     return nullptr;
4111   E = getExprAsWritten(E);
4112   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4113     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4114       if ((Ctor->isCopyOrMoveConstructor() ||
4115            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4116           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4117         E = CE->getArg(0)->IgnoreParenImpCasts();
4118   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4119     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4120       return getCanonicalDecl(VD);
4121   }
4122   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
4123     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4124       return getCanonicalDecl(ME->getMemberDecl());
4125   return nullptr;
4126 }
4127 
4128 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
4129   // Check test-expr for canonical form, save upper-bound UB, flags for
4130   // less/greater and for strict/non-strict comparison.
4131   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4132   //   var relational-op b
4133   //   b relational-op var
4134   //
4135   if (!S) {
4136     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4137     return true;
4138   }
4139   S = getExprAsWritten(S);
4140   SourceLocation CondLoc = S->getBeginLoc();
4141   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4142     if (BO->isRelationalOp()) {
4143       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4144         return setUB(BO->getRHS(),
4145                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4146                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4147                      BO->getSourceRange(), BO->getOperatorLoc());
4148       if (getInitLCDecl(BO->getRHS()) == LCDecl)
4149         return setUB(BO->getLHS(),
4150                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4151                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4152                      BO->getSourceRange(), BO->getOperatorLoc());
4153     }
4154   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4155     if (CE->getNumArgs() == 2) {
4156       auto Op = CE->getOperator();
4157       switch (Op) {
4158       case OO_Greater:
4159       case OO_GreaterEqual:
4160       case OO_Less:
4161       case OO_LessEqual:
4162         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4163           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4164                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4165                        CE->getOperatorLoc());
4166         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4167           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4168                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4169                        CE->getOperatorLoc());
4170         break;
4171       default:
4172         break;
4173       }
4174     }
4175   }
4176   if (dependent() || SemaRef.CurContext->isDependentContext())
4177     return false;
4178   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4179       << S->getSourceRange() << LCDecl;
4180   return true;
4181 }
4182 
4183 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4184   // RHS of canonical loop form increment can be:
4185   //   var + incr
4186   //   incr + var
4187   //   var - incr
4188   //
4189   RHS = RHS->IgnoreParenImpCasts();
4190   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4191     if (BO->isAdditiveOp()) {
4192       bool IsAdd = BO->getOpcode() == BO_Add;
4193       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4194         return setStep(BO->getRHS(), !IsAdd);
4195       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4196         return setStep(BO->getLHS(), /*Subtract=*/false);
4197     }
4198   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4199     bool IsAdd = CE->getOperator() == OO_Plus;
4200     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4201       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4202         return setStep(CE->getArg(1), !IsAdd);
4203       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4204         return setStep(CE->getArg(0), /*Subtract=*/false);
4205     }
4206   }
4207   if (dependent() || SemaRef.CurContext->isDependentContext())
4208     return false;
4209   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4210       << RHS->getSourceRange() << LCDecl;
4211   return true;
4212 }
4213 
4214 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4215   // Check incr-expr for canonical loop form and return true if it
4216   // does not conform.
4217   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4218   //   ++var
4219   //   var++
4220   //   --var
4221   //   var--
4222   //   var += incr
4223   //   var -= incr
4224   //   var = var + incr
4225   //   var = incr + var
4226   //   var = var - incr
4227   //
4228   if (!S) {
4229     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4230     return true;
4231   }
4232   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4233     if (!ExprTemp->cleanupsHaveSideEffects())
4234       S = ExprTemp->getSubExpr();
4235 
4236   IncrementSrcRange = S->getSourceRange();
4237   S = S->IgnoreParens();
4238   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4239     if (UO->isIncrementDecrementOp() &&
4240         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4241       return setStep(SemaRef
4242                          .ActOnIntegerConstant(UO->getBeginLoc(),
4243                                                (UO->isDecrementOp() ? -1 : 1))
4244                          .get(),
4245                      /*Subtract=*/false);
4246   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4247     switch (BO->getOpcode()) {
4248     case BO_AddAssign:
4249     case BO_SubAssign:
4250       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4251         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4252       break;
4253     case BO_Assign:
4254       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4255         return checkAndSetIncRHS(BO->getRHS());
4256       break;
4257     default:
4258       break;
4259     }
4260   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4261     switch (CE->getOperator()) {
4262     case OO_PlusPlus:
4263     case OO_MinusMinus:
4264       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4265         return setStep(SemaRef
4266                            .ActOnIntegerConstant(
4267                                CE->getBeginLoc(),
4268                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4269                            .get(),
4270                        /*Subtract=*/false);
4271       break;
4272     case OO_PlusEqual:
4273     case OO_MinusEqual:
4274       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4275         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4276       break;
4277     case OO_Equal:
4278       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4279         return checkAndSetIncRHS(CE->getArg(1));
4280       break;
4281     default:
4282       break;
4283     }
4284   }
4285   if (dependent() || SemaRef.CurContext->isDependentContext())
4286     return false;
4287   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4288       << S->getSourceRange() << LCDecl;
4289   return true;
4290 }
4291 
4292 static ExprResult
4293 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4294                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4295   if (SemaRef.CurContext->isDependentContext())
4296     return ExprResult(Capture);
4297   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4298     return SemaRef.PerformImplicitConversion(
4299         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4300         /*AllowExplicit=*/true);
4301   auto I = Captures.find(Capture);
4302   if (I != Captures.end())
4303     return buildCapture(SemaRef, Capture, I->second);
4304   DeclRefExpr *Ref = nullptr;
4305   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4306   Captures[Capture] = Ref;
4307   return Res;
4308 }
4309 
4310 /// Build the expression to calculate the number of iterations.
4311 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4312     Scope *S, const bool LimitedType,
4313     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4314   ExprResult Diff;
4315   QualType VarType = LCDecl->getType().getNonReferenceType();
4316   if (VarType->isIntegerType() || VarType->isPointerType() ||
4317       SemaRef.getLangOpts().CPlusPlus) {
4318     // Upper - Lower
4319     Expr *UBExpr = TestIsLessOp ? UB : LB;
4320     Expr *LBExpr = TestIsLessOp ? LB : UB;
4321     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4322     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4323     if (!Upper || !Lower)
4324       return nullptr;
4325 
4326     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4327 
4328     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4329       // BuildBinOp already emitted error, this one is to point user to upper
4330       // and lower bound, and to tell what is passed to 'operator-'.
4331       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4332           << Upper->getSourceRange() << Lower->getSourceRange();
4333       return nullptr;
4334     }
4335   }
4336 
4337   if (!Diff.isUsable())
4338     return nullptr;
4339 
4340   // Upper - Lower [- 1]
4341   if (TestIsStrictOp)
4342     Diff = SemaRef.BuildBinOp(
4343         S, DefaultLoc, BO_Sub, Diff.get(),
4344         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4345   if (!Diff.isUsable())
4346     return nullptr;
4347 
4348   // Upper - Lower [- 1] + Step
4349   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4350   if (!NewStep.isUsable())
4351     return nullptr;
4352   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4353   if (!Diff.isUsable())
4354     return nullptr;
4355 
4356   // Parentheses (for dumping/debugging purposes only).
4357   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4358   if (!Diff.isUsable())
4359     return nullptr;
4360 
4361   // (Upper - Lower [- 1] + Step) / Step
4362   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4363   if (!Diff.isUsable())
4364     return nullptr;
4365 
4366   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4367   QualType Type = Diff.get()->getType();
4368   ASTContext &C = SemaRef.Context;
4369   bool UseVarType = VarType->hasIntegerRepresentation() &&
4370                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4371   if (!Type->isIntegerType() || UseVarType) {
4372     unsigned NewSize =
4373         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4374     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4375                                : Type->hasSignedIntegerRepresentation();
4376     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4377     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4378       Diff = SemaRef.PerformImplicitConversion(
4379           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4380       if (!Diff.isUsable())
4381         return nullptr;
4382     }
4383   }
4384   if (LimitedType) {
4385     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4386     if (NewSize != C.getTypeSize(Type)) {
4387       if (NewSize < C.getTypeSize(Type)) {
4388         assert(NewSize == 64 && "incorrect loop var size");
4389         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4390             << InitSrcRange << ConditionSrcRange;
4391       }
4392       QualType NewType = C.getIntTypeForBitwidth(
4393           NewSize, Type->hasSignedIntegerRepresentation() ||
4394                        C.getTypeSize(Type) < NewSize);
4395       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4396         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4397                                                  Sema::AA_Converting, true);
4398         if (!Diff.isUsable())
4399           return nullptr;
4400       }
4401     }
4402   }
4403 
4404   return Diff.get();
4405 }
4406 
4407 Expr *OpenMPIterationSpaceChecker::buildPreCond(
4408     Scope *S, Expr *Cond,
4409     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4410   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4411   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4412   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4413 
4414   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4415   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
4416   if (!NewLB.isUsable() || !NewUB.isUsable())
4417     return nullptr;
4418 
4419   ExprResult CondExpr =
4420       SemaRef.BuildBinOp(S, DefaultLoc,
4421                          TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4422                                       : (TestIsStrictOp ? BO_GT : BO_GE),
4423                          NewLB.get(), NewUB.get());
4424   if (CondExpr.isUsable()) {
4425     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4426                                                 SemaRef.Context.BoolTy))
4427       CondExpr = SemaRef.PerformImplicitConversion(
4428           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4429           /*AllowExplicit=*/true);
4430   }
4431   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4432   // Otherwise use original loop conditon and evaluate it in runtime.
4433   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4434 }
4435 
4436 /// Build reference expression to the counter be used for codegen.
4437 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4438     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4439     DSAStackTy &DSA) const {
4440   auto *VD = dyn_cast<VarDecl>(LCDecl);
4441   if (!VD) {
4442     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4443     DeclRefExpr *Ref = buildDeclRefExpr(
4444         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4445     const DSAStackTy::DSAVarData Data =
4446         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4447     // If the loop control decl is explicitly marked as private, do not mark it
4448     // as captured again.
4449     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4450       Captures.insert(std::make_pair(LCRef, Ref));
4451     return Ref;
4452   }
4453   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4454                           DefaultLoc);
4455 }
4456 
4457 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
4458   if (LCDecl && !LCDecl->isInvalidDecl()) {
4459     QualType Type = LCDecl->getType().getNonReferenceType();
4460     VarDecl *PrivateVar = buildVarDecl(
4461         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4462         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4463         isa<VarDecl>(LCDecl)
4464             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4465             : nullptr);
4466     if (PrivateVar->isInvalidDecl())
4467       return nullptr;
4468     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4469   }
4470   return nullptr;
4471 }
4472 
4473 /// Build initialization of the counter to be used for codegen.
4474 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
4475 
4476 /// Build step of the counter be used for codegen.
4477 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
4478 
4479 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4480     Scope *S, Expr *Counter,
4481     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4482     Expr *Inc, OverloadedOperatorKind OOK) {
4483   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4484   if (!Cnt)
4485     return nullptr;
4486   if (Inc) {
4487     assert((OOK == OO_Plus || OOK == OO_Minus) &&
4488            "Expected only + or - operations for depend clauses.");
4489     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4490     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4491     if (!Cnt)
4492       return nullptr;
4493   }
4494   ExprResult Diff;
4495   QualType VarType = LCDecl->getType().getNonReferenceType();
4496   if (VarType->isIntegerType() || VarType->isPointerType() ||
4497       SemaRef.getLangOpts().CPlusPlus) {
4498     // Upper - Lower
4499     Expr *Upper =
4500         TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
4501     Expr *Lower =
4502         TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
4503     if (!Upper || !Lower)
4504       return nullptr;
4505 
4506     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4507 
4508     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4509       // BuildBinOp already emitted error, this one is to point user to upper
4510       // and lower bound, and to tell what is passed to 'operator-'.
4511       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4512           << Upper->getSourceRange() << Lower->getSourceRange();
4513       return nullptr;
4514     }
4515   }
4516 
4517   if (!Diff.isUsable())
4518     return nullptr;
4519 
4520   // Parentheses (for dumping/debugging purposes only).
4521   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4522   if (!Diff.isUsable())
4523     return nullptr;
4524 
4525   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4526   if (!NewStep.isUsable())
4527     return nullptr;
4528   // (Upper - Lower) / Step
4529   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4530   if (!Diff.isUsable())
4531     return nullptr;
4532 
4533   return Diff.get();
4534 }
4535 
4536 /// Iteration space of a single for loop.
4537 struct LoopIterationSpace final {
4538   /// Condition of the loop.
4539   Expr *PreCond = nullptr;
4540   /// This expression calculates the number of iterations in the loop.
4541   /// It is always possible to calculate it before starting the loop.
4542   Expr *NumIterations = nullptr;
4543   /// The loop counter variable.
4544   Expr *CounterVar = nullptr;
4545   /// Private loop counter variable.
4546   Expr *PrivateCounterVar = nullptr;
4547   /// This is initializer for the initial value of #CounterVar.
4548   Expr *CounterInit = nullptr;
4549   /// This is step for the #CounterVar used to generate its update:
4550   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4551   Expr *CounterStep = nullptr;
4552   /// Should step be subtracted?
4553   bool Subtract = false;
4554   /// Source range of the loop init.
4555   SourceRange InitSrcRange;
4556   /// Source range of the loop condition.
4557   SourceRange CondSrcRange;
4558   /// Source range of the loop increment.
4559   SourceRange IncSrcRange;
4560 };
4561 
4562 } // namespace
4563 
4564 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4565   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4566   assert(Init && "Expected loop in canonical form.");
4567   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4568   if (AssociatedLoops > 0 &&
4569       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4570     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4571     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4572       if (ValueDecl *D = ISC.getLoopDecl()) {
4573         auto *VD = dyn_cast<VarDecl>(D);
4574         if (!VD) {
4575           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
4576             VD = Private;
4577           } else {
4578             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4579                                             /*WithInit=*/false);
4580             VD = cast<VarDecl>(Ref->getDecl());
4581           }
4582         }
4583         DSAStack->addLoopControlVariable(D, VD);
4584         const Decl *LD = DSAStack->getPossiblyLoopCunter();
4585         if (LD != D->getCanonicalDecl()) {
4586           DSAStack->resetPossibleLoopCounter();
4587           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4588             MarkDeclarationsReferencedInExpr(
4589                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4590                                  Var->getType().getNonLValueExprType(Context),
4591                                  ForLoc, /*RefersToCapture=*/true));
4592         }
4593       }
4594     }
4595     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4596   }
4597 }
4598 
4599 /// Called on a for stmt to check and extract its iteration space
4600 /// for further processing (such as collapsing).
4601 static bool checkOpenMPIterationSpace(
4602     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4603     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4604     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4605     Expr *OrderedLoopCountExpr,
4606     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4607     LoopIterationSpace &ResultIterSpace,
4608     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4609   // OpenMP [2.6, Canonical Loop Form]
4610   //   for (init-expr; test-expr; incr-expr) structured-block
4611   auto *For = dyn_cast_or_null<ForStmt>(S);
4612   if (!For) {
4613     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
4614         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4615         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
4616         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4617     if (TotalNestedLoopCount > 1) {
4618       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4619         SemaRef.Diag(DSA.getConstructLoc(),
4620                      diag::note_omp_collapse_ordered_expr)
4621             << 2 << CollapseLoopCountExpr->getSourceRange()
4622             << OrderedLoopCountExpr->getSourceRange();
4623       else if (CollapseLoopCountExpr)
4624         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4625                      diag::note_omp_collapse_ordered_expr)
4626             << 0 << CollapseLoopCountExpr->getSourceRange();
4627       else
4628         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4629                      diag::note_omp_collapse_ordered_expr)
4630             << 1 << OrderedLoopCountExpr->getSourceRange();
4631     }
4632     return true;
4633   }
4634   assert(For->getBody());
4635 
4636   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4637 
4638   // Check init.
4639   Stmt *Init = For->getInit();
4640   if (ISC.checkAndSetInit(Init))
4641     return true;
4642 
4643   bool HasErrors = false;
4644 
4645   // Check loop variable's type.
4646   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4647     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
4648 
4649     // OpenMP [2.6, Canonical Loop Form]
4650     // Var is one of the following:
4651     //   A variable of signed or unsigned integer type.
4652     //   For C++, a variable of a random access iterator type.
4653     //   For C, a variable of a pointer type.
4654     QualType VarType = LCDecl->getType().getNonReferenceType();
4655     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4656         !VarType->isPointerType() &&
4657         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4658       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
4659           << SemaRef.getLangOpts().CPlusPlus;
4660       HasErrors = true;
4661     }
4662 
4663     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4664     // a Construct
4665     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4666     // parallel for construct is (are) private.
4667     // The loop iteration variable in the associated for-loop of a simd
4668     // construct with just one associated for-loop is linear with a
4669     // constant-linear-step that is the increment of the associated for-loop.
4670     // Exclude loop var from the list of variables with implicitly defined data
4671     // sharing attributes.
4672     VarsWithImplicitDSA.erase(LCDecl);
4673 
4674     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4675     // in a Construct, C/C++].
4676     // The loop iteration variable in the associated for-loop of a simd
4677     // construct with just one associated for-loop may be listed in a linear
4678     // clause with a constant-linear-step that is the increment of the
4679     // associated for-loop.
4680     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4681     // parallel for construct may be listed in a private or lastprivate clause.
4682     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4683     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4684     // declared in the loop and it is predetermined as a private.
4685     OpenMPClauseKind PredeterminedCKind =
4686         isOpenMPSimdDirective(DKind)
4687             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4688             : OMPC_private;
4689     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4690           DVar.CKind != PredeterminedCKind) ||
4691          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4692            isOpenMPDistributeDirective(DKind)) &&
4693           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4694           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4695         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4696       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
4697           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4698           << getOpenMPClauseName(PredeterminedCKind);
4699       if (DVar.RefExpr == nullptr)
4700         DVar.CKind = PredeterminedCKind;
4701       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4702       HasErrors = true;
4703     } else if (LoopDeclRefExpr != nullptr) {
4704       // Make the loop iteration variable private (for worksharing constructs),
4705       // linear (for simd directives with the only one associated loop) or
4706       // lastprivate (for simd directives with several collapsed or ordered
4707       // loops).
4708       if (DVar.CKind == OMPC_unknown)
4709         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4710                           [](OpenMPDirectiveKind) -> bool { return true; },
4711                           /*FromParent=*/false);
4712       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4713     }
4714 
4715     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4716 
4717     // Check test-expr.
4718     HasErrors |= ISC.checkAndSetCond(For->getCond());
4719 
4720     // Check incr-expr.
4721     HasErrors |= ISC.checkAndSetInc(For->getInc());
4722   }
4723 
4724   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4725     return HasErrors;
4726 
4727   // Build the loop's iteration space representation.
4728   ResultIterSpace.PreCond =
4729       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4730   ResultIterSpace.NumIterations = ISC.buildNumIterations(
4731       DSA.getCurScope(),
4732       (isOpenMPWorksharingDirective(DKind) ||
4733        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4734       Captures);
4735   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4736   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4737   ResultIterSpace.CounterInit = ISC.buildCounterInit();
4738   ResultIterSpace.CounterStep = ISC.buildCounterStep();
4739   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4740   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4741   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4742   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
4743 
4744   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4745                 ResultIterSpace.NumIterations == nullptr ||
4746                 ResultIterSpace.CounterVar == nullptr ||
4747                 ResultIterSpace.PrivateCounterVar == nullptr ||
4748                 ResultIterSpace.CounterInit == nullptr ||
4749                 ResultIterSpace.CounterStep == nullptr);
4750   if (!HasErrors && DSA.isOrderedRegion()) {
4751     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4752       if (CurrentNestedLoopCount <
4753           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4754         DSA.getOrderedRegionParam().second->setLoopNumIterations(
4755             CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4756         DSA.getOrderedRegionParam().second->setLoopCounter(
4757             CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4758       }
4759     }
4760     for (auto &Pair : DSA.getDoacrossDependClauses()) {
4761       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4762         // Erroneous case - clause has some problems.
4763         continue;
4764       }
4765       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4766           Pair.second.size() <= CurrentNestedLoopCount) {
4767         // Erroneous case - clause has some problems.
4768         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4769         continue;
4770       }
4771       Expr *CntValue;
4772       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4773         CntValue = ISC.buildOrderedLoopData(
4774             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4775             Pair.first->getDependencyLoc());
4776       else
4777         CntValue = ISC.buildOrderedLoopData(
4778             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4779             Pair.first->getDependencyLoc(),
4780             Pair.second[CurrentNestedLoopCount].first,
4781             Pair.second[CurrentNestedLoopCount].second);
4782       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4783     }
4784   }
4785 
4786   return HasErrors;
4787 }
4788 
4789 /// Build 'VarRef = Start.
4790 static ExprResult
4791 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4792                  ExprResult Start,
4793                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4794   // Build 'VarRef = Start.
4795   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4796   if (!NewStart.isUsable())
4797     return ExprError();
4798   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4799                                    VarRef.get()->getType())) {
4800     NewStart = SemaRef.PerformImplicitConversion(
4801         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4802         /*AllowExplicit=*/true);
4803     if (!NewStart.isUsable())
4804       return ExprError();
4805   }
4806 
4807   ExprResult Init =
4808       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4809   return Init;
4810 }
4811 
4812 /// Build 'VarRef = Start + Iter * Step'.
4813 static ExprResult buildCounterUpdate(
4814     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4815     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4816     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
4817   // Add parentheses (for debugging purposes only).
4818   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4819   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4820       !Step.isUsable())
4821     return ExprError();
4822 
4823   ExprResult NewStep = Step;
4824   if (Captures)
4825     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4826   if (NewStep.isInvalid())
4827     return ExprError();
4828   ExprResult Update =
4829       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4830   if (!Update.isUsable())
4831     return ExprError();
4832 
4833   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4834   // 'VarRef = Start (+|-) Iter * Step'.
4835   ExprResult NewStart = Start;
4836   if (Captures)
4837     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4838   if (NewStart.isInvalid())
4839     return ExprError();
4840 
4841   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4842   ExprResult SavedUpdate = Update;
4843   ExprResult UpdateVal;
4844   if (VarRef.get()->getType()->isOverloadableType() ||
4845       NewStart.get()->getType()->isOverloadableType() ||
4846       Update.get()->getType()->isOverloadableType()) {
4847     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4848     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4849     Update =
4850         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4851     if (Update.isUsable()) {
4852       UpdateVal =
4853           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4854                              VarRef.get(), SavedUpdate.get());
4855       if (UpdateVal.isUsable()) {
4856         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4857                                             UpdateVal.get());
4858       }
4859     }
4860     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4861   }
4862 
4863   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4864   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4865     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4866                                 NewStart.get(), SavedUpdate.get());
4867     if (!Update.isUsable())
4868       return ExprError();
4869 
4870     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4871                                      VarRef.get()->getType())) {
4872       Update = SemaRef.PerformImplicitConversion(
4873           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4874       if (!Update.isUsable())
4875         return ExprError();
4876     }
4877 
4878     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4879   }
4880   return Update;
4881 }
4882 
4883 /// Convert integer expression \a E to make it have at least \a Bits
4884 /// bits.
4885 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4886   if (E == nullptr)
4887     return ExprError();
4888   ASTContext &C = SemaRef.Context;
4889   QualType OldType = E->getType();
4890   unsigned HasBits = C.getTypeSize(OldType);
4891   if (HasBits >= Bits)
4892     return ExprResult(E);
4893   // OK to convert to signed, because new type has more bits than old.
4894   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4895   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4896                                            true);
4897 }
4898 
4899 /// Check if the given expression \a E is a constant integer that fits
4900 /// into \a Bits bits.
4901 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
4902   if (E == nullptr)
4903     return false;
4904   llvm::APSInt Result;
4905   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4906     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4907   return false;
4908 }
4909 
4910 /// Build preinits statement for the given declarations.
4911 static Stmt *buildPreInits(ASTContext &Context,
4912                            MutableArrayRef<Decl *> PreInits) {
4913   if (!PreInits.empty()) {
4914     return new (Context) DeclStmt(
4915         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4916         SourceLocation(), SourceLocation());
4917   }
4918   return nullptr;
4919 }
4920 
4921 /// Build preinits statement for the given declarations.
4922 static Stmt *
4923 buildPreInits(ASTContext &Context,
4924               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4925   if (!Captures.empty()) {
4926     SmallVector<Decl *, 16> PreInits;
4927     for (const auto &Pair : Captures)
4928       PreInits.push_back(Pair.second->getDecl());
4929     return buildPreInits(Context, PreInits);
4930   }
4931   return nullptr;
4932 }
4933 
4934 /// Build postupdate expression for the given list of postupdates expressions.
4935 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4936   Expr *PostUpdate = nullptr;
4937   if (!PostUpdates.empty()) {
4938     for (Expr *E : PostUpdates) {
4939       Expr *ConvE = S.BuildCStyleCastExpr(
4940                          E->getExprLoc(),
4941                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4942                          E->getExprLoc(), E)
4943                         .get();
4944       PostUpdate = PostUpdate
4945                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4946                                               PostUpdate, ConvE)
4947                              .get()
4948                        : ConvE;
4949     }
4950   }
4951   return PostUpdate;
4952 }
4953 
4954 /// Called on a for stmt to check itself and nested loops (if any).
4955 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4956 /// number of collapsed loops otherwise.
4957 static unsigned
4958 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4959                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4960                 DSAStackTy &DSA,
4961                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4962                 OMPLoopDirective::HelperExprs &Built) {
4963   unsigned NestedLoopCount = 1;
4964   if (CollapseLoopCountExpr) {
4965     // Found 'collapse' clause - calculate collapse number.
4966     llvm::APSInt Result;
4967     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4968       NestedLoopCount = Result.getLimitedValue();
4969   }
4970   unsigned OrderedLoopCount = 1;
4971   if (OrderedLoopCountExpr) {
4972     // Found 'ordered' clause - calculate collapse number.
4973     llvm::APSInt Result;
4974     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4975       if (Result.getLimitedValue() < NestedLoopCount) {
4976         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4977                      diag::err_omp_wrong_ordered_loop_count)
4978             << OrderedLoopCountExpr->getSourceRange();
4979         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4980                      diag::note_collapse_loop_count)
4981             << CollapseLoopCountExpr->getSourceRange();
4982       }
4983       OrderedLoopCount = Result.getLimitedValue();
4984     }
4985   }
4986   // This is helper routine for loop directives (e.g., 'for', 'simd',
4987   // 'for simd', etc.).
4988   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
4989   SmallVector<LoopIterationSpace, 4> IterSpaces;
4990   IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
4991   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4992   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4993     if (checkOpenMPIterationSpace(
4994             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
4995             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
4996             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
4997             Captures))
4998       return 0;
4999     // Move on to the next nested for loop, or to the loop body.
5000     // OpenMP [2.8.1, simd construct, Restrictions]
5001     // All loops associated with the construct must be perfectly nested; that
5002     // is, there must be no intervening code nor any OpenMP directive between
5003     // any two loops.
5004     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5005   }
5006   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5007     if (checkOpenMPIterationSpace(
5008             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5009             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5010             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5011             Captures))
5012       return 0;
5013     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5014       // Handle initialization of captured loop iterator variables.
5015       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5016       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5017         Captures[DRE] = DRE;
5018       }
5019     }
5020     // Move on to the next nested for loop, or to the loop body.
5021     // OpenMP [2.8.1, simd construct, Restrictions]
5022     // All loops associated with the construct must be perfectly nested; that
5023     // is, there must be no intervening code nor any OpenMP directive between
5024     // any two loops.
5025     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5026   }
5027 
5028   Built.clear(/* size */ NestedLoopCount);
5029 
5030   if (SemaRef.CurContext->isDependentContext())
5031     return NestedLoopCount;
5032 
5033   // An example of what is generated for the following code:
5034   //
5035   //   #pragma omp simd collapse(2) ordered(2)
5036   //   for (i = 0; i < NI; ++i)
5037   //     for (k = 0; k < NK; ++k)
5038   //       for (j = J0; j < NJ; j+=2) {
5039   //         <loop body>
5040   //       }
5041   //
5042   // We generate the code below.
5043   // Note: the loop body may be outlined in CodeGen.
5044   // Note: some counters may be C++ classes, operator- is used to find number of
5045   // iterations and operator+= to calculate counter value.
5046   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5047   // or i64 is currently supported).
5048   //
5049   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5050   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5051   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5052   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5053   //     // similar updates for vars in clauses (e.g. 'linear')
5054   //     <loop body (using local i and j)>
5055   //   }
5056   //   i = NI; // assign final values of counters
5057   //   j = NJ;
5058   //
5059 
5060   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5061   // the iteration counts of the collapsed for loops.
5062   // Precondition tests if there is at least one iteration (all conditions are
5063   // true).
5064   auto PreCond = ExprResult(IterSpaces[0].PreCond);
5065   Expr *N0 = IterSpaces[0].NumIterations;
5066   ExprResult LastIteration32 =
5067       widenIterationCount(/*Bits=*/32,
5068                           SemaRef
5069                               .PerformImplicitConversion(
5070                                   N0->IgnoreImpCasts(), N0->getType(),
5071                                   Sema::AA_Converting, /*AllowExplicit=*/true)
5072                               .get(),
5073                           SemaRef);
5074   ExprResult LastIteration64 = widenIterationCount(
5075       /*Bits=*/64,
5076       SemaRef
5077           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5078                                      Sema::AA_Converting,
5079                                      /*AllowExplicit=*/true)
5080           .get(),
5081       SemaRef);
5082 
5083   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5084     return NestedLoopCount;
5085 
5086   ASTContext &C = SemaRef.Context;
5087   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5088 
5089   Scope *CurScope = DSA.getCurScope();
5090   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
5091     if (PreCond.isUsable()) {
5092       PreCond =
5093           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5094                              PreCond.get(), IterSpaces[Cnt].PreCond);
5095     }
5096     Expr *N = IterSpaces[Cnt].NumIterations;
5097     SourceLocation Loc = N->getExprLoc();
5098     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5099     if (LastIteration32.isUsable())
5100       LastIteration32 = SemaRef.BuildBinOp(
5101           CurScope, Loc, BO_Mul, LastIteration32.get(),
5102           SemaRef
5103               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5104                                          Sema::AA_Converting,
5105                                          /*AllowExplicit=*/true)
5106               .get());
5107     if (LastIteration64.isUsable())
5108       LastIteration64 = SemaRef.BuildBinOp(
5109           CurScope, Loc, BO_Mul, LastIteration64.get(),
5110           SemaRef
5111               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5112                                          Sema::AA_Converting,
5113                                          /*AllowExplicit=*/true)
5114               .get());
5115   }
5116 
5117   // Choose either the 32-bit or 64-bit version.
5118   ExprResult LastIteration = LastIteration64;
5119   if (LastIteration32.isUsable() &&
5120       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5121       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5122        fitsInto(
5123            /*Bits=*/32,
5124            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5125            LastIteration64.get(), SemaRef)))
5126     LastIteration = LastIteration32;
5127   QualType VType = LastIteration.get()->getType();
5128   QualType RealVType = VType;
5129   QualType StrideVType = VType;
5130   if (isOpenMPTaskLoopDirective(DKind)) {
5131     VType =
5132         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5133     StrideVType =
5134         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5135   }
5136 
5137   if (!LastIteration.isUsable())
5138     return 0;
5139 
5140   // Save the number of iterations.
5141   ExprResult NumIterations = LastIteration;
5142   {
5143     LastIteration = SemaRef.BuildBinOp(
5144         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5145         LastIteration.get(),
5146         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5147     if (!LastIteration.isUsable())
5148       return 0;
5149   }
5150 
5151   // Calculate the last iteration number beforehand instead of doing this on
5152   // each iteration. Do not do this if the number of iterations may be kfold-ed.
5153   llvm::APSInt Result;
5154   bool IsConstant =
5155       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5156   ExprResult CalcLastIteration;
5157   if (!IsConstant) {
5158     ExprResult SaveRef =
5159         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
5160     LastIteration = SaveRef;
5161 
5162     // Prepare SaveRef + 1.
5163     NumIterations = SemaRef.BuildBinOp(
5164         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
5165         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5166     if (!NumIterations.isUsable())
5167       return 0;
5168   }
5169 
5170   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5171 
5172   // Build variables passed into runtime, necessary for worksharing directives.
5173   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
5174   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5175       isOpenMPDistributeDirective(DKind)) {
5176     // Lower bound variable, initialized with zero.
5177     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5178     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
5179     SemaRef.AddInitializerToDecl(LBDecl,
5180                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5181                                  /*DirectInit*/ false);
5182 
5183     // Upper bound variable, initialized with last iteration number.
5184     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5185     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
5186     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
5187                                  /*DirectInit*/ false);
5188 
5189     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5190     // This will be used to implement clause 'lastprivate'.
5191     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
5192     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5193     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
5194     SemaRef.AddInitializerToDecl(ILDecl,
5195                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5196                                  /*DirectInit*/ false);
5197 
5198     // Stride variable returned by runtime (we initialize it to 1 by default).
5199     VarDecl *STDecl =
5200         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5201     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
5202     SemaRef.AddInitializerToDecl(STDecl,
5203                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5204                                  /*DirectInit*/ false);
5205 
5206     // Build expression: UB = min(UB, LastIteration)
5207     // It is necessary for CodeGen of directives with static scheduling.
5208     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5209                                                 UB.get(), LastIteration.get());
5210     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5211         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5212         LastIteration.get(), UB.get());
5213     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5214                              CondOp.get());
5215     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
5216 
5217     // If we have a combined directive that combines 'distribute', 'for' or
5218     // 'simd' we need to be able to access the bounds of the schedule of the
5219     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5220     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5221     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5222       // Lower bound variable, initialized with zero.
5223       VarDecl *CombLBDecl =
5224           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5225       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5226       SemaRef.AddInitializerToDecl(
5227           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5228           /*DirectInit*/ false);
5229 
5230       // Upper bound variable, initialized with last iteration number.
5231       VarDecl *CombUBDecl =
5232           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5233       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5234       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5235                                    /*DirectInit*/ false);
5236 
5237       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5238           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5239       ExprResult CombCondOp =
5240           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5241                                      LastIteration.get(), CombUB.get());
5242       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5243                                    CombCondOp.get());
5244       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
5245 
5246       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
5247       // We expect to have at least 2 more parameters than the 'parallel'
5248       // directive does - the lower and upper bounds of the previous schedule.
5249       assert(CD->getNumParams() >= 4 &&
5250              "Unexpected number of parameters in loop combined directive");
5251 
5252       // Set the proper type for the bounds given what we learned from the
5253       // enclosed loops.
5254       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5255       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
5256 
5257       // Previous lower and upper bounds are obtained from the region
5258       // parameters.
5259       PrevLB =
5260           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5261       PrevUB =
5262           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5263     }
5264   }
5265 
5266   // Build the iteration variable and its initialization before loop.
5267   ExprResult IV;
5268   ExprResult Init, CombInit;
5269   {
5270     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5271     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
5272     Expr *RHS =
5273         (isOpenMPWorksharingDirective(DKind) ||
5274          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5275             ? LB.get()
5276             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5277     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5278     Init = SemaRef.ActOnFinishFullExpr(Init.get());
5279 
5280     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5281       Expr *CombRHS =
5282           (isOpenMPWorksharingDirective(DKind) ||
5283            isOpenMPTaskLoopDirective(DKind) ||
5284            isOpenMPDistributeDirective(DKind))
5285               ? CombLB.get()
5286               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5287       CombInit =
5288           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
5289       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
5290     }
5291   }
5292 
5293   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
5294   SourceLocation CondLoc = AStmt->getBeginLoc();
5295   ExprResult Cond =
5296       (isOpenMPWorksharingDirective(DKind) ||
5297        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5298           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
5299           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5300                                NumIterations.get());
5301   ExprResult CombDistCond;
5302   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5303     CombDistCond =
5304         SemaRef.BuildBinOp(
5305             CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
5306   }
5307 
5308   ExprResult CombCond;
5309   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5310     CombCond =
5311         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
5312   }
5313   // Loop increment (IV = IV + 1)
5314   SourceLocation IncLoc = AStmt->getBeginLoc();
5315   ExprResult Inc =
5316       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5317                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5318   if (!Inc.isUsable())
5319     return 0;
5320   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5321   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
5322   if (!Inc.isUsable())
5323     return 0;
5324 
5325   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5326   // Used for directives with static scheduling.
5327   // In combined construct, add combined version that use CombLB and CombUB
5328   // base variables for the update
5329   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
5330   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5331       isOpenMPDistributeDirective(DKind)) {
5332     // LB + ST
5333     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5334     if (!NextLB.isUsable())
5335       return 0;
5336     // LB = LB + ST
5337     NextLB =
5338         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5339     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
5340     if (!NextLB.isUsable())
5341       return 0;
5342     // UB + ST
5343     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5344     if (!NextUB.isUsable())
5345       return 0;
5346     // UB = UB + ST
5347     NextUB =
5348         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5349     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
5350     if (!NextUB.isUsable())
5351       return 0;
5352     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5353       CombNextLB =
5354           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5355       if (!NextLB.isUsable())
5356         return 0;
5357       // LB = LB + ST
5358       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5359                                       CombNextLB.get());
5360       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
5361       if (!CombNextLB.isUsable())
5362         return 0;
5363       // UB + ST
5364       CombNextUB =
5365           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5366       if (!CombNextUB.isUsable())
5367         return 0;
5368       // UB = UB + ST
5369       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5370                                       CombNextUB.get());
5371       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
5372       if (!CombNextUB.isUsable())
5373         return 0;
5374     }
5375   }
5376 
5377   // Create increment expression for distribute loop when combined in a same
5378   // directive with for as IV = IV + ST; ensure upper bound expression based
5379   // on PrevUB instead of NumIterations - used to implement 'for' when found
5380   // in combination with 'distribute', like in 'distribute parallel for'
5381   SourceLocation DistIncLoc = AStmt->getBeginLoc();
5382   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
5383   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5384     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5385     assert(DistCond.isUsable() && "distribute cond expr was not built");
5386 
5387     DistInc =
5388         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5389     assert(DistInc.isUsable() && "distribute inc expr was not built");
5390     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5391                                  DistInc.get());
5392     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5393     assert(DistInc.isUsable() && "distribute inc expr was not built");
5394 
5395     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5396     // construct
5397     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
5398     ExprResult IsUBGreater =
5399         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5400     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5401         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5402     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5403                                  CondOp.get());
5404     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5405 
5406     // Build IV <= PrevUB to be used in parallel for is in combination with
5407     // a distribute directive with schedule(static, 1)
5408     ParForInDistCond =
5409         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
5410   }
5411 
5412   // Build updates and final values of the loop counters.
5413   bool HasErrors = false;
5414   Built.Counters.resize(NestedLoopCount);
5415   Built.Inits.resize(NestedLoopCount);
5416   Built.Updates.resize(NestedLoopCount);
5417   Built.Finals.resize(NestedLoopCount);
5418   {
5419     ExprResult Div;
5420     // Go from inner nested loop to outer.
5421     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5422       LoopIterationSpace &IS = IterSpaces[Cnt];
5423       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5424       // Build: Iter = (IV / Div) % IS.NumIters
5425       // where Div is product of previous iterations' IS.NumIters.
5426       ExprResult Iter;
5427       if (Div.isUsable()) {
5428         Iter =
5429             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5430       } else {
5431         Iter = IV;
5432         assert((Cnt == (int)NestedLoopCount - 1) &&
5433                "unusable div expected on first iteration only");
5434       }
5435 
5436       if (Cnt != 0 && Iter.isUsable())
5437         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5438                                   IS.NumIterations);
5439       if (!Iter.isUsable()) {
5440         HasErrors = true;
5441         break;
5442       }
5443 
5444       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5445       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5446       DeclRefExpr *CounterVar = buildDeclRefExpr(
5447           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5448           /*RefersToCapture=*/true);
5449       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5450                                          IS.CounterInit, Captures);
5451       if (!Init.isUsable()) {
5452         HasErrors = true;
5453         break;
5454       }
5455       ExprResult Update = buildCounterUpdate(
5456           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5457           IS.CounterStep, IS.Subtract, &Captures);
5458       if (!Update.isUsable()) {
5459         HasErrors = true;
5460         break;
5461       }
5462 
5463       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5464       ExprResult Final = buildCounterUpdate(
5465           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5466           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5467       if (!Final.isUsable()) {
5468         HasErrors = true;
5469         break;
5470       }
5471 
5472       // Build Div for the next iteration: Div <- Div * IS.NumIters
5473       if (Cnt != 0) {
5474         if (Div.isUnset())
5475           Div = IS.NumIterations;
5476         else
5477           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5478                                    IS.NumIterations);
5479 
5480         // Add parentheses (for debugging purposes only).
5481         if (Div.isUsable())
5482           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5483         if (!Div.isUsable()) {
5484           HasErrors = true;
5485           break;
5486         }
5487       }
5488       if (!Update.isUsable() || !Final.isUsable()) {
5489         HasErrors = true;
5490         break;
5491       }
5492       // Save results
5493       Built.Counters[Cnt] = IS.CounterVar;
5494       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5495       Built.Inits[Cnt] = Init.get();
5496       Built.Updates[Cnt] = Update.get();
5497       Built.Finals[Cnt] = Final.get();
5498     }
5499   }
5500 
5501   if (HasErrors)
5502     return 0;
5503 
5504   // Save results
5505   Built.IterationVarRef = IV.get();
5506   Built.LastIteration = LastIteration.get();
5507   Built.NumIterations = NumIterations.get();
5508   Built.CalcLastIteration =
5509       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
5510   Built.PreCond = PreCond.get();
5511   Built.PreInits = buildPreInits(C, Captures);
5512   Built.Cond = Cond.get();
5513   Built.Init = Init.get();
5514   Built.Inc = Inc.get();
5515   Built.LB = LB.get();
5516   Built.UB = UB.get();
5517   Built.IL = IL.get();
5518   Built.ST = ST.get();
5519   Built.EUB = EUB.get();
5520   Built.NLB = NextLB.get();
5521   Built.NUB = NextUB.get();
5522   Built.PrevLB = PrevLB.get();
5523   Built.PrevUB = PrevUB.get();
5524   Built.DistInc = DistInc.get();
5525   Built.PrevEUB = PrevEUB.get();
5526   Built.DistCombinedFields.LB = CombLB.get();
5527   Built.DistCombinedFields.UB = CombUB.get();
5528   Built.DistCombinedFields.EUB = CombEUB.get();
5529   Built.DistCombinedFields.Init = CombInit.get();
5530   Built.DistCombinedFields.Cond = CombCond.get();
5531   Built.DistCombinedFields.NLB = CombNextLB.get();
5532   Built.DistCombinedFields.NUB = CombNextUB.get();
5533   Built.DistCombinedFields.DistCond = CombDistCond.get();
5534   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
5535 
5536   return NestedLoopCount;
5537 }
5538 
5539 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5540   auto CollapseClauses =
5541       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5542   if (CollapseClauses.begin() != CollapseClauses.end())
5543     return (*CollapseClauses.begin())->getNumForLoops();
5544   return nullptr;
5545 }
5546 
5547 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5548   auto OrderedClauses =
5549       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5550   if (OrderedClauses.begin() != OrderedClauses.end())
5551     return (*OrderedClauses.begin())->getNumForLoops();
5552   return nullptr;
5553 }
5554 
5555 static bool checkSimdlenSafelenSpecified(Sema &S,
5556                                          const ArrayRef<OMPClause *> Clauses) {
5557   const OMPSafelenClause *Safelen = nullptr;
5558   const OMPSimdlenClause *Simdlen = nullptr;
5559 
5560   for (const OMPClause *Clause : Clauses) {
5561     if (Clause->getClauseKind() == OMPC_safelen)
5562       Safelen = cast<OMPSafelenClause>(Clause);
5563     else if (Clause->getClauseKind() == OMPC_simdlen)
5564       Simdlen = cast<OMPSimdlenClause>(Clause);
5565     if (Safelen && Simdlen)
5566       break;
5567   }
5568 
5569   if (Simdlen && Safelen) {
5570     llvm::APSInt SimdlenRes, SafelenRes;
5571     const Expr *SimdlenLength = Simdlen->getSimdlen();
5572     const Expr *SafelenLength = Safelen->getSafelen();
5573     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5574         SimdlenLength->isInstantiationDependent() ||
5575         SimdlenLength->containsUnexpandedParameterPack())
5576       return false;
5577     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5578         SafelenLength->isInstantiationDependent() ||
5579         SafelenLength->containsUnexpandedParameterPack())
5580       return false;
5581     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5582     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5583     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5584     // If both simdlen and safelen clauses are specified, the value of the
5585     // simdlen parameter must be less than or equal to the value of the safelen
5586     // parameter.
5587     if (SimdlenRes > SafelenRes) {
5588       S.Diag(SimdlenLength->getExprLoc(),
5589              diag::err_omp_wrong_simdlen_safelen_values)
5590           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5591       return true;
5592     }
5593   }
5594   return false;
5595 }
5596 
5597 StmtResult
5598 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5599                                SourceLocation StartLoc, SourceLocation EndLoc,
5600                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5601   if (!AStmt)
5602     return StmtError();
5603 
5604   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5605   OMPLoopDirective::HelperExprs B;
5606   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5607   // define the nested loops number.
5608   unsigned NestedLoopCount = checkOpenMPLoop(
5609       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5610       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5611   if (NestedLoopCount == 0)
5612     return StmtError();
5613 
5614   assert((CurContext->isDependentContext() || B.builtAll()) &&
5615          "omp simd loop exprs were not built");
5616 
5617   if (!CurContext->isDependentContext()) {
5618     // Finalize the clauses that need pre-built expressions for CodeGen.
5619     for (OMPClause *C : Clauses) {
5620       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5621         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5622                                      B.NumIterations, *this, CurScope,
5623                                      DSAStack))
5624           return StmtError();
5625     }
5626   }
5627 
5628   if (checkSimdlenSafelenSpecified(*this, Clauses))
5629     return StmtError();
5630 
5631   setFunctionHasBranchProtectedScope();
5632   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5633                                   Clauses, AStmt, B);
5634 }
5635 
5636 StmtResult
5637 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5638                               SourceLocation StartLoc, SourceLocation EndLoc,
5639                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5640   if (!AStmt)
5641     return StmtError();
5642 
5643   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5644   OMPLoopDirective::HelperExprs B;
5645   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5646   // define the nested loops number.
5647   unsigned NestedLoopCount = checkOpenMPLoop(
5648       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5649       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5650   if (NestedLoopCount == 0)
5651     return StmtError();
5652 
5653   assert((CurContext->isDependentContext() || B.builtAll()) &&
5654          "omp for loop exprs were not built");
5655 
5656   if (!CurContext->isDependentContext()) {
5657     // Finalize the clauses that need pre-built expressions for CodeGen.
5658     for (OMPClause *C : Clauses) {
5659       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5660         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5661                                      B.NumIterations, *this, CurScope,
5662                                      DSAStack))
5663           return StmtError();
5664     }
5665   }
5666 
5667   setFunctionHasBranchProtectedScope();
5668   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5669                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5670 }
5671 
5672 StmtResult Sema::ActOnOpenMPForSimdDirective(
5673     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5674     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5675   if (!AStmt)
5676     return StmtError();
5677 
5678   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5679   OMPLoopDirective::HelperExprs B;
5680   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5681   // define the nested loops number.
5682   unsigned NestedLoopCount =
5683       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5684                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5685                       VarsWithImplicitDSA, B);
5686   if (NestedLoopCount == 0)
5687     return StmtError();
5688 
5689   assert((CurContext->isDependentContext() || B.builtAll()) &&
5690          "omp for simd loop exprs were not built");
5691 
5692   if (!CurContext->isDependentContext()) {
5693     // Finalize the clauses that need pre-built expressions for CodeGen.
5694     for (OMPClause *C : Clauses) {
5695       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5696         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5697                                      B.NumIterations, *this, CurScope,
5698                                      DSAStack))
5699           return StmtError();
5700     }
5701   }
5702 
5703   if (checkSimdlenSafelenSpecified(*this, Clauses))
5704     return StmtError();
5705 
5706   setFunctionHasBranchProtectedScope();
5707   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5708                                      Clauses, AStmt, B);
5709 }
5710 
5711 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5712                                               Stmt *AStmt,
5713                                               SourceLocation StartLoc,
5714                                               SourceLocation EndLoc) {
5715   if (!AStmt)
5716     return StmtError();
5717 
5718   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5719   auto BaseStmt = AStmt;
5720   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5721     BaseStmt = CS->getCapturedStmt();
5722   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5723     auto S = C->children();
5724     if (S.begin() == S.end())
5725       return StmtError();
5726     // All associated statements must be '#pragma omp section' except for
5727     // the first one.
5728     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5729       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5730         if (SectionStmt)
5731           Diag(SectionStmt->getBeginLoc(),
5732                diag::err_omp_sections_substmt_not_section);
5733         return StmtError();
5734       }
5735       cast<OMPSectionDirective>(SectionStmt)
5736           ->setHasCancel(DSAStack->isCancelRegion());
5737     }
5738   } else {
5739     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
5740     return StmtError();
5741   }
5742 
5743   setFunctionHasBranchProtectedScope();
5744 
5745   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5746                                       DSAStack->isCancelRegion());
5747 }
5748 
5749 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5750                                              SourceLocation StartLoc,
5751                                              SourceLocation EndLoc) {
5752   if (!AStmt)
5753     return StmtError();
5754 
5755   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5756 
5757   setFunctionHasBranchProtectedScope();
5758   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5759 
5760   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5761                                      DSAStack->isCancelRegion());
5762 }
5763 
5764 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5765                                             Stmt *AStmt,
5766                                             SourceLocation StartLoc,
5767                                             SourceLocation EndLoc) {
5768   if (!AStmt)
5769     return StmtError();
5770 
5771   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5772 
5773   setFunctionHasBranchProtectedScope();
5774 
5775   // OpenMP [2.7.3, single Construct, Restrictions]
5776   // The copyprivate clause must not be used with the nowait clause.
5777   const OMPClause *Nowait = nullptr;
5778   const OMPClause *Copyprivate = nullptr;
5779   for (const OMPClause *Clause : Clauses) {
5780     if (Clause->getClauseKind() == OMPC_nowait)
5781       Nowait = Clause;
5782     else if (Clause->getClauseKind() == OMPC_copyprivate)
5783       Copyprivate = Clause;
5784     if (Copyprivate && Nowait) {
5785       Diag(Copyprivate->getBeginLoc(),
5786            diag::err_omp_single_copyprivate_with_nowait);
5787       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
5788       return StmtError();
5789     }
5790   }
5791 
5792   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5793 }
5794 
5795 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5796                                             SourceLocation StartLoc,
5797                                             SourceLocation EndLoc) {
5798   if (!AStmt)
5799     return StmtError();
5800 
5801   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5802 
5803   setFunctionHasBranchProtectedScope();
5804 
5805   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5806 }
5807 
5808 StmtResult Sema::ActOnOpenMPCriticalDirective(
5809     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5810     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5811   if (!AStmt)
5812     return StmtError();
5813 
5814   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5815 
5816   bool ErrorFound = false;
5817   llvm::APSInt Hint;
5818   SourceLocation HintLoc;
5819   bool DependentHint = false;
5820   for (const OMPClause *C : Clauses) {
5821     if (C->getClauseKind() == OMPC_hint) {
5822       if (!DirName.getName()) {
5823         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
5824         ErrorFound = true;
5825       }
5826       Expr *E = cast<OMPHintClause>(C)->getHint();
5827       if (E->isTypeDependent() || E->isValueDependent() ||
5828           E->isInstantiationDependent()) {
5829         DependentHint = true;
5830       } else {
5831         Hint = E->EvaluateKnownConstInt(Context);
5832         HintLoc = C->getBeginLoc();
5833       }
5834     }
5835   }
5836   if (ErrorFound)
5837     return StmtError();
5838   const auto Pair = DSAStack->getCriticalWithHint(DirName);
5839   if (Pair.first && DirName.getName() && !DependentHint) {
5840     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5841       Diag(StartLoc, diag::err_omp_critical_with_hint);
5842       if (HintLoc.isValid())
5843         Diag(HintLoc, diag::note_omp_critical_hint_here)
5844             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5845       else
5846         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5847       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5848         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
5849             << 1
5850             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5851                    /*Radix=*/10, /*Signed=*/false);
5852       } else {
5853         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
5854       }
5855     }
5856   }
5857 
5858   setFunctionHasBranchProtectedScope();
5859 
5860   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5861                                            Clauses, AStmt);
5862   if (!Pair.first && DirName.getName() && !DependentHint)
5863     DSAStack->addCriticalWithHint(Dir, Hint);
5864   return Dir;
5865 }
5866 
5867 StmtResult Sema::ActOnOpenMPParallelForDirective(
5868     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5869     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5870   if (!AStmt)
5871     return StmtError();
5872 
5873   auto *CS = cast<CapturedStmt>(AStmt);
5874   // 1.2.2 OpenMP Language Terminology
5875   // Structured block - An executable statement with a single entry at the
5876   // top and a single exit at the bottom.
5877   // The point of exit cannot be a branch out of the structured block.
5878   // longjmp() and throw() must not violate the entry/exit criteria.
5879   CS->getCapturedDecl()->setNothrow();
5880 
5881   OMPLoopDirective::HelperExprs B;
5882   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5883   // define the nested loops number.
5884   unsigned NestedLoopCount =
5885       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5886                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5887                       VarsWithImplicitDSA, B);
5888   if (NestedLoopCount == 0)
5889     return StmtError();
5890 
5891   assert((CurContext->isDependentContext() || B.builtAll()) &&
5892          "omp parallel for loop exprs were not built");
5893 
5894   if (!CurContext->isDependentContext()) {
5895     // Finalize the clauses that need pre-built expressions for CodeGen.
5896     for (OMPClause *C : Clauses) {
5897       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5898         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5899                                      B.NumIterations, *this, CurScope,
5900                                      DSAStack))
5901           return StmtError();
5902     }
5903   }
5904 
5905   setFunctionHasBranchProtectedScope();
5906   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5907                                          NestedLoopCount, Clauses, AStmt, B,
5908                                          DSAStack->isCancelRegion());
5909 }
5910 
5911 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5912     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5913     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5914   if (!AStmt)
5915     return StmtError();
5916 
5917   auto *CS = cast<CapturedStmt>(AStmt);
5918   // 1.2.2 OpenMP Language Terminology
5919   // Structured block - An executable statement with a single entry at the
5920   // top and a single exit at the bottom.
5921   // The point of exit cannot be a branch out of the structured block.
5922   // longjmp() and throw() must not violate the entry/exit criteria.
5923   CS->getCapturedDecl()->setNothrow();
5924 
5925   OMPLoopDirective::HelperExprs B;
5926   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5927   // define the nested loops number.
5928   unsigned NestedLoopCount =
5929       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5930                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5931                       VarsWithImplicitDSA, B);
5932   if (NestedLoopCount == 0)
5933     return StmtError();
5934 
5935   if (!CurContext->isDependentContext()) {
5936     // Finalize the clauses that need pre-built expressions for CodeGen.
5937     for (OMPClause *C : Clauses) {
5938       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5939         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5940                                      B.NumIterations, *this, CurScope,
5941                                      DSAStack))
5942           return StmtError();
5943     }
5944   }
5945 
5946   if (checkSimdlenSafelenSpecified(*this, Clauses))
5947     return StmtError();
5948 
5949   setFunctionHasBranchProtectedScope();
5950   return OMPParallelForSimdDirective::Create(
5951       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5952 }
5953 
5954 StmtResult
5955 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5956                                            Stmt *AStmt, SourceLocation StartLoc,
5957                                            SourceLocation EndLoc) {
5958   if (!AStmt)
5959     return StmtError();
5960 
5961   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5962   auto BaseStmt = AStmt;
5963   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5964     BaseStmt = CS->getCapturedStmt();
5965   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5966     auto S = C->children();
5967     if (S.begin() == S.end())
5968       return StmtError();
5969     // All associated statements must be '#pragma omp section' except for
5970     // the first one.
5971     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5972       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5973         if (SectionStmt)
5974           Diag(SectionStmt->getBeginLoc(),
5975                diag::err_omp_parallel_sections_substmt_not_section);
5976         return StmtError();
5977       }
5978       cast<OMPSectionDirective>(SectionStmt)
5979           ->setHasCancel(DSAStack->isCancelRegion());
5980     }
5981   } else {
5982     Diag(AStmt->getBeginLoc(),
5983          diag::err_omp_parallel_sections_not_compound_stmt);
5984     return StmtError();
5985   }
5986 
5987   setFunctionHasBranchProtectedScope();
5988 
5989   return OMPParallelSectionsDirective::Create(
5990       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5991 }
5992 
5993 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5994                                           Stmt *AStmt, SourceLocation StartLoc,
5995                                           SourceLocation EndLoc) {
5996   if (!AStmt)
5997     return StmtError();
5998 
5999   auto *CS = cast<CapturedStmt>(AStmt);
6000   // 1.2.2 OpenMP Language Terminology
6001   // Structured block - An executable statement with a single entry at the
6002   // top and a single exit at the bottom.
6003   // The point of exit cannot be a branch out of the structured block.
6004   // longjmp() and throw() must not violate the entry/exit criteria.
6005   CS->getCapturedDecl()->setNothrow();
6006 
6007   setFunctionHasBranchProtectedScope();
6008 
6009   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6010                                   DSAStack->isCancelRegion());
6011 }
6012 
6013 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6014                                                SourceLocation EndLoc) {
6015   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6016 }
6017 
6018 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6019                                              SourceLocation EndLoc) {
6020   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6021 }
6022 
6023 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6024                                               SourceLocation EndLoc) {
6025   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6026 }
6027 
6028 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6029                                                Stmt *AStmt,
6030                                                SourceLocation StartLoc,
6031                                                SourceLocation EndLoc) {
6032   if (!AStmt)
6033     return StmtError();
6034 
6035   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6036 
6037   setFunctionHasBranchProtectedScope();
6038 
6039   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
6040                                        AStmt,
6041                                        DSAStack->getTaskgroupReductionRef());
6042 }
6043 
6044 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6045                                            SourceLocation StartLoc,
6046                                            SourceLocation EndLoc) {
6047   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6048   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6049 }
6050 
6051 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6052                                              Stmt *AStmt,
6053                                              SourceLocation StartLoc,
6054                                              SourceLocation EndLoc) {
6055   const OMPClause *DependFound = nullptr;
6056   const OMPClause *DependSourceClause = nullptr;
6057   const OMPClause *DependSinkClause = nullptr;
6058   bool ErrorFound = false;
6059   const OMPThreadsClause *TC = nullptr;
6060   const OMPSIMDClause *SC = nullptr;
6061   for (const OMPClause *C : Clauses) {
6062     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6063       DependFound = C;
6064       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6065         if (DependSourceClause) {
6066           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
6067               << getOpenMPDirectiveName(OMPD_ordered)
6068               << getOpenMPClauseName(OMPC_depend) << 2;
6069           ErrorFound = true;
6070         } else {
6071           DependSourceClause = C;
6072         }
6073         if (DependSinkClause) {
6074           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6075               << 0;
6076           ErrorFound = true;
6077         }
6078       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6079         if (DependSourceClause) {
6080           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6081               << 1;
6082           ErrorFound = true;
6083         }
6084         DependSinkClause = C;
6085       }
6086     } else if (C->getClauseKind() == OMPC_threads) {
6087       TC = cast<OMPThreadsClause>(C);
6088     } else if (C->getClauseKind() == OMPC_simd) {
6089       SC = cast<OMPSIMDClause>(C);
6090     }
6091   }
6092   if (!ErrorFound && !SC &&
6093       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
6094     // OpenMP [2.8.1,simd Construct, Restrictions]
6095     // An ordered construct with the simd clause is the only OpenMP construct
6096     // that can appear in the simd region.
6097     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
6098     ErrorFound = true;
6099   } else if (DependFound && (TC || SC)) {
6100     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
6101         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6102     ErrorFound = true;
6103   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
6104     Diag(DependFound->getBeginLoc(),
6105          diag::err_omp_ordered_directive_without_param);
6106     ErrorFound = true;
6107   } else if (TC || Clauses.empty()) {
6108     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
6109       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
6110       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6111           << (TC != nullptr);
6112       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
6113       ErrorFound = true;
6114     }
6115   }
6116   if ((!AStmt && !DependFound) || ErrorFound)
6117     return StmtError();
6118 
6119   if (AStmt) {
6120     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6121 
6122     setFunctionHasBranchProtectedScope();
6123   }
6124 
6125   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6126 }
6127 
6128 namespace {
6129 /// Helper class for checking expression in 'omp atomic [update]'
6130 /// construct.
6131 class OpenMPAtomicUpdateChecker {
6132   /// Error results for atomic update expressions.
6133   enum ExprAnalysisErrorCode {
6134     /// A statement is not an expression statement.
6135     NotAnExpression,
6136     /// Expression is not builtin binary or unary operation.
6137     NotABinaryOrUnaryExpression,
6138     /// Unary operation is not post-/pre- increment/decrement operation.
6139     NotAnUnaryIncDecExpression,
6140     /// An expression is not of scalar type.
6141     NotAScalarType,
6142     /// A binary operation is not an assignment operation.
6143     NotAnAssignmentOp,
6144     /// RHS part of the binary operation is not a binary expression.
6145     NotABinaryExpression,
6146     /// RHS part is not additive/multiplicative/shift/biwise binary
6147     /// expression.
6148     NotABinaryOperator,
6149     /// RHS binary operation does not have reference to the updated LHS
6150     /// part.
6151     NotAnUpdateExpression,
6152     /// No errors is found.
6153     NoError
6154   };
6155   /// Reference to Sema.
6156   Sema &SemaRef;
6157   /// A location for note diagnostics (when error is found).
6158   SourceLocation NoteLoc;
6159   /// 'x' lvalue part of the source atomic expression.
6160   Expr *X;
6161   /// 'expr' rvalue part of the source atomic expression.
6162   Expr *E;
6163   /// Helper expression of the form
6164   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6165   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6166   Expr *UpdateExpr;
6167   /// Is 'x' a LHS in a RHS part of full update expression. It is
6168   /// important for non-associative operations.
6169   bool IsXLHSInRHSPart;
6170   BinaryOperatorKind Op;
6171   SourceLocation OpLoc;
6172   /// true if the source expression is a postfix unary operation, false
6173   /// if it is a prefix unary operation.
6174   bool IsPostfixUpdate;
6175 
6176 public:
6177   OpenMPAtomicUpdateChecker(Sema &SemaRef)
6178       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
6179         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
6180   /// Check specified statement that it is suitable for 'atomic update'
6181   /// constructs and extract 'x', 'expr' and Operation from the original
6182   /// expression. If DiagId and NoteId == 0, then only check is performed
6183   /// without error notification.
6184   /// \param DiagId Diagnostic which should be emitted if error is found.
6185   /// \param NoteId Diagnostic note for the main error message.
6186   /// \return true if statement is not an update expression, false otherwise.
6187   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
6188   /// Return the 'x' lvalue part of the source atomic expression.
6189   Expr *getX() const { return X; }
6190   /// Return the 'expr' rvalue part of the source atomic expression.
6191   Expr *getExpr() const { return E; }
6192   /// Return the update expression used in calculation of the updated
6193   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6194   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6195   Expr *getUpdateExpr() const { return UpdateExpr; }
6196   /// Return true if 'x' is LHS in RHS part of full update expression,
6197   /// false otherwise.
6198   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6199 
6200   /// true if the source expression is a postfix unary operation, false
6201   /// if it is a prefix unary operation.
6202   bool isPostfixUpdate() const { return IsPostfixUpdate; }
6203 
6204 private:
6205   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6206                             unsigned NoteId = 0);
6207 };
6208 } // namespace
6209 
6210 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6211     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6212   ExprAnalysisErrorCode ErrorFound = NoError;
6213   SourceLocation ErrorLoc, NoteLoc;
6214   SourceRange ErrorRange, NoteRange;
6215   // Allowed constructs are:
6216   //  x = x binop expr;
6217   //  x = expr binop x;
6218   if (AtomicBinOp->getOpcode() == BO_Assign) {
6219     X = AtomicBinOp->getLHS();
6220     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
6221             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6222       if (AtomicInnerBinOp->isMultiplicativeOp() ||
6223           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6224           AtomicInnerBinOp->isBitwiseOp()) {
6225         Op = AtomicInnerBinOp->getOpcode();
6226         OpLoc = AtomicInnerBinOp->getOperatorLoc();
6227         Expr *LHS = AtomicInnerBinOp->getLHS();
6228         Expr *RHS = AtomicInnerBinOp->getRHS();
6229         llvm::FoldingSetNodeID XId, LHSId, RHSId;
6230         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6231                                           /*Canonical=*/true);
6232         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6233                                             /*Canonical=*/true);
6234         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6235                                             /*Canonical=*/true);
6236         if (XId == LHSId) {
6237           E = RHS;
6238           IsXLHSInRHSPart = true;
6239         } else if (XId == RHSId) {
6240           E = LHS;
6241           IsXLHSInRHSPart = false;
6242         } else {
6243           ErrorLoc = AtomicInnerBinOp->getExprLoc();
6244           ErrorRange = AtomicInnerBinOp->getSourceRange();
6245           NoteLoc = X->getExprLoc();
6246           NoteRange = X->getSourceRange();
6247           ErrorFound = NotAnUpdateExpression;
6248         }
6249       } else {
6250         ErrorLoc = AtomicInnerBinOp->getExprLoc();
6251         ErrorRange = AtomicInnerBinOp->getSourceRange();
6252         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6253         NoteRange = SourceRange(NoteLoc, NoteLoc);
6254         ErrorFound = NotABinaryOperator;
6255       }
6256     } else {
6257       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6258       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6259       ErrorFound = NotABinaryExpression;
6260     }
6261   } else {
6262     ErrorLoc = AtomicBinOp->getExprLoc();
6263     ErrorRange = AtomicBinOp->getSourceRange();
6264     NoteLoc = AtomicBinOp->getOperatorLoc();
6265     NoteRange = SourceRange(NoteLoc, NoteLoc);
6266     ErrorFound = NotAnAssignmentOp;
6267   }
6268   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6269     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6270     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6271     return true;
6272   }
6273   if (SemaRef.CurContext->isDependentContext())
6274     E = X = UpdateExpr = nullptr;
6275   return ErrorFound != NoError;
6276 }
6277 
6278 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6279                                                unsigned NoteId) {
6280   ExprAnalysisErrorCode ErrorFound = NoError;
6281   SourceLocation ErrorLoc, NoteLoc;
6282   SourceRange ErrorRange, NoteRange;
6283   // Allowed constructs are:
6284   //  x++;
6285   //  x--;
6286   //  ++x;
6287   //  --x;
6288   //  x binop= expr;
6289   //  x = x binop expr;
6290   //  x = expr binop x;
6291   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6292     AtomicBody = AtomicBody->IgnoreParenImpCasts();
6293     if (AtomicBody->getType()->isScalarType() ||
6294         AtomicBody->isInstantiationDependent()) {
6295       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6296               AtomicBody->IgnoreParenImpCasts())) {
6297         // Check for Compound Assignment Operation
6298         Op = BinaryOperator::getOpForCompoundAssignment(
6299             AtomicCompAssignOp->getOpcode());
6300         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6301         E = AtomicCompAssignOp->getRHS();
6302         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
6303         IsXLHSInRHSPart = true;
6304       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6305                      AtomicBody->IgnoreParenImpCasts())) {
6306         // Check for Binary Operation
6307         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6308           return true;
6309       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6310                      AtomicBody->IgnoreParenImpCasts())) {
6311         // Check for Unary Operation
6312         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6313           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6314           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6315           OpLoc = AtomicUnaryOp->getOperatorLoc();
6316           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
6317           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6318           IsXLHSInRHSPart = true;
6319         } else {
6320           ErrorFound = NotAnUnaryIncDecExpression;
6321           ErrorLoc = AtomicUnaryOp->getExprLoc();
6322           ErrorRange = AtomicUnaryOp->getSourceRange();
6323           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6324           NoteRange = SourceRange(NoteLoc, NoteLoc);
6325         }
6326       } else if (!AtomicBody->isInstantiationDependent()) {
6327         ErrorFound = NotABinaryOrUnaryExpression;
6328         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6329         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6330       }
6331     } else {
6332       ErrorFound = NotAScalarType;
6333       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
6334       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6335     }
6336   } else {
6337     ErrorFound = NotAnExpression;
6338     NoteLoc = ErrorLoc = S->getBeginLoc();
6339     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6340   }
6341   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6342     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6343     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6344     return true;
6345   }
6346   if (SemaRef.CurContext->isDependentContext())
6347     E = X = UpdateExpr = nullptr;
6348   if (ErrorFound == NoError && E && X) {
6349     // Build an update expression of form 'OpaqueValueExpr(x) binop
6350     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6351     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6352     auto *OVEX = new (SemaRef.getASTContext())
6353         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6354     auto *OVEExpr = new (SemaRef.getASTContext())
6355         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6356     ExprResult Update =
6357         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6358                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6359     if (Update.isInvalid())
6360       return true;
6361     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6362                                                Sema::AA_Casting);
6363     if (Update.isInvalid())
6364       return true;
6365     UpdateExpr = Update.get();
6366   }
6367   return ErrorFound != NoError;
6368 }
6369 
6370 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6371                                             Stmt *AStmt,
6372                                             SourceLocation StartLoc,
6373                                             SourceLocation EndLoc) {
6374   if (!AStmt)
6375     return StmtError();
6376 
6377   auto *CS = cast<CapturedStmt>(AStmt);
6378   // 1.2.2 OpenMP Language Terminology
6379   // Structured block - An executable statement with a single entry at the
6380   // top and a single exit at the bottom.
6381   // The point of exit cannot be a branch out of the structured block.
6382   // longjmp() and throw() must not violate the entry/exit criteria.
6383   OpenMPClauseKind AtomicKind = OMPC_unknown;
6384   SourceLocation AtomicKindLoc;
6385   for (const OMPClause *C : Clauses) {
6386     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6387         C->getClauseKind() == OMPC_update ||
6388         C->getClauseKind() == OMPC_capture) {
6389       if (AtomicKind != OMPC_unknown) {
6390         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
6391             << SourceRange(C->getBeginLoc(), C->getEndLoc());
6392         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6393             << getOpenMPClauseName(AtomicKind);
6394       } else {
6395         AtomicKind = C->getClauseKind();
6396         AtomicKindLoc = C->getBeginLoc();
6397       }
6398     }
6399   }
6400 
6401   Stmt *Body = CS->getCapturedStmt();
6402   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6403     Body = EWC->getSubExpr();
6404 
6405   Expr *X = nullptr;
6406   Expr *V = nullptr;
6407   Expr *E = nullptr;
6408   Expr *UE = nullptr;
6409   bool IsXLHSInRHSPart = false;
6410   bool IsPostfixUpdate = false;
6411   // OpenMP [2.12.6, atomic Construct]
6412   // In the next expressions:
6413   // * x and v (as applicable) are both l-value expressions with scalar type.
6414   // * During the execution of an atomic region, multiple syntactic
6415   // occurrences of x must designate the same storage location.
6416   // * Neither of v and expr (as applicable) may access the storage location
6417   // designated by x.
6418   // * Neither of x and expr (as applicable) may access the storage location
6419   // designated by v.
6420   // * expr is an expression with scalar type.
6421   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6422   // * binop, binop=, ++, and -- are not overloaded operators.
6423   // * The expression x binop expr must be numerically equivalent to x binop
6424   // (expr). This requirement is satisfied if the operators in expr have
6425   // precedence greater than binop, or by using parentheses around expr or
6426   // subexpressions of expr.
6427   // * The expression expr binop x must be numerically equivalent to (expr)
6428   // binop x. This requirement is satisfied if the operators in expr have
6429   // precedence equal to or greater than binop, or by using parentheses around
6430   // expr or subexpressions of expr.
6431   // * For forms that allow multiple occurrences of x, the number of times
6432   // that x is evaluated is unspecified.
6433   if (AtomicKind == OMPC_read) {
6434     enum {
6435       NotAnExpression,
6436       NotAnAssignmentOp,
6437       NotAScalarType,
6438       NotAnLValue,
6439       NoError
6440     } ErrorFound = NoError;
6441     SourceLocation ErrorLoc, NoteLoc;
6442     SourceRange ErrorRange, NoteRange;
6443     // If clause is read:
6444     //  v = x;
6445     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6446       const auto *AtomicBinOp =
6447           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6448       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6449         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6450         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6451         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6452             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6453           if (!X->isLValue() || !V->isLValue()) {
6454             const Expr *NotLValueExpr = X->isLValue() ? V : X;
6455             ErrorFound = NotAnLValue;
6456             ErrorLoc = AtomicBinOp->getExprLoc();
6457             ErrorRange = AtomicBinOp->getSourceRange();
6458             NoteLoc = NotLValueExpr->getExprLoc();
6459             NoteRange = NotLValueExpr->getSourceRange();
6460           }
6461         } else if (!X->isInstantiationDependent() ||
6462                    !V->isInstantiationDependent()) {
6463           const Expr *NotScalarExpr =
6464               (X->isInstantiationDependent() || X->getType()->isScalarType())
6465                   ? V
6466                   : X;
6467           ErrorFound = NotAScalarType;
6468           ErrorLoc = AtomicBinOp->getExprLoc();
6469           ErrorRange = AtomicBinOp->getSourceRange();
6470           NoteLoc = NotScalarExpr->getExprLoc();
6471           NoteRange = NotScalarExpr->getSourceRange();
6472         }
6473       } else if (!AtomicBody->isInstantiationDependent()) {
6474         ErrorFound = NotAnAssignmentOp;
6475         ErrorLoc = AtomicBody->getExprLoc();
6476         ErrorRange = AtomicBody->getSourceRange();
6477         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6478                               : AtomicBody->getExprLoc();
6479         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6480                                 : AtomicBody->getSourceRange();
6481       }
6482     } else {
6483       ErrorFound = NotAnExpression;
6484       NoteLoc = ErrorLoc = Body->getBeginLoc();
6485       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6486     }
6487     if (ErrorFound != NoError) {
6488       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6489           << ErrorRange;
6490       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6491                                                       << NoteRange;
6492       return StmtError();
6493     }
6494     if (CurContext->isDependentContext())
6495       V = X = nullptr;
6496   } else if (AtomicKind == OMPC_write) {
6497     enum {
6498       NotAnExpression,
6499       NotAnAssignmentOp,
6500       NotAScalarType,
6501       NotAnLValue,
6502       NoError
6503     } ErrorFound = NoError;
6504     SourceLocation ErrorLoc, NoteLoc;
6505     SourceRange ErrorRange, NoteRange;
6506     // If clause is write:
6507     //  x = expr;
6508     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6509       const auto *AtomicBinOp =
6510           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6511       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6512         X = AtomicBinOp->getLHS();
6513         E = AtomicBinOp->getRHS();
6514         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6515             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6516           if (!X->isLValue()) {
6517             ErrorFound = NotAnLValue;
6518             ErrorLoc = AtomicBinOp->getExprLoc();
6519             ErrorRange = AtomicBinOp->getSourceRange();
6520             NoteLoc = X->getExprLoc();
6521             NoteRange = X->getSourceRange();
6522           }
6523         } else if (!X->isInstantiationDependent() ||
6524                    !E->isInstantiationDependent()) {
6525           const Expr *NotScalarExpr =
6526               (X->isInstantiationDependent() || X->getType()->isScalarType())
6527                   ? E
6528                   : X;
6529           ErrorFound = NotAScalarType;
6530           ErrorLoc = AtomicBinOp->getExprLoc();
6531           ErrorRange = AtomicBinOp->getSourceRange();
6532           NoteLoc = NotScalarExpr->getExprLoc();
6533           NoteRange = NotScalarExpr->getSourceRange();
6534         }
6535       } else if (!AtomicBody->isInstantiationDependent()) {
6536         ErrorFound = NotAnAssignmentOp;
6537         ErrorLoc = AtomicBody->getExprLoc();
6538         ErrorRange = AtomicBody->getSourceRange();
6539         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6540                               : AtomicBody->getExprLoc();
6541         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6542                                 : AtomicBody->getSourceRange();
6543       }
6544     } else {
6545       ErrorFound = NotAnExpression;
6546       NoteLoc = ErrorLoc = Body->getBeginLoc();
6547       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6548     }
6549     if (ErrorFound != NoError) {
6550       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6551           << ErrorRange;
6552       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6553                                                       << NoteRange;
6554       return StmtError();
6555     }
6556     if (CurContext->isDependentContext())
6557       E = X = nullptr;
6558   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6559     // If clause is update:
6560     //  x++;
6561     //  x--;
6562     //  ++x;
6563     //  --x;
6564     //  x binop= expr;
6565     //  x = x binop expr;
6566     //  x = expr binop x;
6567     OpenMPAtomicUpdateChecker Checker(*this);
6568     if (Checker.checkStatement(
6569             Body, (AtomicKind == OMPC_update)
6570                       ? diag::err_omp_atomic_update_not_expression_statement
6571                       : diag::err_omp_atomic_not_expression_statement,
6572             diag::note_omp_atomic_update))
6573       return StmtError();
6574     if (!CurContext->isDependentContext()) {
6575       E = Checker.getExpr();
6576       X = Checker.getX();
6577       UE = Checker.getUpdateExpr();
6578       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6579     }
6580   } else if (AtomicKind == OMPC_capture) {
6581     enum {
6582       NotAnAssignmentOp,
6583       NotACompoundStatement,
6584       NotTwoSubstatements,
6585       NotASpecificExpression,
6586       NoError
6587     } ErrorFound = NoError;
6588     SourceLocation ErrorLoc, NoteLoc;
6589     SourceRange ErrorRange, NoteRange;
6590     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6591       // If clause is a capture:
6592       //  v = x++;
6593       //  v = x--;
6594       //  v = ++x;
6595       //  v = --x;
6596       //  v = x binop= expr;
6597       //  v = x = x binop expr;
6598       //  v = x = expr binop x;
6599       const auto *AtomicBinOp =
6600           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6601       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6602         V = AtomicBinOp->getLHS();
6603         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6604         OpenMPAtomicUpdateChecker Checker(*this);
6605         if (Checker.checkStatement(
6606                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6607                 diag::note_omp_atomic_update))
6608           return StmtError();
6609         E = Checker.getExpr();
6610         X = Checker.getX();
6611         UE = Checker.getUpdateExpr();
6612         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6613         IsPostfixUpdate = Checker.isPostfixUpdate();
6614       } else if (!AtomicBody->isInstantiationDependent()) {
6615         ErrorLoc = AtomicBody->getExprLoc();
6616         ErrorRange = AtomicBody->getSourceRange();
6617         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6618                               : AtomicBody->getExprLoc();
6619         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6620                                 : AtomicBody->getSourceRange();
6621         ErrorFound = NotAnAssignmentOp;
6622       }
6623       if (ErrorFound != NoError) {
6624         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6625             << ErrorRange;
6626         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6627         return StmtError();
6628       }
6629       if (CurContext->isDependentContext())
6630         UE = V = E = X = nullptr;
6631     } else {
6632       // If clause is a capture:
6633       //  { v = x; x = expr; }
6634       //  { v = x; x++; }
6635       //  { v = x; x--; }
6636       //  { v = x; ++x; }
6637       //  { v = x; --x; }
6638       //  { v = x; x binop= expr; }
6639       //  { v = x; x = x binop expr; }
6640       //  { v = x; x = expr binop x; }
6641       //  { x++; v = x; }
6642       //  { x--; v = x; }
6643       //  { ++x; v = x; }
6644       //  { --x; v = x; }
6645       //  { x binop= expr; v = x; }
6646       //  { x = x binop expr; v = x; }
6647       //  { x = expr binop x; v = x; }
6648       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6649         // Check that this is { expr1; expr2; }
6650         if (CS->size() == 2) {
6651           Stmt *First = CS->body_front();
6652           Stmt *Second = CS->body_back();
6653           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6654             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6655           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6656             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6657           // Need to find what subexpression is 'v' and what is 'x'.
6658           OpenMPAtomicUpdateChecker Checker(*this);
6659           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6660           BinaryOperator *BinOp = nullptr;
6661           if (IsUpdateExprFound) {
6662             BinOp = dyn_cast<BinaryOperator>(First);
6663             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6664           }
6665           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6666             //  { v = x; x++; }
6667             //  { v = x; x--; }
6668             //  { v = x; ++x; }
6669             //  { v = x; --x; }
6670             //  { v = x; x binop= expr; }
6671             //  { v = x; x = x binop expr; }
6672             //  { v = x; x = expr binop x; }
6673             // Check that the first expression has form v = x.
6674             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6675             llvm::FoldingSetNodeID XId, PossibleXId;
6676             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6677             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6678             IsUpdateExprFound = XId == PossibleXId;
6679             if (IsUpdateExprFound) {
6680               V = BinOp->getLHS();
6681               X = Checker.getX();
6682               E = Checker.getExpr();
6683               UE = Checker.getUpdateExpr();
6684               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6685               IsPostfixUpdate = true;
6686             }
6687           }
6688           if (!IsUpdateExprFound) {
6689             IsUpdateExprFound = !Checker.checkStatement(First);
6690             BinOp = nullptr;
6691             if (IsUpdateExprFound) {
6692               BinOp = dyn_cast<BinaryOperator>(Second);
6693               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6694             }
6695             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6696               //  { x++; v = x; }
6697               //  { x--; v = x; }
6698               //  { ++x; v = x; }
6699               //  { --x; v = x; }
6700               //  { x binop= expr; v = x; }
6701               //  { x = x binop expr; v = x; }
6702               //  { x = expr binop x; v = x; }
6703               // Check that the second expression has form v = x.
6704               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6705               llvm::FoldingSetNodeID XId, PossibleXId;
6706               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6707               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6708               IsUpdateExprFound = XId == PossibleXId;
6709               if (IsUpdateExprFound) {
6710                 V = BinOp->getLHS();
6711                 X = Checker.getX();
6712                 E = Checker.getExpr();
6713                 UE = Checker.getUpdateExpr();
6714                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6715                 IsPostfixUpdate = false;
6716               }
6717             }
6718           }
6719           if (!IsUpdateExprFound) {
6720             //  { v = x; x = expr; }
6721             auto *FirstExpr = dyn_cast<Expr>(First);
6722             auto *SecondExpr = dyn_cast<Expr>(Second);
6723             if (!FirstExpr || !SecondExpr ||
6724                 !(FirstExpr->isInstantiationDependent() ||
6725                   SecondExpr->isInstantiationDependent())) {
6726               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6727               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6728                 ErrorFound = NotAnAssignmentOp;
6729                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6730                                                 : First->getBeginLoc();
6731                 NoteRange = ErrorRange = FirstBinOp
6732                                              ? FirstBinOp->getSourceRange()
6733                                              : SourceRange(ErrorLoc, ErrorLoc);
6734               } else {
6735                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6736                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6737                   ErrorFound = NotAnAssignmentOp;
6738                   NoteLoc = ErrorLoc = SecondBinOp
6739                                            ? SecondBinOp->getOperatorLoc()
6740                                            : Second->getBeginLoc();
6741                   NoteRange = ErrorRange =
6742                       SecondBinOp ? SecondBinOp->getSourceRange()
6743                                   : SourceRange(ErrorLoc, ErrorLoc);
6744                 } else {
6745                   Expr *PossibleXRHSInFirst =
6746                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6747                   Expr *PossibleXLHSInSecond =
6748                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6749                   llvm::FoldingSetNodeID X1Id, X2Id;
6750                   PossibleXRHSInFirst->Profile(X1Id, Context,
6751                                                /*Canonical=*/true);
6752                   PossibleXLHSInSecond->Profile(X2Id, Context,
6753                                                 /*Canonical=*/true);
6754                   IsUpdateExprFound = X1Id == X2Id;
6755                   if (IsUpdateExprFound) {
6756                     V = FirstBinOp->getLHS();
6757                     X = SecondBinOp->getLHS();
6758                     E = SecondBinOp->getRHS();
6759                     UE = nullptr;
6760                     IsXLHSInRHSPart = false;
6761                     IsPostfixUpdate = true;
6762                   } else {
6763                     ErrorFound = NotASpecificExpression;
6764                     ErrorLoc = FirstBinOp->getExprLoc();
6765                     ErrorRange = FirstBinOp->getSourceRange();
6766                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6767                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6768                   }
6769                 }
6770               }
6771             }
6772           }
6773         } else {
6774           NoteLoc = ErrorLoc = Body->getBeginLoc();
6775           NoteRange = ErrorRange =
6776               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
6777           ErrorFound = NotTwoSubstatements;
6778         }
6779       } else {
6780         NoteLoc = ErrorLoc = Body->getBeginLoc();
6781         NoteRange = ErrorRange =
6782             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
6783         ErrorFound = NotACompoundStatement;
6784       }
6785       if (ErrorFound != NoError) {
6786         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6787             << ErrorRange;
6788         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6789         return StmtError();
6790       }
6791       if (CurContext->isDependentContext())
6792         UE = V = E = X = nullptr;
6793     }
6794   }
6795 
6796   setFunctionHasBranchProtectedScope();
6797 
6798   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6799                                     X, V, E, UE, IsXLHSInRHSPart,
6800                                     IsPostfixUpdate);
6801 }
6802 
6803 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6804                                             Stmt *AStmt,
6805                                             SourceLocation StartLoc,
6806                                             SourceLocation EndLoc) {
6807   if (!AStmt)
6808     return StmtError();
6809 
6810   auto *CS = cast<CapturedStmt>(AStmt);
6811   // 1.2.2 OpenMP Language Terminology
6812   // Structured block - An executable statement with a single entry at the
6813   // top and a single exit at the bottom.
6814   // The point of exit cannot be a branch out of the structured block.
6815   // longjmp() and throw() must not violate the entry/exit criteria.
6816   CS->getCapturedDecl()->setNothrow();
6817   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6818        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6819     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6820     // 1.2.2 OpenMP Language Terminology
6821     // Structured block - An executable statement with a single entry at the
6822     // top and a single exit at the bottom.
6823     // The point of exit cannot be a branch out of the structured block.
6824     // longjmp() and throw() must not violate the entry/exit criteria.
6825     CS->getCapturedDecl()->setNothrow();
6826   }
6827 
6828   // OpenMP [2.16, Nesting of Regions]
6829   // If specified, a teams construct must be contained within a target
6830   // construct. That target construct must contain no statements or directives
6831   // outside of the teams construct.
6832   if (DSAStack->hasInnerTeamsRegion()) {
6833     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
6834     bool OMPTeamsFound = true;
6835     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
6836       auto I = CS->body_begin();
6837       while (I != CS->body_end()) {
6838         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6839         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6840           OMPTeamsFound = false;
6841           break;
6842         }
6843         ++I;
6844       }
6845       assert(I != CS->body_end() && "Not found statement");
6846       S = *I;
6847     } else {
6848       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
6849       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6850     }
6851     if (!OMPTeamsFound) {
6852       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6853       Diag(DSAStack->getInnerTeamsRegionLoc(),
6854            diag::note_omp_nested_teams_construct_here);
6855       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
6856           << isa<OMPExecutableDirective>(S);
6857       return StmtError();
6858     }
6859   }
6860 
6861   setFunctionHasBranchProtectedScope();
6862 
6863   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6864 }
6865 
6866 StmtResult
6867 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6868                                          Stmt *AStmt, SourceLocation StartLoc,
6869                                          SourceLocation EndLoc) {
6870   if (!AStmt)
6871     return StmtError();
6872 
6873   auto *CS = cast<CapturedStmt>(AStmt);
6874   // 1.2.2 OpenMP Language Terminology
6875   // Structured block - An executable statement with a single entry at the
6876   // top and a single exit at the bottom.
6877   // The point of exit cannot be a branch out of the structured block.
6878   // longjmp() and throw() must not violate the entry/exit criteria.
6879   CS->getCapturedDecl()->setNothrow();
6880   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6881        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6882     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6883     // 1.2.2 OpenMP Language Terminology
6884     // Structured block - An executable statement with a single entry at the
6885     // top and a single exit at the bottom.
6886     // The point of exit cannot be a branch out of the structured block.
6887     // longjmp() and throw() must not violate the entry/exit criteria.
6888     CS->getCapturedDecl()->setNothrow();
6889   }
6890 
6891   setFunctionHasBranchProtectedScope();
6892 
6893   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6894                                             AStmt);
6895 }
6896 
6897 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6898     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6899     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6900   if (!AStmt)
6901     return StmtError();
6902 
6903   auto *CS = cast<CapturedStmt>(AStmt);
6904   // 1.2.2 OpenMP Language Terminology
6905   // Structured block - An executable statement with a single entry at the
6906   // top and a single exit at the bottom.
6907   // The point of exit cannot be a branch out of the structured block.
6908   // longjmp() and throw() must not violate the entry/exit criteria.
6909   CS->getCapturedDecl()->setNothrow();
6910   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6911        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6912     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6913     // 1.2.2 OpenMP Language Terminology
6914     // Structured block - An executable statement with a single entry at the
6915     // top and a single exit at the bottom.
6916     // The point of exit cannot be a branch out of the structured block.
6917     // longjmp() and throw() must not violate the entry/exit criteria.
6918     CS->getCapturedDecl()->setNothrow();
6919   }
6920 
6921   OMPLoopDirective::HelperExprs B;
6922   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6923   // define the nested loops number.
6924   unsigned NestedLoopCount =
6925       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6926                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
6927                       VarsWithImplicitDSA, B);
6928   if (NestedLoopCount == 0)
6929     return StmtError();
6930 
6931   assert((CurContext->isDependentContext() || B.builtAll()) &&
6932          "omp target parallel for loop exprs were not built");
6933 
6934   if (!CurContext->isDependentContext()) {
6935     // Finalize the clauses that need pre-built expressions for CodeGen.
6936     for (OMPClause *C : Clauses) {
6937       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6938         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6939                                      B.NumIterations, *this, CurScope,
6940                                      DSAStack))
6941           return StmtError();
6942     }
6943   }
6944 
6945   setFunctionHasBranchProtectedScope();
6946   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6947                                                NestedLoopCount, Clauses, AStmt,
6948                                                B, DSAStack->isCancelRegion());
6949 }
6950 
6951 /// Check for existence of a map clause in the list of clauses.
6952 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6953                        const OpenMPClauseKind K) {
6954   return llvm::any_of(
6955       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6956 }
6957 
6958 template <typename... Params>
6959 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6960                        const Params... ClauseTypes) {
6961   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6962 }
6963 
6964 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6965                                                 Stmt *AStmt,
6966                                                 SourceLocation StartLoc,
6967                                                 SourceLocation EndLoc) {
6968   if (!AStmt)
6969     return StmtError();
6970 
6971   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6972 
6973   // OpenMP [2.10.1, Restrictions, p. 97]
6974   // At least one map clause must appear on the directive.
6975   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6976     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6977         << "'map' or 'use_device_ptr'"
6978         << getOpenMPDirectiveName(OMPD_target_data);
6979     return StmtError();
6980   }
6981 
6982   setFunctionHasBranchProtectedScope();
6983 
6984   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6985                                         AStmt);
6986 }
6987 
6988 StmtResult
6989 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6990                                           SourceLocation StartLoc,
6991                                           SourceLocation EndLoc, Stmt *AStmt) {
6992   if (!AStmt)
6993     return StmtError();
6994 
6995   auto *CS = cast<CapturedStmt>(AStmt);
6996   // 1.2.2 OpenMP Language Terminology
6997   // Structured block - An executable statement with a single entry at the
6998   // top and a single exit at the bottom.
6999   // The point of exit cannot be a branch out of the structured block.
7000   // longjmp() and throw() must not violate the entry/exit criteria.
7001   CS->getCapturedDecl()->setNothrow();
7002   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7003        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7004     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7005     // 1.2.2 OpenMP Language Terminology
7006     // Structured block - An executable statement with a single entry at the
7007     // top and a single exit at the bottom.
7008     // The point of exit cannot be a branch out of the structured block.
7009     // longjmp() and throw() must not violate the entry/exit criteria.
7010     CS->getCapturedDecl()->setNothrow();
7011   }
7012 
7013   // OpenMP [2.10.2, Restrictions, p. 99]
7014   // At least one map clause must appear on the directive.
7015   if (!hasClauses(Clauses, OMPC_map)) {
7016     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7017         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
7018     return StmtError();
7019   }
7020 
7021   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7022                                              AStmt);
7023 }
7024 
7025 StmtResult
7026 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7027                                          SourceLocation StartLoc,
7028                                          SourceLocation EndLoc, Stmt *AStmt) {
7029   if (!AStmt)
7030     return StmtError();
7031 
7032   auto *CS = cast<CapturedStmt>(AStmt);
7033   // 1.2.2 OpenMP Language Terminology
7034   // Structured block - An executable statement with a single entry at the
7035   // top and a single exit at the bottom.
7036   // The point of exit cannot be a branch out of the structured block.
7037   // longjmp() and throw() must not violate the entry/exit criteria.
7038   CS->getCapturedDecl()->setNothrow();
7039   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7040        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7041     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7042     // 1.2.2 OpenMP Language Terminology
7043     // Structured block - An executable statement with a single entry at the
7044     // top and a single exit at the bottom.
7045     // The point of exit cannot be a branch out of the structured block.
7046     // longjmp() and throw() must not violate the entry/exit criteria.
7047     CS->getCapturedDecl()->setNothrow();
7048   }
7049 
7050   // OpenMP [2.10.3, Restrictions, p. 102]
7051   // At least one map clause must appear on the directive.
7052   if (!hasClauses(Clauses, OMPC_map)) {
7053     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7054         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
7055     return StmtError();
7056   }
7057 
7058   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7059                                             AStmt);
7060 }
7061 
7062 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7063                                                   SourceLocation StartLoc,
7064                                                   SourceLocation EndLoc,
7065                                                   Stmt *AStmt) {
7066   if (!AStmt)
7067     return StmtError();
7068 
7069   auto *CS = cast<CapturedStmt>(AStmt);
7070   // 1.2.2 OpenMP Language Terminology
7071   // Structured block - An executable statement with a single entry at the
7072   // top and a single exit at the bottom.
7073   // The point of exit cannot be a branch out of the structured block.
7074   // longjmp() and throw() must not violate the entry/exit criteria.
7075   CS->getCapturedDecl()->setNothrow();
7076   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7077        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7078     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7079     // 1.2.2 OpenMP Language Terminology
7080     // Structured block - An executable statement with a single entry at the
7081     // top and a single exit at the bottom.
7082     // The point of exit cannot be a branch out of the structured block.
7083     // longjmp() and throw() must not violate the entry/exit criteria.
7084     CS->getCapturedDecl()->setNothrow();
7085   }
7086 
7087   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
7088     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7089     return StmtError();
7090   }
7091   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7092                                           AStmt);
7093 }
7094 
7095 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7096                                            Stmt *AStmt, SourceLocation StartLoc,
7097                                            SourceLocation EndLoc) {
7098   if (!AStmt)
7099     return StmtError();
7100 
7101   auto *CS = cast<CapturedStmt>(AStmt);
7102   // 1.2.2 OpenMP Language Terminology
7103   // Structured block - An executable statement with a single entry at the
7104   // top and a single exit at the bottom.
7105   // The point of exit cannot be a branch out of the structured block.
7106   // longjmp() and throw() must not violate the entry/exit criteria.
7107   CS->getCapturedDecl()->setNothrow();
7108 
7109   setFunctionHasBranchProtectedScope();
7110 
7111   DSAStack->setParentTeamsRegionLoc(StartLoc);
7112 
7113   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7114 }
7115 
7116 StmtResult
7117 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7118                                             SourceLocation EndLoc,
7119                                             OpenMPDirectiveKind CancelRegion) {
7120   if (DSAStack->isParentNowaitRegion()) {
7121     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7122     return StmtError();
7123   }
7124   if (DSAStack->isParentOrderedRegion()) {
7125     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7126     return StmtError();
7127   }
7128   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7129                                                CancelRegion);
7130 }
7131 
7132 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7133                                             SourceLocation StartLoc,
7134                                             SourceLocation EndLoc,
7135                                             OpenMPDirectiveKind CancelRegion) {
7136   if (DSAStack->isParentNowaitRegion()) {
7137     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7138     return StmtError();
7139   }
7140   if (DSAStack->isParentOrderedRegion()) {
7141     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7142     return StmtError();
7143   }
7144   DSAStack->setParentCancelRegion(/*Cancel=*/true);
7145   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7146                                     CancelRegion);
7147 }
7148 
7149 static bool checkGrainsizeNumTasksClauses(Sema &S,
7150                                           ArrayRef<OMPClause *> Clauses) {
7151   const OMPClause *PrevClause = nullptr;
7152   bool ErrorFound = false;
7153   for (const OMPClause *C : Clauses) {
7154     if (C->getClauseKind() == OMPC_grainsize ||
7155         C->getClauseKind() == OMPC_num_tasks) {
7156       if (!PrevClause)
7157         PrevClause = C;
7158       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
7159         S.Diag(C->getBeginLoc(),
7160                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7161             << getOpenMPClauseName(C->getClauseKind())
7162             << getOpenMPClauseName(PrevClause->getClauseKind());
7163         S.Diag(PrevClause->getBeginLoc(),
7164                diag::note_omp_previous_grainsize_num_tasks)
7165             << getOpenMPClauseName(PrevClause->getClauseKind());
7166         ErrorFound = true;
7167       }
7168     }
7169   }
7170   return ErrorFound;
7171 }
7172 
7173 static bool checkReductionClauseWithNogroup(Sema &S,
7174                                             ArrayRef<OMPClause *> Clauses) {
7175   const OMPClause *ReductionClause = nullptr;
7176   const OMPClause *NogroupClause = nullptr;
7177   for (const OMPClause *C : Clauses) {
7178     if (C->getClauseKind() == OMPC_reduction) {
7179       ReductionClause = C;
7180       if (NogroupClause)
7181         break;
7182       continue;
7183     }
7184     if (C->getClauseKind() == OMPC_nogroup) {
7185       NogroupClause = C;
7186       if (ReductionClause)
7187         break;
7188       continue;
7189     }
7190   }
7191   if (ReductionClause && NogroupClause) {
7192     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7193         << SourceRange(NogroupClause->getBeginLoc(),
7194                        NogroupClause->getEndLoc());
7195     return true;
7196   }
7197   return false;
7198 }
7199 
7200 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7201     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7202     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7203   if (!AStmt)
7204     return StmtError();
7205 
7206   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7207   OMPLoopDirective::HelperExprs B;
7208   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7209   // define the nested loops number.
7210   unsigned NestedLoopCount =
7211       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
7212                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7213                       VarsWithImplicitDSA, B);
7214   if (NestedLoopCount == 0)
7215     return StmtError();
7216 
7217   assert((CurContext->isDependentContext() || B.builtAll()) &&
7218          "omp for loop exprs were not built");
7219 
7220   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7221   // The grainsize clause and num_tasks clause are mutually exclusive and may
7222   // not appear on the same taskloop directive.
7223   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7224     return StmtError();
7225   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7226   // If a reduction clause is present on the taskloop directive, the nogroup
7227   // clause must not be specified.
7228   if (checkReductionClauseWithNogroup(*this, Clauses))
7229     return StmtError();
7230 
7231   setFunctionHasBranchProtectedScope();
7232   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7233                                       NestedLoopCount, Clauses, AStmt, B);
7234 }
7235 
7236 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7237     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7238     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7239   if (!AStmt)
7240     return StmtError();
7241 
7242   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7243   OMPLoopDirective::HelperExprs B;
7244   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7245   // define the nested loops number.
7246   unsigned NestedLoopCount =
7247       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
7248                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7249                       VarsWithImplicitDSA, B);
7250   if (NestedLoopCount == 0)
7251     return StmtError();
7252 
7253   assert((CurContext->isDependentContext() || B.builtAll()) &&
7254          "omp for loop exprs were not built");
7255 
7256   if (!CurContext->isDependentContext()) {
7257     // Finalize the clauses that need pre-built expressions for CodeGen.
7258     for (OMPClause *C : Clauses) {
7259       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7260         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7261                                      B.NumIterations, *this, CurScope,
7262                                      DSAStack))
7263           return StmtError();
7264     }
7265   }
7266 
7267   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7268   // The grainsize clause and num_tasks clause are mutually exclusive and may
7269   // not appear on the same taskloop directive.
7270   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7271     return StmtError();
7272   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7273   // If a reduction clause is present on the taskloop directive, the nogroup
7274   // clause must not be specified.
7275   if (checkReductionClauseWithNogroup(*this, Clauses))
7276     return StmtError();
7277   if (checkSimdlenSafelenSpecified(*this, Clauses))
7278     return StmtError();
7279 
7280   setFunctionHasBranchProtectedScope();
7281   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7282                                           NestedLoopCount, Clauses, AStmt, B);
7283 }
7284 
7285 StmtResult Sema::ActOnOpenMPDistributeDirective(
7286     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7287     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7288   if (!AStmt)
7289     return StmtError();
7290 
7291   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7292   OMPLoopDirective::HelperExprs B;
7293   // In presence of clause 'collapse' with number of loops, it will
7294   // define the nested loops number.
7295   unsigned NestedLoopCount =
7296       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
7297                       nullptr /*ordered not a clause on distribute*/, AStmt,
7298                       *this, *DSAStack, VarsWithImplicitDSA, B);
7299   if (NestedLoopCount == 0)
7300     return StmtError();
7301 
7302   assert((CurContext->isDependentContext() || B.builtAll()) &&
7303          "omp for loop exprs were not built");
7304 
7305   setFunctionHasBranchProtectedScope();
7306   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7307                                         NestedLoopCount, Clauses, AStmt, B);
7308 }
7309 
7310 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7311     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7312     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7313   if (!AStmt)
7314     return StmtError();
7315 
7316   auto *CS = cast<CapturedStmt>(AStmt);
7317   // 1.2.2 OpenMP Language Terminology
7318   // Structured block - An executable statement with a single entry at the
7319   // top and a single exit at the bottom.
7320   // The point of exit cannot be a branch out of the structured block.
7321   // longjmp() and throw() must not violate the entry/exit criteria.
7322   CS->getCapturedDecl()->setNothrow();
7323   for (int ThisCaptureLevel =
7324            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7325        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7326     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7327     // 1.2.2 OpenMP Language Terminology
7328     // Structured block - An executable statement with a single entry at the
7329     // top and a single exit at the bottom.
7330     // The point of exit cannot be a branch out of the structured block.
7331     // longjmp() and throw() must not violate the entry/exit criteria.
7332     CS->getCapturedDecl()->setNothrow();
7333   }
7334 
7335   OMPLoopDirective::HelperExprs B;
7336   // In presence of clause 'collapse' with number of loops, it will
7337   // define the nested loops number.
7338   unsigned NestedLoopCount = checkOpenMPLoop(
7339       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7340       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7341       VarsWithImplicitDSA, B);
7342   if (NestedLoopCount == 0)
7343     return StmtError();
7344 
7345   assert((CurContext->isDependentContext() || B.builtAll()) &&
7346          "omp for loop exprs were not built");
7347 
7348   setFunctionHasBranchProtectedScope();
7349   return OMPDistributeParallelForDirective::Create(
7350       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7351       DSAStack->isCancelRegion());
7352 }
7353 
7354 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7355     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7356     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7357   if (!AStmt)
7358     return StmtError();
7359 
7360   auto *CS = cast<CapturedStmt>(AStmt);
7361   // 1.2.2 OpenMP Language Terminology
7362   // Structured block - An executable statement with a single entry at the
7363   // top and a single exit at the bottom.
7364   // The point of exit cannot be a branch out of the structured block.
7365   // longjmp() and throw() must not violate the entry/exit criteria.
7366   CS->getCapturedDecl()->setNothrow();
7367   for (int ThisCaptureLevel =
7368            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7369        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7370     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7371     // 1.2.2 OpenMP Language Terminology
7372     // Structured block - An executable statement with a single entry at the
7373     // top and a single exit at the bottom.
7374     // The point of exit cannot be a branch out of the structured block.
7375     // longjmp() and throw() must not violate the entry/exit criteria.
7376     CS->getCapturedDecl()->setNothrow();
7377   }
7378 
7379   OMPLoopDirective::HelperExprs B;
7380   // In presence of clause 'collapse' with number of loops, it will
7381   // define the nested loops number.
7382   unsigned NestedLoopCount = checkOpenMPLoop(
7383       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7384       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7385       VarsWithImplicitDSA, B);
7386   if (NestedLoopCount == 0)
7387     return StmtError();
7388 
7389   assert((CurContext->isDependentContext() || B.builtAll()) &&
7390          "omp for loop exprs were not built");
7391 
7392   if (!CurContext->isDependentContext()) {
7393     // Finalize the clauses that need pre-built expressions for CodeGen.
7394     for (OMPClause *C : Clauses) {
7395       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7396         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7397                                      B.NumIterations, *this, CurScope,
7398                                      DSAStack))
7399           return StmtError();
7400     }
7401   }
7402 
7403   if (checkSimdlenSafelenSpecified(*this, Clauses))
7404     return StmtError();
7405 
7406   setFunctionHasBranchProtectedScope();
7407   return OMPDistributeParallelForSimdDirective::Create(
7408       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7409 }
7410 
7411 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7412     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7413     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7414   if (!AStmt)
7415     return StmtError();
7416 
7417   auto *CS = cast<CapturedStmt>(AStmt);
7418   // 1.2.2 OpenMP Language Terminology
7419   // Structured block - An executable statement with a single entry at the
7420   // top and a single exit at the bottom.
7421   // The point of exit cannot be a branch out of the structured block.
7422   // longjmp() and throw() must not violate the entry/exit criteria.
7423   CS->getCapturedDecl()->setNothrow();
7424   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7425        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7426     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7427     // 1.2.2 OpenMP Language Terminology
7428     // Structured block - An executable statement with a single entry at the
7429     // top and a single exit at the bottom.
7430     // The point of exit cannot be a branch out of the structured block.
7431     // longjmp() and throw() must not violate the entry/exit criteria.
7432     CS->getCapturedDecl()->setNothrow();
7433   }
7434 
7435   OMPLoopDirective::HelperExprs B;
7436   // In presence of clause 'collapse' with number of loops, it will
7437   // define the nested loops number.
7438   unsigned NestedLoopCount =
7439       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7440                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7441                       *DSAStack, VarsWithImplicitDSA, B);
7442   if (NestedLoopCount == 0)
7443     return StmtError();
7444 
7445   assert((CurContext->isDependentContext() || B.builtAll()) &&
7446          "omp for loop exprs were not built");
7447 
7448   if (!CurContext->isDependentContext()) {
7449     // Finalize the clauses that need pre-built expressions for CodeGen.
7450     for (OMPClause *C : Clauses) {
7451       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7452         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7453                                      B.NumIterations, *this, CurScope,
7454                                      DSAStack))
7455           return StmtError();
7456     }
7457   }
7458 
7459   if (checkSimdlenSafelenSpecified(*this, Clauses))
7460     return StmtError();
7461 
7462   setFunctionHasBranchProtectedScope();
7463   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7464                                             NestedLoopCount, Clauses, AStmt, B);
7465 }
7466 
7467 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7468     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7469     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7470   if (!AStmt)
7471     return StmtError();
7472 
7473   auto *CS = cast<CapturedStmt>(AStmt);
7474   // 1.2.2 OpenMP Language Terminology
7475   // Structured block - An executable statement with a single entry at the
7476   // top and a single exit at the bottom.
7477   // The point of exit cannot be a branch out of the structured block.
7478   // longjmp() and throw() must not violate the entry/exit criteria.
7479   CS->getCapturedDecl()->setNothrow();
7480   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7481        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7482     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7483     // 1.2.2 OpenMP Language Terminology
7484     // Structured block - An executable statement with a single entry at the
7485     // top and a single exit at the bottom.
7486     // The point of exit cannot be a branch out of the structured block.
7487     // longjmp() and throw() must not violate the entry/exit criteria.
7488     CS->getCapturedDecl()->setNothrow();
7489   }
7490 
7491   OMPLoopDirective::HelperExprs B;
7492   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7493   // define the nested loops number.
7494   unsigned NestedLoopCount = checkOpenMPLoop(
7495       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7496       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7497       VarsWithImplicitDSA, B);
7498   if (NestedLoopCount == 0)
7499     return StmtError();
7500 
7501   assert((CurContext->isDependentContext() || B.builtAll()) &&
7502          "omp target parallel for simd loop exprs were not built");
7503 
7504   if (!CurContext->isDependentContext()) {
7505     // Finalize the clauses that need pre-built expressions for CodeGen.
7506     for (OMPClause *C : Clauses) {
7507       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7508         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7509                                      B.NumIterations, *this, CurScope,
7510                                      DSAStack))
7511           return StmtError();
7512     }
7513   }
7514   if (checkSimdlenSafelenSpecified(*this, Clauses))
7515     return StmtError();
7516 
7517   setFunctionHasBranchProtectedScope();
7518   return OMPTargetParallelForSimdDirective::Create(
7519       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7520 }
7521 
7522 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7523     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7524     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7525   if (!AStmt)
7526     return StmtError();
7527 
7528   auto *CS = cast<CapturedStmt>(AStmt);
7529   // 1.2.2 OpenMP Language Terminology
7530   // Structured block - An executable statement with a single entry at the
7531   // top and a single exit at the bottom.
7532   // The point of exit cannot be a branch out of the structured block.
7533   // longjmp() and throw() must not violate the entry/exit criteria.
7534   CS->getCapturedDecl()->setNothrow();
7535   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7536        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7537     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7538     // 1.2.2 OpenMP Language Terminology
7539     // Structured block - An executable statement with a single entry at the
7540     // top and a single exit at the bottom.
7541     // The point of exit cannot be a branch out of the structured block.
7542     // longjmp() and throw() must not violate the entry/exit criteria.
7543     CS->getCapturedDecl()->setNothrow();
7544   }
7545 
7546   OMPLoopDirective::HelperExprs B;
7547   // In presence of clause 'collapse' with number of loops, it will define the
7548   // nested loops number.
7549   unsigned NestedLoopCount =
7550       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7551                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7552                       VarsWithImplicitDSA, B);
7553   if (NestedLoopCount == 0)
7554     return StmtError();
7555 
7556   assert((CurContext->isDependentContext() || B.builtAll()) &&
7557          "omp target simd loop exprs were not built");
7558 
7559   if (!CurContext->isDependentContext()) {
7560     // Finalize the clauses that need pre-built expressions for CodeGen.
7561     for (OMPClause *C : Clauses) {
7562       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7563         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7564                                      B.NumIterations, *this, CurScope,
7565                                      DSAStack))
7566           return StmtError();
7567     }
7568   }
7569 
7570   if (checkSimdlenSafelenSpecified(*this, Clauses))
7571     return StmtError();
7572 
7573   setFunctionHasBranchProtectedScope();
7574   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7575                                         NestedLoopCount, Clauses, AStmt, B);
7576 }
7577 
7578 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7579     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7580     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7581   if (!AStmt)
7582     return StmtError();
7583 
7584   auto *CS = cast<CapturedStmt>(AStmt);
7585   // 1.2.2 OpenMP Language Terminology
7586   // Structured block - An executable statement with a single entry at the
7587   // top and a single exit at the bottom.
7588   // The point of exit cannot be a branch out of the structured block.
7589   // longjmp() and throw() must not violate the entry/exit criteria.
7590   CS->getCapturedDecl()->setNothrow();
7591   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7592        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7593     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7594     // 1.2.2 OpenMP Language Terminology
7595     // Structured block - An executable statement with a single entry at the
7596     // top and a single exit at the bottom.
7597     // The point of exit cannot be a branch out of the structured block.
7598     // longjmp() and throw() must not violate the entry/exit criteria.
7599     CS->getCapturedDecl()->setNothrow();
7600   }
7601 
7602   OMPLoopDirective::HelperExprs B;
7603   // In presence of clause 'collapse' with number of loops, it will
7604   // define the nested loops number.
7605   unsigned NestedLoopCount =
7606       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7607                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7608                       *DSAStack, VarsWithImplicitDSA, B);
7609   if (NestedLoopCount == 0)
7610     return StmtError();
7611 
7612   assert((CurContext->isDependentContext() || B.builtAll()) &&
7613          "omp teams distribute loop exprs were not built");
7614 
7615   setFunctionHasBranchProtectedScope();
7616 
7617   DSAStack->setParentTeamsRegionLoc(StartLoc);
7618 
7619   return OMPTeamsDistributeDirective::Create(
7620       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7621 }
7622 
7623 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7624     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7625     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7626   if (!AStmt)
7627     return StmtError();
7628 
7629   auto *CS = cast<CapturedStmt>(AStmt);
7630   // 1.2.2 OpenMP Language Terminology
7631   // Structured block - An executable statement with a single entry at the
7632   // top and a single exit at the bottom.
7633   // The point of exit cannot be a branch out of the structured block.
7634   // longjmp() and throw() must not violate the entry/exit criteria.
7635   CS->getCapturedDecl()->setNothrow();
7636   for (int ThisCaptureLevel =
7637            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7638        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7639     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7640     // 1.2.2 OpenMP Language Terminology
7641     // Structured block - An executable statement with a single entry at the
7642     // top and a single exit at the bottom.
7643     // The point of exit cannot be a branch out of the structured block.
7644     // longjmp() and throw() must not violate the entry/exit criteria.
7645     CS->getCapturedDecl()->setNothrow();
7646   }
7647 
7648 
7649   OMPLoopDirective::HelperExprs B;
7650   // In presence of clause 'collapse' with number of loops, it will
7651   // define the nested loops number.
7652   unsigned NestedLoopCount = checkOpenMPLoop(
7653       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7654       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7655       VarsWithImplicitDSA, B);
7656 
7657   if (NestedLoopCount == 0)
7658     return StmtError();
7659 
7660   assert((CurContext->isDependentContext() || B.builtAll()) &&
7661          "omp teams distribute simd loop exprs were not built");
7662 
7663   if (!CurContext->isDependentContext()) {
7664     // Finalize the clauses that need pre-built expressions for CodeGen.
7665     for (OMPClause *C : Clauses) {
7666       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7667         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7668                                      B.NumIterations, *this, CurScope,
7669                                      DSAStack))
7670           return StmtError();
7671     }
7672   }
7673 
7674   if (checkSimdlenSafelenSpecified(*this, Clauses))
7675     return StmtError();
7676 
7677   setFunctionHasBranchProtectedScope();
7678 
7679   DSAStack->setParentTeamsRegionLoc(StartLoc);
7680 
7681   return OMPTeamsDistributeSimdDirective::Create(
7682       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7683 }
7684 
7685 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7686     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7687     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7688   if (!AStmt)
7689     return StmtError();
7690 
7691   auto *CS = cast<CapturedStmt>(AStmt);
7692   // 1.2.2 OpenMP Language Terminology
7693   // Structured block - An executable statement with a single entry at the
7694   // top and a single exit at the bottom.
7695   // The point of exit cannot be a branch out of the structured block.
7696   // longjmp() and throw() must not violate the entry/exit criteria.
7697   CS->getCapturedDecl()->setNothrow();
7698 
7699   for (int ThisCaptureLevel =
7700            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7701        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7702     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7703     // 1.2.2 OpenMP Language Terminology
7704     // Structured block - An executable statement with a single entry at the
7705     // top and a single exit at the bottom.
7706     // The point of exit cannot be a branch out of the structured block.
7707     // longjmp() and throw() must not violate the entry/exit criteria.
7708     CS->getCapturedDecl()->setNothrow();
7709   }
7710 
7711   OMPLoopDirective::HelperExprs B;
7712   // In presence of clause 'collapse' with number of loops, it will
7713   // define the nested loops number.
7714   unsigned NestedLoopCount = checkOpenMPLoop(
7715       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7716       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7717       VarsWithImplicitDSA, B);
7718 
7719   if (NestedLoopCount == 0)
7720     return StmtError();
7721 
7722   assert((CurContext->isDependentContext() || B.builtAll()) &&
7723          "omp for loop exprs were not built");
7724 
7725   if (!CurContext->isDependentContext()) {
7726     // Finalize the clauses that need pre-built expressions for CodeGen.
7727     for (OMPClause *C : Clauses) {
7728       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7729         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7730                                      B.NumIterations, *this, CurScope,
7731                                      DSAStack))
7732           return StmtError();
7733     }
7734   }
7735 
7736   if (checkSimdlenSafelenSpecified(*this, Clauses))
7737     return StmtError();
7738 
7739   setFunctionHasBranchProtectedScope();
7740 
7741   DSAStack->setParentTeamsRegionLoc(StartLoc);
7742 
7743   return OMPTeamsDistributeParallelForSimdDirective::Create(
7744       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7745 }
7746 
7747 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7748     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7749     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7750   if (!AStmt)
7751     return StmtError();
7752 
7753   auto *CS = cast<CapturedStmt>(AStmt);
7754   // 1.2.2 OpenMP Language Terminology
7755   // Structured block - An executable statement with a single entry at the
7756   // top and a single exit at the bottom.
7757   // The point of exit cannot be a branch out of the structured block.
7758   // longjmp() and throw() must not violate the entry/exit criteria.
7759   CS->getCapturedDecl()->setNothrow();
7760 
7761   for (int ThisCaptureLevel =
7762            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7763        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7764     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7765     // 1.2.2 OpenMP Language Terminology
7766     // Structured block - An executable statement with a single entry at the
7767     // top and a single exit at the bottom.
7768     // The point of exit cannot be a branch out of the structured block.
7769     // longjmp() and throw() must not violate the entry/exit criteria.
7770     CS->getCapturedDecl()->setNothrow();
7771   }
7772 
7773   OMPLoopDirective::HelperExprs B;
7774   // In presence of clause 'collapse' with number of loops, it will
7775   // define the nested loops number.
7776   unsigned NestedLoopCount = checkOpenMPLoop(
7777       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7778       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7779       VarsWithImplicitDSA, B);
7780 
7781   if (NestedLoopCount == 0)
7782     return StmtError();
7783 
7784   assert((CurContext->isDependentContext() || B.builtAll()) &&
7785          "omp for loop exprs were not built");
7786 
7787   setFunctionHasBranchProtectedScope();
7788 
7789   DSAStack->setParentTeamsRegionLoc(StartLoc);
7790 
7791   return OMPTeamsDistributeParallelForDirective::Create(
7792       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7793       DSAStack->isCancelRegion());
7794 }
7795 
7796 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7797                                                  Stmt *AStmt,
7798                                                  SourceLocation StartLoc,
7799                                                  SourceLocation EndLoc) {
7800   if (!AStmt)
7801     return StmtError();
7802 
7803   auto *CS = cast<CapturedStmt>(AStmt);
7804   // 1.2.2 OpenMP Language Terminology
7805   // Structured block - An executable statement with a single entry at the
7806   // top and a single exit at the bottom.
7807   // The point of exit cannot be a branch out of the structured block.
7808   // longjmp() and throw() must not violate the entry/exit criteria.
7809   CS->getCapturedDecl()->setNothrow();
7810 
7811   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7812        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7813     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7814     // 1.2.2 OpenMP Language Terminology
7815     // Structured block - An executable statement with a single entry at the
7816     // top and a single exit at the bottom.
7817     // The point of exit cannot be a branch out of the structured block.
7818     // longjmp() and throw() must not violate the entry/exit criteria.
7819     CS->getCapturedDecl()->setNothrow();
7820   }
7821   setFunctionHasBranchProtectedScope();
7822 
7823   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7824                                          AStmt);
7825 }
7826 
7827 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7828     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7829     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7830   if (!AStmt)
7831     return StmtError();
7832 
7833   auto *CS = cast<CapturedStmt>(AStmt);
7834   // 1.2.2 OpenMP Language Terminology
7835   // Structured block - An executable statement with a single entry at the
7836   // top and a single exit at the bottom.
7837   // The point of exit cannot be a branch out of the structured block.
7838   // longjmp() and throw() must not violate the entry/exit criteria.
7839   CS->getCapturedDecl()->setNothrow();
7840   for (int ThisCaptureLevel =
7841            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7842        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7843     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7844     // 1.2.2 OpenMP Language Terminology
7845     // Structured block - An executable statement with a single entry at the
7846     // top and a single exit at the bottom.
7847     // The point of exit cannot be a branch out of the structured block.
7848     // longjmp() and throw() must not violate the entry/exit criteria.
7849     CS->getCapturedDecl()->setNothrow();
7850   }
7851 
7852   OMPLoopDirective::HelperExprs B;
7853   // In presence of clause 'collapse' with number of loops, it will
7854   // define the nested loops number.
7855   unsigned NestedLoopCount = checkOpenMPLoop(
7856       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7857       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7858       VarsWithImplicitDSA, B);
7859   if (NestedLoopCount == 0)
7860     return StmtError();
7861 
7862   assert((CurContext->isDependentContext() || B.builtAll()) &&
7863          "omp target teams distribute loop exprs were not built");
7864 
7865   setFunctionHasBranchProtectedScope();
7866   return OMPTargetTeamsDistributeDirective::Create(
7867       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7868 }
7869 
7870 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7871     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7872     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7873   if (!AStmt)
7874     return StmtError();
7875 
7876   auto *CS = cast<CapturedStmt>(AStmt);
7877   // 1.2.2 OpenMP Language Terminology
7878   // Structured block - An executable statement with a single entry at the
7879   // top and a single exit at the bottom.
7880   // The point of exit cannot be a branch out of the structured block.
7881   // longjmp() and throw() must not violate the entry/exit criteria.
7882   CS->getCapturedDecl()->setNothrow();
7883   for (int ThisCaptureLevel =
7884            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7885        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7886     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7887     // 1.2.2 OpenMP Language Terminology
7888     // Structured block - An executable statement with a single entry at the
7889     // top and a single exit at the bottom.
7890     // The point of exit cannot be a branch out of the structured block.
7891     // longjmp() and throw() must not violate the entry/exit criteria.
7892     CS->getCapturedDecl()->setNothrow();
7893   }
7894 
7895   OMPLoopDirective::HelperExprs B;
7896   // In presence of clause 'collapse' with number of loops, it will
7897   // define the nested loops number.
7898   unsigned NestedLoopCount = checkOpenMPLoop(
7899       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7900       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7901       VarsWithImplicitDSA, B);
7902   if (NestedLoopCount == 0)
7903     return StmtError();
7904 
7905   assert((CurContext->isDependentContext() || B.builtAll()) &&
7906          "omp target teams distribute parallel for loop exprs were not built");
7907 
7908   if (!CurContext->isDependentContext()) {
7909     // Finalize the clauses that need pre-built expressions for CodeGen.
7910     for (OMPClause *C : Clauses) {
7911       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7912         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7913                                      B.NumIterations, *this, CurScope,
7914                                      DSAStack))
7915           return StmtError();
7916     }
7917   }
7918 
7919   setFunctionHasBranchProtectedScope();
7920   return OMPTargetTeamsDistributeParallelForDirective::Create(
7921       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7922       DSAStack->isCancelRegion());
7923 }
7924 
7925 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7926     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7927     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7928   if (!AStmt)
7929     return StmtError();
7930 
7931   auto *CS = cast<CapturedStmt>(AStmt);
7932   // 1.2.2 OpenMP Language Terminology
7933   // Structured block - An executable statement with a single entry at the
7934   // top and a single exit at the bottom.
7935   // The point of exit cannot be a branch out of the structured block.
7936   // longjmp() and throw() must not violate the entry/exit criteria.
7937   CS->getCapturedDecl()->setNothrow();
7938   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7939            OMPD_target_teams_distribute_parallel_for_simd);
7940        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7941     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7942     // 1.2.2 OpenMP Language Terminology
7943     // Structured block - An executable statement with a single entry at the
7944     // top and a single exit at the bottom.
7945     // The point of exit cannot be a branch out of the structured block.
7946     // longjmp() and throw() must not violate the entry/exit criteria.
7947     CS->getCapturedDecl()->setNothrow();
7948   }
7949 
7950   OMPLoopDirective::HelperExprs B;
7951   // In presence of clause 'collapse' with number of loops, it will
7952   // define the nested loops number.
7953   unsigned NestedLoopCount =
7954       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7955                       getCollapseNumberExpr(Clauses),
7956                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7957                       *DSAStack, VarsWithImplicitDSA, B);
7958   if (NestedLoopCount == 0)
7959     return StmtError();
7960 
7961   assert((CurContext->isDependentContext() || B.builtAll()) &&
7962          "omp target teams distribute parallel for simd loop exprs were not "
7963          "built");
7964 
7965   if (!CurContext->isDependentContext()) {
7966     // Finalize the clauses that need pre-built expressions for CodeGen.
7967     for (OMPClause *C : Clauses) {
7968       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7969         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7970                                      B.NumIterations, *this, CurScope,
7971                                      DSAStack))
7972           return StmtError();
7973     }
7974   }
7975 
7976   if (checkSimdlenSafelenSpecified(*this, Clauses))
7977     return StmtError();
7978 
7979   setFunctionHasBranchProtectedScope();
7980   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7981       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7982 }
7983 
7984 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7985     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7986     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7987   if (!AStmt)
7988     return StmtError();
7989 
7990   auto *CS = cast<CapturedStmt>(AStmt);
7991   // 1.2.2 OpenMP Language Terminology
7992   // Structured block - An executable statement with a single entry at the
7993   // top and a single exit at the bottom.
7994   // The point of exit cannot be a branch out of the structured block.
7995   // longjmp() and throw() must not violate the entry/exit criteria.
7996   CS->getCapturedDecl()->setNothrow();
7997   for (int ThisCaptureLevel =
7998            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7999        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8000     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8001     // 1.2.2 OpenMP Language Terminology
8002     // Structured block - An executable statement with a single entry at the
8003     // top and a single exit at the bottom.
8004     // The point of exit cannot be a branch out of the structured block.
8005     // longjmp() and throw() must not violate the entry/exit criteria.
8006     CS->getCapturedDecl()->setNothrow();
8007   }
8008 
8009   OMPLoopDirective::HelperExprs B;
8010   // In presence of clause 'collapse' with number of loops, it will
8011   // define the nested loops number.
8012   unsigned NestedLoopCount = checkOpenMPLoop(
8013       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8014       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8015       VarsWithImplicitDSA, B);
8016   if (NestedLoopCount == 0)
8017     return StmtError();
8018 
8019   assert((CurContext->isDependentContext() || B.builtAll()) &&
8020          "omp target teams distribute simd loop exprs were not built");
8021 
8022   if (!CurContext->isDependentContext()) {
8023     // Finalize the clauses that need pre-built expressions for CodeGen.
8024     for (OMPClause *C : Clauses) {
8025       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8026         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8027                                      B.NumIterations, *this, CurScope,
8028                                      DSAStack))
8029           return StmtError();
8030     }
8031   }
8032 
8033   if (checkSimdlenSafelenSpecified(*this, Clauses))
8034     return StmtError();
8035 
8036   setFunctionHasBranchProtectedScope();
8037   return OMPTargetTeamsDistributeSimdDirective::Create(
8038       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8039 }
8040 
8041 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
8042                                              SourceLocation StartLoc,
8043                                              SourceLocation LParenLoc,
8044                                              SourceLocation EndLoc) {
8045   OMPClause *Res = nullptr;
8046   switch (Kind) {
8047   case OMPC_final:
8048     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8049     break;
8050   case OMPC_num_threads:
8051     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8052     break;
8053   case OMPC_safelen:
8054     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8055     break;
8056   case OMPC_simdlen:
8057     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8058     break;
8059   case OMPC_collapse:
8060     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8061     break;
8062   case OMPC_ordered:
8063     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8064     break;
8065   case OMPC_device:
8066     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8067     break;
8068   case OMPC_num_teams:
8069     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8070     break;
8071   case OMPC_thread_limit:
8072     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8073     break;
8074   case OMPC_priority:
8075     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8076     break;
8077   case OMPC_grainsize:
8078     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8079     break;
8080   case OMPC_num_tasks:
8081     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8082     break;
8083   case OMPC_hint:
8084     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8085     break;
8086   case OMPC_if:
8087   case OMPC_default:
8088   case OMPC_proc_bind:
8089   case OMPC_schedule:
8090   case OMPC_private:
8091   case OMPC_firstprivate:
8092   case OMPC_lastprivate:
8093   case OMPC_shared:
8094   case OMPC_reduction:
8095   case OMPC_task_reduction:
8096   case OMPC_in_reduction:
8097   case OMPC_linear:
8098   case OMPC_aligned:
8099   case OMPC_copyin:
8100   case OMPC_copyprivate:
8101   case OMPC_nowait:
8102   case OMPC_untied:
8103   case OMPC_mergeable:
8104   case OMPC_threadprivate:
8105   case OMPC_flush:
8106   case OMPC_read:
8107   case OMPC_write:
8108   case OMPC_update:
8109   case OMPC_capture:
8110   case OMPC_seq_cst:
8111   case OMPC_depend:
8112   case OMPC_threads:
8113   case OMPC_simd:
8114   case OMPC_map:
8115   case OMPC_nogroup:
8116   case OMPC_dist_schedule:
8117   case OMPC_defaultmap:
8118   case OMPC_unknown:
8119   case OMPC_uniform:
8120   case OMPC_to:
8121   case OMPC_from:
8122   case OMPC_use_device_ptr:
8123   case OMPC_is_device_ptr:
8124   case OMPC_unified_address:
8125   case OMPC_unified_shared_memory:
8126   case OMPC_reverse_offload:
8127   case OMPC_dynamic_allocators:
8128     llvm_unreachable("Clause is not allowed.");
8129   }
8130   return Res;
8131 }
8132 
8133 // An OpenMP directive such as 'target parallel' has two captured regions:
8134 // for the 'target' and 'parallel' respectively.  This function returns
8135 // the region in which to capture expressions associated with a clause.
8136 // A return value of OMPD_unknown signifies that the expression should not
8137 // be captured.
8138 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8139     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8140     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
8141   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8142   switch (CKind) {
8143   case OMPC_if:
8144     switch (DKind) {
8145     case OMPD_target_parallel:
8146     case OMPD_target_parallel_for:
8147     case OMPD_target_parallel_for_simd:
8148       // If this clause applies to the nested 'parallel' region, capture within
8149       // the 'target' region, otherwise do not capture.
8150       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8151         CaptureRegion = OMPD_target;
8152       break;
8153     case OMPD_target_teams_distribute_parallel_for:
8154     case OMPD_target_teams_distribute_parallel_for_simd:
8155       // If this clause applies to the nested 'parallel' region, capture within
8156       // the 'teams' region, otherwise do not capture.
8157       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8158         CaptureRegion = OMPD_teams;
8159       break;
8160     case OMPD_teams_distribute_parallel_for:
8161     case OMPD_teams_distribute_parallel_for_simd:
8162       CaptureRegion = OMPD_teams;
8163       break;
8164     case OMPD_target_update:
8165     case OMPD_target_enter_data:
8166     case OMPD_target_exit_data:
8167       CaptureRegion = OMPD_task;
8168       break;
8169     case OMPD_cancel:
8170     case OMPD_parallel:
8171     case OMPD_parallel_sections:
8172     case OMPD_parallel_for:
8173     case OMPD_parallel_for_simd:
8174     case OMPD_target:
8175     case OMPD_target_simd:
8176     case OMPD_target_teams:
8177     case OMPD_target_teams_distribute:
8178     case OMPD_target_teams_distribute_simd:
8179     case OMPD_distribute_parallel_for:
8180     case OMPD_distribute_parallel_for_simd:
8181     case OMPD_task:
8182     case OMPD_taskloop:
8183     case OMPD_taskloop_simd:
8184     case OMPD_target_data:
8185       // Do not capture if-clause expressions.
8186       break;
8187     case OMPD_threadprivate:
8188     case OMPD_taskyield:
8189     case OMPD_barrier:
8190     case OMPD_taskwait:
8191     case OMPD_cancellation_point:
8192     case OMPD_flush:
8193     case OMPD_declare_reduction:
8194     case OMPD_declare_simd:
8195     case OMPD_declare_target:
8196     case OMPD_end_declare_target:
8197     case OMPD_teams:
8198     case OMPD_simd:
8199     case OMPD_for:
8200     case OMPD_for_simd:
8201     case OMPD_sections:
8202     case OMPD_section:
8203     case OMPD_single:
8204     case OMPD_master:
8205     case OMPD_critical:
8206     case OMPD_taskgroup:
8207     case OMPD_distribute:
8208     case OMPD_ordered:
8209     case OMPD_atomic:
8210     case OMPD_distribute_simd:
8211     case OMPD_teams_distribute:
8212     case OMPD_teams_distribute_simd:
8213     case OMPD_requires:
8214       llvm_unreachable("Unexpected OpenMP directive with if-clause");
8215     case OMPD_unknown:
8216       llvm_unreachable("Unknown OpenMP directive");
8217     }
8218     break;
8219   case OMPC_num_threads:
8220     switch (DKind) {
8221     case OMPD_target_parallel:
8222     case OMPD_target_parallel_for:
8223     case OMPD_target_parallel_for_simd:
8224       CaptureRegion = OMPD_target;
8225       break;
8226     case OMPD_teams_distribute_parallel_for:
8227     case OMPD_teams_distribute_parallel_for_simd:
8228     case OMPD_target_teams_distribute_parallel_for:
8229     case OMPD_target_teams_distribute_parallel_for_simd:
8230       CaptureRegion = OMPD_teams;
8231       break;
8232     case OMPD_parallel:
8233     case OMPD_parallel_sections:
8234     case OMPD_parallel_for:
8235     case OMPD_parallel_for_simd:
8236     case OMPD_distribute_parallel_for:
8237     case OMPD_distribute_parallel_for_simd:
8238       // Do not capture num_threads-clause expressions.
8239       break;
8240     case OMPD_target_data:
8241     case OMPD_target_enter_data:
8242     case OMPD_target_exit_data:
8243     case OMPD_target_update:
8244     case OMPD_target:
8245     case OMPD_target_simd:
8246     case OMPD_target_teams:
8247     case OMPD_target_teams_distribute:
8248     case OMPD_target_teams_distribute_simd:
8249     case OMPD_cancel:
8250     case OMPD_task:
8251     case OMPD_taskloop:
8252     case OMPD_taskloop_simd:
8253     case OMPD_threadprivate:
8254     case OMPD_taskyield:
8255     case OMPD_barrier:
8256     case OMPD_taskwait:
8257     case OMPD_cancellation_point:
8258     case OMPD_flush:
8259     case OMPD_declare_reduction:
8260     case OMPD_declare_simd:
8261     case OMPD_declare_target:
8262     case OMPD_end_declare_target:
8263     case OMPD_teams:
8264     case OMPD_simd:
8265     case OMPD_for:
8266     case OMPD_for_simd:
8267     case OMPD_sections:
8268     case OMPD_section:
8269     case OMPD_single:
8270     case OMPD_master:
8271     case OMPD_critical:
8272     case OMPD_taskgroup:
8273     case OMPD_distribute:
8274     case OMPD_ordered:
8275     case OMPD_atomic:
8276     case OMPD_distribute_simd:
8277     case OMPD_teams_distribute:
8278     case OMPD_teams_distribute_simd:
8279     case OMPD_requires:
8280       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8281     case OMPD_unknown:
8282       llvm_unreachable("Unknown OpenMP directive");
8283     }
8284     break;
8285   case OMPC_num_teams:
8286     switch (DKind) {
8287     case OMPD_target_teams:
8288     case OMPD_target_teams_distribute:
8289     case OMPD_target_teams_distribute_simd:
8290     case OMPD_target_teams_distribute_parallel_for:
8291     case OMPD_target_teams_distribute_parallel_for_simd:
8292       CaptureRegion = OMPD_target;
8293       break;
8294     case OMPD_teams_distribute_parallel_for:
8295     case OMPD_teams_distribute_parallel_for_simd:
8296     case OMPD_teams:
8297     case OMPD_teams_distribute:
8298     case OMPD_teams_distribute_simd:
8299       // Do not capture num_teams-clause expressions.
8300       break;
8301     case OMPD_distribute_parallel_for:
8302     case OMPD_distribute_parallel_for_simd:
8303     case OMPD_task:
8304     case OMPD_taskloop:
8305     case OMPD_taskloop_simd:
8306     case OMPD_target_data:
8307     case OMPD_target_enter_data:
8308     case OMPD_target_exit_data:
8309     case OMPD_target_update:
8310     case OMPD_cancel:
8311     case OMPD_parallel:
8312     case OMPD_parallel_sections:
8313     case OMPD_parallel_for:
8314     case OMPD_parallel_for_simd:
8315     case OMPD_target:
8316     case OMPD_target_simd:
8317     case OMPD_target_parallel:
8318     case OMPD_target_parallel_for:
8319     case OMPD_target_parallel_for_simd:
8320     case OMPD_threadprivate:
8321     case OMPD_taskyield:
8322     case OMPD_barrier:
8323     case OMPD_taskwait:
8324     case OMPD_cancellation_point:
8325     case OMPD_flush:
8326     case OMPD_declare_reduction:
8327     case OMPD_declare_simd:
8328     case OMPD_declare_target:
8329     case OMPD_end_declare_target:
8330     case OMPD_simd:
8331     case OMPD_for:
8332     case OMPD_for_simd:
8333     case OMPD_sections:
8334     case OMPD_section:
8335     case OMPD_single:
8336     case OMPD_master:
8337     case OMPD_critical:
8338     case OMPD_taskgroup:
8339     case OMPD_distribute:
8340     case OMPD_ordered:
8341     case OMPD_atomic:
8342     case OMPD_distribute_simd:
8343     case OMPD_requires:
8344       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8345     case OMPD_unknown:
8346       llvm_unreachable("Unknown OpenMP directive");
8347     }
8348     break;
8349   case OMPC_thread_limit:
8350     switch (DKind) {
8351     case OMPD_target_teams:
8352     case OMPD_target_teams_distribute:
8353     case OMPD_target_teams_distribute_simd:
8354     case OMPD_target_teams_distribute_parallel_for:
8355     case OMPD_target_teams_distribute_parallel_for_simd:
8356       CaptureRegion = OMPD_target;
8357       break;
8358     case OMPD_teams_distribute_parallel_for:
8359     case OMPD_teams_distribute_parallel_for_simd:
8360     case OMPD_teams:
8361     case OMPD_teams_distribute:
8362     case OMPD_teams_distribute_simd:
8363       // Do not capture thread_limit-clause expressions.
8364       break;
8365     case OMPD_distribute_parallel_for:
8366     case OMPD_distribute_parallel_for_simd:
8367     case OMPD_task:
8368     case OMPD_taskloop:
8369     case OMPD_taskloop_simd:
8370     case OMPD_target_data:
8371     case OMPD_target_enter_data:
8372     case OMPD_target_exit_data:
8373     case OMPD_target_update:
8374     case OMPD_cancel:
8375     case OMPD_parallel:
8376     case OMPD_parallel_sections:
8377     case OMPD_parallel_for:
8378     case OMPD_parallel_for_simd:
8379     case OMPD_target:
8380     case OMPD_target_simd:
8381     case OMPD_target_parallel:
8382     case OMPD_target_parallel_for:
8383     case OMPD_target_parallel_for_simd:
8384     case OMPD_threadprivate:
8385     case OMPD_taskyield:
8386     case OMPD_barrier:
8387     case OMPD_taskwait:
8388     case OMPD_cancellation_point:
8389     case OMPD_flush:
8390     case OMPD_declare_reduction:
8391     case OMPD_declare_simd:
8392     case OMPD_declare_target:
8393     case OMPD_end_declare_target:
8394     case OMPD_simd:
8395     case OMPD_for:
8396     case OMPD_for_simd:
8397     case OMPD_sections:
8398     case OMPD_section:
8399     case OMPD_single:
8400     case OMPD_master:
8401     case OMPD_critical:
8402     case OMPD_taskgroup:
8403     case OMPD_distribute:
8404     case OMPD_ordered:
8405     case OMPD_atomic:
8406     case OMPD_distribute_simd:
8407     case OMPD_requires:
8408       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8409     case OMPD_unknown:
8410       llvm_unreachable("Unknown OpenMP directive");
8411     }
8412     break;
8413   case OMPC_schedule:
8414     switch (DKind) {
8415     case OMPD_parallel_for:
8416     case OMPD_parallel_for_simd:
8417     case OMPD_distribute_parallel_for:
8418     case OMPD_distribute_parallel_for_simd:
8419     case OMPD_teams_distribute_parallel_for:
8420     case OMPD_teams_distribute_parallel_for_simd:
8421     case OMPD_target_parallel_for:
8422     case OMPD_target_parallel_for_simd:
8423     case OMPD_target_teams_distribute_parallel_for:
8424     case OMPD_target_teams_distribute_parallel_for_simd:
8425       CaptureRegion = OMPD_parallel;
8426       break;
8427     case OMPD_for:
8428     case OMPD_for_simd:
8429       // Do not capture schedule-clause expressions.
8430       break;
8431     case OMPD_task:
8432     case OMPD_taskloop:
8433     case OMPD_taskloop_simd:
8434     case OMPD_target_data:
8435     case OMPD_target_enter_data:
8436     case OMPD_target_exit_data:
8437     case OMPD_target_update:
8438     case OMPD_teams:
8439     case OMPD_teams_distribute:
8440     case OMPD_teams_distribute_simd:
8441     case OMPD_target_teams_distribute:
8442     case OMPD_target_teams_distribute_simd:
8443     case OMPD_target:
8444     case OMPD_target_simd:
8445     case OMPD_target_parallel:
8446     case OMPD_cancel:
8447     case OMPD_parallel:
8448     case OMPD_parallel_sections:
8449     case OMPD_threadprivate:
8450     case OMPD_taskyield:
8451     case OMPD_barrier:
8452     case OMPD_taskwait:
8453     case OMPD_cancellation_point:
8454     case OMPD_flush:
8455     case OMPD_declare_reduction:
8456     case OMPD_declare_simd:
8457     case OMPD_declare_target:
8458     case OMPD_end_declare_target:
8459     case OMPD_simd:
8460     case OMPD_sections:
8461     case OMPD_section:
8462     case OMPD_single:
8463     case OMPD_master:
8464     case OMPD_critical:
8465     case OMPD_taskgroup:
8466     case OMPD_distribute:
8467     case OMPD_ordered:
8468     case OMPD_atomic:
8469     case OMPD_distribute_simd:
8470     case OMPD_target_teams:
8471     case OMPD_requires:
8472       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8473     case OMPD_unknown:
8474       llvm_unreachable("Unknown OpenMP directive");
8475     }
8476     break;
8477   case OMPC_dist_schedule:
8478     switch (DKind) {
8479     case OMPD_teams_distribute_parallel_for:
8480     case OMPD_teams_distribute_parallel_for_simd:
8481     case OMPD_teams_distribute:
8482     case OMPD_teams_distribute_simd:
8483     case OMPD_target_teams_distribute_parallel_for:
8484     case OMPD_target_teams_distribute_parallel_for_simd:
8485     case OMPD_target_teams_distribute:
8486     case OMPD_target_teams_distribute_simd:
8487       CaptureRegion = OMPD_teams;
8488       break;
8489     case OMPD_distribute_parallel_for:
8490     case OMPD_distribute_parallel_for_simd:
8491     case OMPD_distribute:
8492     case OMPD_distribute_simd:
8493       // Do not capture thread_limit-clause expressions.
8494       break;
8495     case OMPD_parallel_for:
8496     case OMPD_parallel_for_simd:
8497     case OMPD_target_parallel_for_simd:
8498     case OMPD_target_parallel_for:
8499     case OMPD_task:
8500     case OMPD_taskloop:
8501     case OMPD_taskloop_simd:
8502     case OMPD_target_data:
8503     case OMPD_target_enter_data:
8504     case OMPD_target_exit_data:
8505     case OMPD_target_update:
8506     case OMPD_teams:
8507     case OMPD_target:
8508     case OMPD_target_simd:
8509     case OMPD_target_parallel:
8510     case OMPD_cancel:
8511     case OMPD_parallel:
8512     case OMPD_parallel_sections:
8513     case OMPD_threadprivate:
8514     case OMPD_taskyield:
8515     case OMPD_barrier:
8516     case OMPD_taskwait:
8517     case OMPD_cancellation_point:
8518     case OMPD_flush:
8519     case OMPD_declare_reduction:
8520     case OMPD_declare_simd:
8521     case OMPD_declare_target:
8522     case OMPD_end_declare_target:
8523     case OMPD_simd:
8524     case OMPD_for:
8525     case OMPD_for_simd:
8526     case OMPD_sections:
8527     case OMPD_section:
8528     case OMPD_single:
8529     case OMPD_master:
8530     case OMPD_critical:
8531     case OMPD_taskgroup:
8532     case OMPD_ordered:
8533     case OMPD_atomic:
8534     case OMPD_target_teams:
8535     case OMPD_requires:
8536       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8537     case OMPD_unknown:
8538       llvm_unreachable("Unknown OpenMP directive");
8539     }
8540     break;
8541   case OMPC_device:
8542     switch (DKind) {
8543     case OMPD_target_update:
8544     case OMPD_target_enter_data:
8545     case OMPD_target_exit_data:
8546     case OMPD_target:
8547     case OMPD_target_simd:
8548     case OMPD_target_teams:
8549     case OMPD_target_parallel:
8550     case OMPD_target_teams_distribute:
8551     case OMPD_target_teams_distribute_simd:
8552     case OMPD_target_parallel_for:
8553     case OMPD_target_parallel_for_simd:
8554     case OMPD_target_teams_distribute_parallel_for:
8555     case OMPD_target_teams_distribute_parallel_for_simd:
8556       CaptureRegion = OMPD_task;
8557       break;
8558     case OMPD_target_data:
8559       // Do not capture device-clause expressions.
8560       break;
8561     case OMPD_teams_distribute_parallel_for:
8562     case OMPD_teams_distribute_parallel_for_simd:
8563     case OMPD_teams:
8564     case OMPD_teams_distribute:
8565     case OMPD_teams_distribute_simd:
8566     case OMPD_distribute_parallel_for:
8567     case OMPD_distribute_parallel_for_simd:
8568     case OMPD_task:
8569     case OMPD_taskloop:
8570     case OMPD_taskloop_simd:
8571     case OMPD_cancel:
8572     case OMPD_parallel:
8573     case OMPD_parallel_sections:
8574     case OMPD_parallel_for:
8575     case OMPD_parallel_for_simd:
8576     case OMPD_threadprivate:
8577     case OMPD_taskyield:
8578     case OMPD_barrier:
8579     case OMPD_taskwait:
8580     case OMPD_cancellation_point:
8581     case OMPD_flush:
8582     case OMPD_declare_reduction:
8583     case OMPD_declare_simd:
8584     case OMPD_declare_target:
8585     case OMPD_end_declare_target:
8586     case OMPD_simd:
8587     case OMPD_for:
8588     case OMPD_for_simd:
8589     case OMPD_sections:
8590     case OMPD_section:
8591     case OMPD_single:
8592     case OMPD_master:
8593     case OMPD_critical:
8594     case OMPD_taskgroup:
8595     case OMPD_distribute:
8596     case OMPD_ordered:
8597     case OMPD_atomic:
8598     case OMPD_distribute_simd:
8599     case OMPD_requires:
8600       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8601     case OMPD_unknown:
8602       llvm_unreachable("Unknown OpenMP directive");
8603     }
8604     break;
8605   case OMPC_firstprivate:
8606   case OMPC_lastprivate:
8607   case OMPC_reduction:
8608   case OMPC_task_reduction:
8609   case OMPC_in_reduction:
8610   case OMPC_linear:
8611   case OMPC_default:
8612   case OMPC_proc_bind:
8613   case OMPC_final:
8614   case OMPC_safelen:
8615   case OMPC_simdlen:
8616   case OMPC_collapse:
8617   case OMPC_private:
8618   case OMPC_shared:
8619   case OMPC_aligned:
8620   case OMPC_copyin:
8621   case OMPC_copyprivate:
8622   case OMPC_ordered:
8623   case OMPC_nowait:
8624   case OMPC_untied:
8625   case OMPC_mergeable:
8626   case OMPC_threadprivate:
8627   case OMPC_flush:
8628   case OMPC_read:
8629   case OMPC_write:
8630   case OMPC_update:
8631   case OMPC_capture:
8632   case OMPC_seq_cst:
8633   case OMPC_depend:
8634   case OMPC_threads:
8635   case OMPC_simd:
8636   case OMPC_map:
8637   case OMPC_priority:
8638   case OMPC_grainsize:
8639   case OMPC_nogroup:
8640   case OMPC_num_tasks:
8641   case OMPC_hint:
8642   case OMPC_defaultmap:
8643   case OMPC_unknown:
8644   case OMPC_uniform:
8645   case OMPC_to:
8646   case OMPC_from:
8647   case OMPC_use_device_ptr:
8648   case OMPC_is_device_ptr:
8649   case OMPC_unified_address:
8650   case OMPC_unified_shared_memory:
8651   case OMPC_reverse_offload:
8652   case OMPC_dynamic_allocators:
8653     llvm_unreachable("Unexpected OpenMP clause.");
8654   }
8655   return CaptureRegion;
8656 }
8657 
8658 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8659                                      Expr *Condition, SourceLocation StartLoc,
8660                                      SourceLocation LParenLoc,
8661                                      SourceLocation NameModifierLoc,
8662                                      SourceLocation ColonLoc,
8663                                      SourceLocation EndLoc) {
8664   Expr *ValExpr = Condition;
8665   Stmt *HelperValStmt = nullptr;
8666   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8667   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8668       !Condition->isInstantiationDependent() &&
8669       !Condition->containsUnexpandedParameterPack()) {
8670     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8671     if (Val.isInvalid())
8672       return nullptr;
8673 
8674     ValExpr = Val.get();
8675 
8676     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8677     CaptureRegion =
8678         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8679     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8680       ValExpr = MakeFullExpr(ValExpr).get();
8681       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8682       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8683       HelperValStmt = buildPreInits(Context, Captures);
8684     }
8685   }
8686 
8687   return new (Context)
8688       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8689                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8690 }
8691 
8692 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8693                                         SourceLocation StartLoc,
8694                                         SourceLocation LParenLoc,
8695                                         SourceLocation EndLoc) {
8696   Expr *ValExpr = Condition;
8697   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8698       !Condition->isInstantiationDependent() &&
8699       !Condition->containsUnexpandedParameterPack()) {
8700     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8701     if (Val.isInvalid())
8702       return nullptr;
8703 
8704     ValExpr = MakeFullExpr(Val.get()).get();
8705   }
8706 
8707   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8708 }
8709 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8710                                                         Expr *Op) {
8711   if (!Op)
8712     return ExprError();
8713 
8714   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8715   public:
8716     IntConvertDiagnoser()
8717         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8718     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8719                                          QualType T) override {
8720       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8721     }
8722     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8723                                              QualType T) override {
8724       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8725     }
8726     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8727                                                QualType T,
8728                                                QualType ConvTy) override {
8729       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8730     }
8731     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8732                                            QualType ConvTy) override {
8733       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8734              << ConvTy->isEnumeralType() << ConvTy;
8735     }
8736     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8737                                             QualType T) override {
8738       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8739     }
8740     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8741                                         QualType ConvTy) override {
8742       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8743              << ConvTy->isEnumeralType() << ConvTy;
8744     }
8745     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8746                                              QualType) override {
8747       llvm_unreachable("conversion functions are permitted");
8748     }
8749   } ConvertDiagnoser;
8750   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8751 }
8752 
8753 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8754                                       OpenMPClauseKind CKind,
8755                                       bool StrictlyPositive) {
8756   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8757       !ValExpr->isInstantiationDependent()) {
8758     SourceLocation Loc = ValExpr->getExprLoc();
8759     ExprResult Value =
8760         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8761     if (Value.isInvalid())
8762       return false;
8763 
8764     ValExpr = Value.get();
8765     // The expression must evaluate to a non-negative integer value.
8766     llvm::APSInt Result;
8767     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8768         Result.isSigned() &&
8769         !((!StrictlyPositive && Result.isNonNegative()) ||
8770           (StrictlyPositive && Result.isStrictlyPositive()))) {
8771       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8772           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8773           << ValExpr->getSourceRange();
8774       return false;
8775     }
8776   }
8777   return true;
8778 }
8779 
8780 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8781                                              SourceLocation StartLoc,
8782                                              SourceLocation LParenLoc,
8783                                              SourceLocation EndLoc) {
8784   Expr *ValExpr = NumThreads;
8785   Stmt *HelperValStmt = nullptr;
8786 
8787   // OpenMP [2.5, Restrictions]
8788   //  The num_threads expression must evaluate to a positive integer value.
8789   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8790                                  /*StrictlyPositive=*/true))
8791     return nullptr;
8792 
8793   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8794   OpenMPDirectiveKind CaptureRegion =
8795       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8796   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8797     ValExpr = MakeFullExpr(ValExpr).get();
8798     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8799     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8800     HelperValStmt = buildPreInits(Context, Captures);
8801   }
8802 
8803   return new (Context) OMPNumThreadsClause(
8804       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8805 }
8806 
8807 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8808                                                        OpenMPClauseKind CKind,
8809                                                        bool StrictlyPositive) {
8810   if (!E)
8811     return ExprError();
8812   if (E->isValueDependent() || E->isTypeDependent() ||
8813       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8814     return E;
8815   llvm::APSInt Result;
8816   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8817   if (ICE.isInvalid())
8818     return ExprError();
8819   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8820       (!StrictlyPositive && !Result.isNonNegative())) {
8821     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8822         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8823         << E->getSourceRange();
8824     return ExprError();
8825   }
8826   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8827     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8828         << E->getSourceRange();
8829     return ExprError();
8830   }
8831   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8832     DSAStack->setAssociatedLoops(Result.getExtValue());
8833   else if (CKind == OMPC_ordered)
8834     DSAStack->setAssociatedLoops(Result.getExtValue());
8835   return ICE;
8836 }
8837 
8838 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8839                                           SourceLocation LParenLoc,
8840                                           SourceLocation EndLoc) {
8841   // OpenMP [2.8.1, simd construct, Description]
8842   // The parameter of the safelen clause must be a constant
8843   // positive integer expression.
8844   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8845   if (Safelen.isInvalid())
8846     return nullptr;
8847   return new (Context)
8848       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8849 }
8850 
8851 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8852                                           SourceLocation LParenLoc,
8853                                           SourceLocation EndLoc) {
8854   // OpenMP [2.8.1, simd construct, Description]
8855   // The parameter of the simdlen clause must be a constant
8856   // positive integer expression.
8857   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8858   if (Simdlen.isInvalid())
8859     return nullptr;
8860   return new (Context)
8861       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8862 }
8863 
8864 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8865                                            SourceLocation StartLoc,
8866                                            SourceLocation LParenLoc,
8867                                            SourceLocation EndLoc) {
8868   // OpenMP [2.7.1, loop construct, Description]
8869   // OpenMP [2.8.1, simd construct, Description]
8870   // OpenMP [2.9.6, distribute construct, Description]
8871   // The parameter of the collapse clause must be a constant
8872   // positive integer expression.
8873   ExprResult NumForLoopsResult =
8874       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8875   if (NumForLoopsResult.isInvalid())
8876     return nullptr;
8877   return new (Context)
8878       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
8879 }
8880 
8881 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8882                                           SourceLocation EndLoc,
8883                                           SourceLocation LParenLoc,
8884                                           Expr *NumForLoops) {
8885   // OpenMP [2.7.1, loop construct, Description]
8886   // OpenMP [2.8.1, simd construct, Description]
8887   // OpenMP [2.9.6, distribute construct, Description]
8888   // The parameter of the ordered clause must be a constant
8889   // positive integer expression if any.
8890   if (NumForLoops && LParenLoc.isValid()) {
8891     ExprResult NumForLoopsResult =
8892         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8893     if (NumForLoopsResult.isInvalid())
8894       return nullptr;
8895     NumForLoops = NumForLoopsResult.get();
8896   } else {
8897     NumForLoops = nullptr;
8898   }
8899   auto *Clause = OMPOrderedClause::Create(
8900       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
8901       StartLoc, LParenLoc, EndLoc);
8902   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
8903   return Clause;
8904 }
8905 
8906 OMPClause *Sema::ActOnOpenMPSimpleClause(
8907     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8908     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8909   OMPClause *Res = nullptr;
8910   switch (Kind) {
8911   case OMPC_default:
8912     Res =
8913         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8914                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
8915     break;
8916   case OMPC_proc_bind:
8917     Res = ActOnOpenMPProcBindClause(
8918         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8919         LParenLoc, EndLoc);
8920     break;
8921   case OMPC_if:
8922   case OMPC_final:
8923   case OMPC_num_threads:
8924   case OMPC_safelen:
8925   case OMPC_simdlen:
8926   case OMPC_collapse:
8927   case OMPC_schedule:
8928   case OMPC_private:
8929   case OMPC_firstprivate:
8930   case OMPC_lastprivate:
8931   case OMPC_shared:
8932   case OMPC_reduction:
8933   case OMPC_task_reduction:
8934   case OMPC_in_reduction:
8935   case OMPC_linear:
8936   case OMPC_aligned:
8937   case OMPC_copyin:
8938   case OMPC_copyprivate:
8939   case OMPC_ordered:
8940   case OMPC_nowait:
8941   case OMPC_untied:
8942   case OMPC_mergeable:
8943   case OMPC_threadprivate:
8944   case OMPC_flush:
8945   case OMPC_read:
8946   case OMPC_write:
8947   case OMPC_update:
8948   case OMPC_capture:
8949   case OMPC_seq_cst:
8950   case OMPC_depend:
8951   case OMPC_device:
8952   case OMPC_threads:
8953   case OMPC_simd:
8954   case OMPC_map:
8955   case OMPC_num_teams:
8956   case OMPC_thread_limit:
8957   case OMPC_priority:
8958   case OMPC_grainsize:
8959   case OMPC_nogroup:
8960   case OMPC_num_tasks:
8961   case OMPC_hint:
8962   case OMPC_dist_schedule:
8963   case OMPC_defaultmap:
8964   case OMPC_unknown:
8965   case OMPC_uniform:
8966   case OMPC_to:
8967   case OMPC_from:
8968   case OMPC_use_device_ptr:
8969   case OMPC_is_device_ptr:
8970   case OMPC_unified_address:
8971   case OMPC_unified_shared_memory:
8972   case OMPC_reverse_offload:
8973   case OMPC_dynamic_allocators:
8974     llvm_unreachable("Clause is not allowed.");
8975   }
8976   return Res;
8977 }
8978 
8979 static std::string
8980 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8981                         ArrayRef<unsigned> Exclude = llvm::None) {
8982   SmallString<256> Buffer;
8983   llvm::raw_svector_ostream Out(Buffer);
8984   unsigned Bound = Last >= 2 ? Last - 2 : 0;
8985   unsigned Skipped = Exclude.size();
8986   auto S = Exclude.begin(), E = Exclude.end();
8987   for (unsigned I = First; I < Last; ++I) {
8988     if (std::find(S, E, I) != E) {
8989       --Skipped;
8990       continue;
8991     }
8992     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
8993     if (I == Bound - Skipped)
8994       Out << " or ";
8995     else if (I != Bound + 1 - Skipped)
8996       Out << ", ";
8997   }
8998   return Out.str();
8999 }
9000 
9001 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9002                                           SourceLocation KindKwLoc,
9003                                           SourceLocation StartLoc,
9004                                           SourceLocation LParenLoc,
9005                                           SourceLocation EndLoc) {
9006   if (Kind == OMPC_DEFAULT_unknown) {
9007     static_assert(OMPC_DEFAULT_unknown > 0,
9008                   "OMPC_DEFAULT_unknown not greater than 0");
9009     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9010         << getListOfPossibleValues(OMPC_default, /*First=*/0,
9011                                    /*Last=*/OMPC_DEFAULT_unknown)
9012         << getOpenMPClauseName(OMPC_default);
9013     return nullptr;
9014   }
9015   switch (Kind) {
9016   case OMPC_DEFAULT_none:
9017     DSAStack->setDefaultDSANone(KindKwLoc);
9018     break;
9019   case OMPC_DEFAULT_shared:
9020     DSAStack->setDefaultDSAShared(KindKwLoc);
9021     break;
9022   case OMPC_DEFAULT_unknown:
9023     llvm_unreachable("Clause kind is not allowed.");
9024     break;
9025   }
9026   return new (Context)
9027       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9028 }
9029 
9030 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9031                                            SourceLocation KindKwLoc,
9032                                            SourceLocation StartLoc,
9033                                            SourceLocation LParenLoc,
9034                                            SourceLocation EndLoc) {
9035   if (Kind == OMPC_PROC_BIND_unknown) {
9036     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9037         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9038                                    /*Last=*/OMPC_PROC_BIND_unknown)
9039         << getOpenMPClauseName(OMPC_proc_bind);
9040     return nullptr;
9041   }
9042   return new (Context)
9043       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9044 }
9045 
9046 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
9047     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
9048     SourceLocation StartLoc, SourceLocation LParenLoc,
9049     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
9050     SourceLocation EndLoc) {
9051   OMPClause *Res = nullptr;
9052   switch (Kind) {
9053   case OMPC_schedule:
9054     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9055     assert(Argument.size() == NumberOfElements &&
9056            ArgumentLoc.size() == NumberOfElements);
9057     Res = ActOnOpenMPScheduleClause(
9058         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9059         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9060         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9061         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9062         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
9063     break;
9064   case OMPC_if:
9065     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9066     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9067                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9068                               DelimLoc, EndLoc);
9069     break;
9070   case OMPC_dist_schedule:
9071     Res = ActOnOpenMPDistScheduleClause(
9072         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9073         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9074     break;
9075   case OMPC_defaultmap:
9076     enum { Modifier, DefaultmapKind };
9077     Res = ActOnOpenMPDefaultmapClause(
9078         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9079         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
9080         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9081         EndLoc);
9082     break;
9083   case OMPC_final:
9084   case OMPC_num_threads:
9085   case OMPC_safelen:
9086   case OMPC_simdlen:
9087   case OMPC_collapse:
9088   case OMPC_default:
9089   case OMPC_proc_bind:
9090   case OMPC_private:
9091   case OMPC_firstprivate:
9092   case OMPC_lastprivate:
9093   case OMPC_shared:
9094   case OMPC_reduction:
9095   case OMPC_task_reduction:
9096   case OMPC_in_reduction:
9097   case OMPC_linear:
9098   case OMPC_aligned:
9099   case OMPC_copyin:
9100   case OMPC_copyprivate:
9101   case OMPC_ordered:
9102   case OMPC_nowait:
9103   case OMPC_untied:
9104   case OMPC_mergeable:
9105   case OMPC_threadprivate:
9106   case OMPC_flush:
9107   case OMPC_read:
9108   case OMPC_write:
9109   case OMPC_update:
9110   case OMPC_capture:
9111   case OMPC_seq_cst:
9112   case OMPC_depend:
9113   case OMPC_device:
9114   case OMPC_threads:
9115   case OMPC_simd:
9116   case OMPC_map:
9117   case OMPC_num_teams:
9118   case OMPC_thread_limit:
9119   case OMPC_priority:
9120   case OMPC_grainsize:
9121   case OMPC_nogroup:
9122   case OMPC_num_tasks:
9123   case OMPC_hint:
9124   case OMPC_unknown:
9125   case OMPC_uniform:
9126   case OMPC_to:
9127   case OMPC_from:
9128   case OMPC_use_device_ptr:
9129   case OMPC_is_device_ptr:
9130   case OMPC_unified_address:
9131   case OMPC_unified_shared_memory:
9132   case OMPC_reverse_offload:
9133   case OMPC_dynamic_allocators:
9134     llvm_unreachable("Clause is not allowed.");
9135   }
9136   return Res;
9137 }
9138 
9139 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9140                                    OpenMPScheduleClauseModifier M2,
9141                                    SourceLocation M1Loc, SourceLocation M2Loc) {
9142   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9143     SmallVector<unsigned, 2> Excluded;
9144     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9145       Excluded.push_back(M2);
9146     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9147       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9148     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9149       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9150     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9151         << getListOfPossibleValues(OMPC_schedule,
9152                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9153                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9154                                    Excluded)
9155         << getOpenMPClauseName(OMPC_schedule);
9156     return true;
9157   }
9158   return false;
9159 }
9160 
9161 OMPClause *Sema::ActOnOpenMPScheduleClause(
9162     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9163     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9164     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9165     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9166   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9167       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9168     return nullptr;
9169   // OpenMP, 2.7.1, Loop Construct, Restrictions
9170   // Either the monotonic modifier or the nonmonotonic modifier can be specified
9171   // but not both.
9172   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9173       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9174        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9175       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9176        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9177     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9178         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9179         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9180     return nullptr;
9181   }
9182   if (Kind == OMPC_SCHEDULE_unknown) {
9183     std::string Values;
9184     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9185       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9186       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9187                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9188                                        Exclude);
9189     } else {
9190       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9191                                        /*Last=*/OMPC_SCHEDULE_unknown);
9192     }
9193     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9194         << Values << getOpenMPClauseName(OMPC_schedule);
9195     return nullptr;
9196   }
9197   // OpenMP, 2.7.1, Loop Construct, Restrictions
9198   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9199   // schedule(guided).
9200   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9201        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9202       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9203     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9204          diag::err_omp_schedule_nonmonotonic_static);
9205     return nullptr;
9206   }
9207   Expr *ValExpr = ChunkSize;
9208   Stmt *HelperValStmt = nullptr;
9209   if (ChunkSize) {
9210     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9211         !ChunkSize->isInstantiationDependent() &&
9212         !ChunkSize->containsUnexpandedParameterPack()) {
9213       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
9214       ExprResult Val =
9215           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9216       if (Val.isInvalid())
9217         return nullptr;
9218 
9219       ValExpr = Val.get();
9220 
9221       // OpenMP [2.7.1, Restrictions]
9222       //  chunk_size must be a loop invariant integer expression with a positive
9223       //  value.
9224       llvm::APSInt Result;
9225       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9226         if (Result.isSigned() && !Result.isStrictlyPositive()) {
9227           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
9228               << "schedule" << 1 << ChunkSize->getSourceRange();
9229           return nullptr;
9230         }
9231       } else if (getOpenMPCaptureRegionForClause(
9232                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
9233                      OMPD_unknown &&
9234                  !CurContext->isDependentContext()) {
9235         ValExpr = MakeFullExpr(ValExpr).get();
9236         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9237         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9238         HelperValStmt = buildPreInits(Context, Captures);
9239       }
9240     }
9241   }
9242 
9243   return new (Context)
9244       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
9245                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
9246 }
9247 
9248 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9249                                    SourceLocation StartLoc,
9250                                    SourceLocation EndLoc) {
9251   OMPClause *Res = nullptr;
9252   switch (Kind) {
9253   case OMPC_ordered:
9254     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9255     break;
9256   case OMPC_nowait:
9257     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9258     break;
9259   case OMPC_untied:
9260     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9261     break;
9262   case OMPC_mergeable:
9263     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9264     break;
9265   case OMPC_read:
9266     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9267     break;
9268   case OMPC_write:
9269     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9270     break;
9271   case OMPC_update:
9272     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9273     break;
9274   case OMPC_capture:
9275     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9276     break;
9277   case OMPC_seq_cst:
9278     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9279     break;
9280   case OMPC_threads:
9281     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9282     break;
9283   case OMPC_simd:
9284     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9285     break;
9286   case OMPC_nogroup:
9287     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9288     break;
9289   case OMPC_unified_address:
9290     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9291     break;
9292   case OMPC_unified_shared_memory:
9293     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9294     break;
9295   case OMPC_reverse_offload:
9296     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9297     break;
9298   case OMPC_dynamic_allocators:
9299     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9300     break;
9301   case OMPC_if:
9302   case OMPC_final:
9303   case OMPC_num_threads:
9304   case OMPC_safelen:
9305   case OMPC_simdlen:
9306   case OMPC_collapse:
9307   case OMPC_schedule:
9308   case OMPC_private:
9309   case OMPC_firstprivate:
9310   case OMPC_lastprivate:
9311   case OMPC_shared:
9312   case OMPC_reduction:
9313   case OMPC_task_reduction:
9314   case OMPC_in_reduction:
9315   case OMPC_linear:
9316   case OMPC_aligned:
9317   case OMPC_copyin:
9318   case OMPC_copyprivate:
9319   case OMPC_default:
9320   case OMPC_proc_bind:
9321   case OMPC_threadprivate:
9322   case OMPC_flush:
9323   case OMPC_depend:
9324   case OMPC_device:
9325   case OMPC_map:
9326   case OMPC_num_teams:
9327   case OMPC_thread_limit:
9328   case OMPC_priority:
9329   case OMPC_grainsize:
9330   case OMPC_num_tasks:
9331   case OMPC_hint:
9332   case OMPC_dist_schedule:
9333   case OMPC_defaultmap:
9334   case OMPC_unknown:
9335   case OMPC_uniform:
9336   case OMPC_to:
9337   case OMPC_from:
9338   case OMPC_use_device_ptr:
9339   case OMPC_is_device_ptr:
9340     llvm_unreachable("Clause is not allowed.");
9341   }
9342   return Res;
9343 }
9344 
9345 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9346                                          SourceLocation EndLoc) {
9347   DSAStack->setNowaitRegion();
9348   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9349 }
9350 
9351 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9352                                          SourceLocation EndLoc) {
9353   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9354 }
9355 
9356 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9357                                             SourceLocation EndLoc) {
9358   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9359 }
9360 
9361 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9362                                        SourceLocation EndLoc) {
9363   return new (Context) OMPReadClause(StartLoc, EndLoc);
9364 }
9365 
9366 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9367                                         SourceLocation EndLoc) {
9368   return new (Context) OMPWriteClause(StartLoc, EndLoc);
9369 }
9370 
9371 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9372                                          SourceLocation EndLoc) {
9373   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9374 }
9375 
9376 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9377                                           SourceLocation EndLoc) {
9378   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9379 }
9380 
9381 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9382                                          SourceLocation EndLoc) {
9383   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9384 }
9385 
9386 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9387                                           SourceLocation EndLoc) {
9388   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9389 }
9390 
9391 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9392                                        SourceLocation EndLoc) {
9393   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9394 }
9395 
9396 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9397                                           SourceLocation EndLoc) {
9398   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9399 }
9400 
9401 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9402                                                  SourceLocation EndLoc) {
9403   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9404 }
9405 
9406 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9407                                                       SourceLocation EndLoc) {
9408   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9409 }
9410 
9411 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9412                                                  SourceLocation EndLoc) {
9413   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9414 }
9415 
9416 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9417                                                     SourceLocation EndLoc) {
9418   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9419 }
9420 
9421 OMPClause *Sema::ActOnOpenMPVarListClause(
9422     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9423     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9424     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
9425     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9426     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9427     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9428     SourceLocation DepLinMapLoc) {
9429   OMPClause *Res = nullptr;
9430   switch (Kind) {
9431   case OMPC_private:
9432     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9433     break;
9434   case OMPC_firstprivate:
9435     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9436     break;
9437   case OMPC_lastprivate:
9438     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9439     break;
9440   case OMPC_shared:
9441     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9442     break;
9443   case OMPC_reduction:
9444     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9445                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9446     break;
9447   case OMPC_task_reduction:
9448     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9449                                          EndLoc, ReductionIdScopeSpec,
9450                                          ReductionId);
9451     break;
9452   case OMPC_in_reduction:
9453     Res =
9454         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9455                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9456     break;
9457   case OMPC_linear:
9458     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
9459                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
9460     break;
9461   case OMPC_aligned:
9462     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9463                                    ColonLoc, EndLoc);
9464     break;
9465   case OMPC_copyin:
9466     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9467     break;
9468   case OMPC_copyprivate:
9469     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9470     break;
9471   case OMPC_flush:
9472     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9473     break;
9474   case OMPC_depend:
9475     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9476                                   StartLoc, LParenLoc, EndLoc);
9477     break;
9478   case OMPC_map:
9479     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9480                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
9481                                LParenLoc, EndLoc);
9482     break;
9483   case OMPC_to:
9484     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9485     break;
9486   case OMPC_from:
9487     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9488     break;
9489   case OMPC_use_device_ptr:
9490     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9491     break;
9492   case OMPC_is_device_ptr:
9493     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9494     break;
9495   case OMPC_if:
9496   case OMPC_final:
9497   case OMPC_num_threads:
9498   case OMPC_safelen:
9499   case OMPC_simdlen:
9500   case OMPC_collapse:
9501   case OMPC_default:
9502   case OMPC_proc_bind:
9503   case OMPC_schedule:
9504   case OMPC_ordered:
9505   case OMPC_nowait:
9506   case OMPC_untied:
9507   case OMPC_mergeable:
9508   case OMPC_threadprivate:
9509   case OMPC_read:
9510   case OMPC_write:
9511   case OMPC_update:
9512   case OMPC_capture:
9513   case OMPC_seq_cst:
9514   case OMPC_device:
9515   case OMPC_threads:
9516   case OMPC_simd:
9517   case OMPC_num_teams:
9518   case OMPC_thread_limit:
9519   case OMPC_priority:
9520   case OMPC_grainsize:
9521   case OMPC_nogroup:
9522   case OMPC_num_tasks:
9523   case OMPC_hint:
9524   case OMPC_dist_schedule:
9525   case OMPC_defaultmap:
9526   case OMPC_unknown:
9527   case OMPC_uniform:
9528   case OMPC_unified_address:
9529   case OMPC_unified_shared_memory:
9530   case OMPC_reverse_offload:
9531   case OMPC_dynamic_allocators:
9532     llvm_unreachable("Clause is not allowed.");
9533   }
9534   return Res;
9535 }
9536 
9537 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9538                                        ExprObjectKind OK, SourceLocation Loc) {
9539   ExprResult Res = BuildDeclRefExpr(
9540       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9541   if (!Res.isUsable())
9542     return ExprError();
9543   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9544     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9545     if (!Res.isUsable())
9546       return ExprError();
9547   }
9548   if (VK != VK_LValue && Res.get()->isGLValue()) {
9549     Res = DefaultLvalueConversion(Res.get());
9550     if (!Res.isUsable())
9551       return ExprError();
9552   }
9553   return Res;
9554 }
9555 
9556 static std::pair<ValueDecl *, bool>
9557 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9558                SourceRange &ERange, bool AllowArraySection = false) {
9559   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9560       RefExpr->containsUnexpandedParameterPack())
9561     return std::make_pair(nullptr, true);
9562 
9563   // OpenMP [3.1, C/C++]
9564   //  A list item is a variable name.
9565   // OpenMP  [2.9.3.3, Restrictions, p.1]
9566   //  A variable that is part of another variable (as an array or
9567   //  structure element) cannot appear in a private clause.
9568   RefExpr = RefExpr->IgnoreParens();
9569   enum {
9570     NoArrayExpr = -1,
9571     ArraySubscript = 0,
9572     OMPArraySection = 1
9573   } IsArrayExpr = NoArrayExpr;
9574   if (AllowArraySection) {
9575     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9576       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
9577       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9578         Base = TempASE->getBase()->IgnoreParenImpCasts();
9579       RefExpr = Base;
9580       IsArrayExpr = ArraySubscript;
9581     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9582       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9583       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9584         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9585       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9586         Base = TempASE->getBase()->IgnoreParenImpCasts();
9587       RefExpr = Base;
9588       IsArrayExpr = OMPArraySection;
9589     }
9590   }
9591   ELoc = RefExpr->getExprLoc();
9592   ERange = RefExpr->getSourceRange();
9593   RefExpr = RefExpr->IgnoreParenImpCasts();
9594   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9595   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9596   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9597       (S.getCurrentThisType().isNull() || !ME ||
9598        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9599        !isa<FieldDecl>(ME->getMemberDecl()))) {
9600     if (IsArrayExpr != NoArrayExpr) {
9601       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9602                                                          << ERange;
9603     } else {
9604       S.Diag(ELoc,
9605              AllowArraySection
9606                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9607                  : diag::err_omp_expected_var_name_member_expr)
9608           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9609     }
9610     return std::make_pair(nullptr, false);
9611   }
9612   return std::make_pair(
9613       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9614 }
9615 
9616 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9617                                           SourceLocation StartLoc,
9618                                           SourceLocation LParenLoc,
9619                                           SourceLocation EndLoc) {
9620   SmallVector<Expr *, 8> Vars;
9621   SmallVector<Expr *, 8> PrivateCopies;
9622   for (Expr *RefExpr : VarList) {
9623     assert(RefExpr && "NULL expr in OpenMP private clause.");
9624     SourceLocation ELoc;
9625     SourceRange ERange;
9626     Expr *SimpleRefExpr = RefExpr;
9627     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9628     if (Res.second) {
9629       // It will be analyzed later.
9630       Vars.push_back(RefExpr);
9631       PrivateCopies.push_back(nullptr);
9632     }
9633     ValueDecl *D = Res.first;
9634     if (!D)
9635       continue;
9636 
9637     QualType Type = D->getType();
9638     auto *VD = dyn_cast<VarDecl>(D);
9639 
9640     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9641     //  A variable that appears in a private clause must not have an incomplete
9642     //  type or a reference type.
9643     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9644       continue;
9645     Type = Type.getNonReferenceType();
9646 
9647     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9648     // in a Construct]
9649     //  Variables with the predetermined data-sharing attributes may not be
9650     //  listed in data-sharing attributes clauses, except for the cases
9651     //  listed below. For these exceptions only, listing a predetermined
9652     //  variable in a data-sharing attribute clause is allowed and overrides
9653     //  the variable's predetermined data-sharing attributes.
9654     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9655     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9656       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9657                                           << getOpenMPClauseName(OMPC_private);
9658       reportOriginalDsa(*this, DSAStack, D, DVar);
9659       continue;
9660     }
9661 
9662     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9663     // Variably modified types are not supported for tasks.
9664     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9665         isOpenMPTaskingDirective(CurrDir)) {
9666       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9667           << getOpenMPClauseName(OMPC_private) << Type
9668           << getOpenMPDirectiveName(CurrDir);
9669       bool IsDecl =
9670           !VD ||
9671           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9672       Diag(D->getLocation(),
9673            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9674           << D;
9675       continue;
9676     }
9677 
9678     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9679     // A list item cannot appear in both a map clause and a data-sharing
9680     // attribute clause on the same construct
9681     if (isOpenMPTargetExecutionDirective(CurrDir)) {
9682       OpenMPClauseKind ConflictKind;
9683       if (DSAStack->checkMappableExprComponentListsForDecl(
9684               VD, /*CurrentRegionOnly=*/true,
9685               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9686                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9687                 ConflictKind = WhereFoundClauseKind;
9688                 return true;
9689               })) {
9690         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9691             << getOpenMPClauseName(OMPC_private)
9692             << getOpenMPClauseName(ConflictKind)
9693             << getOpenMPDirectiveName(CurrDir);
9694         reportOriginalDsa(*this, DSAStack, D, DVar);
9695         continue;
9696       }
9697     }
9698 
9699     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9700     //  A variable of class type (or array thereof) that appears in a private
9701     //  clause requires an accessible, unambiguous default constructor for the
9702     //  class type.
9703     // Generate helper private variable and initialize it with the default
9704     // value. The address of the original variable is replaced by the address of
9705     // the new private variable in CodeGen. This new variable is not added to
9706     // IdResolver, so the code in the OpenMP region uses original variable for
9707     // proper diagnostics.
9708     Type = Type.getUnqualifiedType();
9709     VarDecl *VDPrivate =
9710         buildVarDecl(*this, ELoc, Type, D->getName(),
9711                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9712                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9713     ActOnUninitializedDecl(VDPrivate);
9714     if (VDPrivate->isInvalidDecl())
9715       continue;
9716     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
9717         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9718 
9719     DeclRefExpr *Ref = nullptr;
9720     if (!VD && !CurContext->isDependentContext())
9721       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9722     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9723     Vars.push_back((VD || CurContext->isDependentContext())
9724                        ? RefExpr->IgnoreParens()
9725                        : Ref);
9726     PrivateCopies.push_back(VDPrivateRefExpr);
9727   }
9728 
9729   if (Vars.empty())
9730     return nullptr;
9731 
9732   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9733                                   PrivateCopies);
9734 }
9735 
9736 namespace {
9737 class DiagsUninitializedSeveretyRAII {
9738 private:
9739   DiagnosticsEngine &Diags;
9740   SourceLocation SavedLoc;
9741   bool IsIgnored = false;
9742 
9743 public:
9744   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9745                                  bool IsIgnored)
9746       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9747     if (!IsIgnored) {
9748       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9749                         /*Map*/ diag::Severity::Ignored, Loc);
9750     }
9751   }
9752   ~DiagsUninitializedSeveretyRAII() {
9753     if (!IsIgnored)
9754       Diags.popMappings(SavedLoc);
9755   }
9756 };
9757 }
9758 
9759 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9760                                                SourceLocation StartLoc,
9761                                                SourceLocation LParenLoc,
9762                                                SourceLocation EndLoc) {
9763   SmallVector<Expr *, 8> Vars;
9764   SmallVector<Expr *, 8> PrivateCopies;
9765   SmallVector<Expr *, 8> Inits;
9766   SmallVector<Decl *, 4> ExprCaptures;
9767   bool IsImplicitClause =
9768       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9769   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
9770 
9771   for (Expr *RefExpr : VarList) {
9772     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9773     SourceLocation ELoc;
9774     SourceRange ERange;
9775     Expr *SimpleRefExpr = RefExpr;
9776     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9777     if (Res.second) {
9778       // It will be analyzed later.
9779       Vars.push_back(RefExpr);
9780       PrivateCopies.push_back(nullptr);
9781       Inits.push_back(nullptr);
9782     }
9783     ValueDecl *D = Res.first;
9784     if (!D)
9785       continue;
9786 
9787     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9788     QualType Type = D->getType();
9789     auto *VD = dyn_cast<VarDecl>(D);
9790 
9791     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9792     //  A variable that appears in a private clause must not have an incomplete
9793     //  type or a reference type.
9794     if (RequireCompleteType(ELoc, Type,
9795                             diag::err_omp_firstprivate_incomplete_type))
9796       continue;
9797     Type = Type.getNonReferenceType();
9798 
9799     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9800     //  A variable of class type (or array thereof) that appears in a private
9801     //  clause requires an accessible, unambiguous copy constructor for the
9802     //  class type.
9803     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9804 
9805     // If an implicit firstprivate variable found it was checked already.
9806     DSAStackTy::DSAVarData TopDVar;
9807     if (!IsImplicitClause) {
9808       DSAStackTy::DSAVarData DVar =
9809           DSAStack->getTopDSA(D, /*FromParent=*/false);
9810       TopDVar = DVar;
9811       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9812       bool IsConstant = ElemType.isConstant(Context);
9813       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9814       //  A list item that specifies a given variable may not appear in more
9815       // than one clause on the same directive, except that a variable may be
9816       //  specified in both firstprivate and lastprivate clauses.
9817       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9818       // A list item may appear in a firstprivate or lastprivate clause but not
9819       // both.
9820       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9821           (isOpenMPDistributeDirective(CurrDir) ||
9822            DVar.CKind != OMPC_lastprivate) &&
9823           DVar.RefExpr) {
9824         Diag(ELoc, diag::err_omp_wrong_dsa)
9825             << getOpenMPClauseName(DVar.CKind)
9826             << getOpenMPClauseName(OMPC_firstprivate);
9827         reportOriginalDsa(*this, DSAStack, D, DVar);
9828         continue;
9829       }
9830 
9831       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9832       // in a Construct]
9833       //  Variables with the predetermined data-sharing attributes may not be
9834       //  listed in data-sharing attributes clauses, except for the cases
9835       //  listed below. For these exceptions only, listing a predetermined
9836       //  variable in a data-sharing attribute clause is allowed and overrides
9837       //  the variable's predetermined data-sharing attributes.
9838       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9839       // in a Construct, C/C++, p.2]
9840       //  Variables with const-qualified type having no mutable member may be
9841       //  listed in a firstprivate clause, even if they are static data members.
9842       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9843           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9844         Diag(ELoc, diag::err_omp_wrong_dsa)
9845             << getOpenMPClauseName(DVar.CKind)
9846             << getOpenMPClauseName(OMPC_firstprivate);
9847         reportOriginalDsa(*this, DSAStack, D, DVar);
9848         continue;
9849       }
9850 
9851       // OpenMP [2.9.3.4, Restrictions, p.2]
9852       //  A list item that is private within a parallel region must not appear
9853       //  in a firstprivate clause on a worksharing construct if any of the
9854       //  worksharing regions arising from the worksharing construct ever bind
9855       //  to any of the parallel regions arising from the parallel construct.
9856       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9857       // A list item that is private within a teams region must not appear in a
9858       // firstprivate clause on a distribute construct if any of the distribute
9859       // regions arising from the distribute construct ever bind to any of the
9860       // teams regions arising from the teams construct.
9861       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9862       // A list item that appears in a reduction clause of a teams construct
9863       // must not appear in a firstprivate clause on a distribute construct if
9864       // any of the distribute regions arising from the distribute construct
9865       // ever bind to any of the teams regions arising from the teams construct.
9866       if ((isOpenMPWorksharingDirective(CurrDir) ||
9867            isOpenMPDistributeDirective(CurrDir)) &&
9868           !isOpenMPParallelDirective(CurrDir) &&
9869           !isOpenMPTeamsDirective(CurrDir)) {
9870         DVar = DSAStack->getImplicitDSA(D, true);
9871         if (DVar.CKind != OMPC_shared &&
9872             (isOpenMPParallelDirective(DVar.DKind) ||
9873              isOpenMPTeamsDirective(DVar.DKind) ||
9874              DVar.DKind == OMPD_unknown)) {
9875           Diag(ELoc, diag::err_omp_required_access)
9876               << getOpenMPClauseName(OMPC_firstprivate)
9877               << getOpenMPClauseName(OMPC_shared);
9878           reportOriginalDsa(*this, DSAStack, D, DVar);
9879           continue;
9880         }
9881       }
9882       // OpenMP [2.9.3.4, Restrictions, p.3]
9883       //  A list item that appears in a reduction clause of a parallel construct
9884       //  must not appear in a firstprivate clause on a worksharing or task
9885       //  construct if any of the worksharing or task regions arising from the
9886       //  worksharing or task construct ever bind to any of the parallel regions
9887       //  arising from the parallel construct.
9888       // OpenMP [2.9.3.4, Restrictions, p.4]
9889       //  A list item that appears in a reduction clause in worksharing
9890       //  construct must not appear in a firstprivate clause in a task construct
9891       //  encountered during execution of any of the worksharing regions arising
9892       //  from the worksharing construct.
9893       if (isOpenMPTaskingDirective(CurrDir)) {
9894         DVar = DSAStack->hasInnermostDSA(
9895             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
9896             [](OpenMPDirectiveKind K) {
9897               return isOpenMPParallelDirective(K) ||
9898                      isOpenMPWorksharingDirective(K) ||
9899                      isOpenMPTeamsDirective(K);
9900             },
9901             /*FromParent=*/true);
9902         if (DVar.CKind == OMPC_reduction &&
9903             (isOpenMPParallelDirective(DVar.DKind) ||
9904              isOpenMPWorksharingDirective(DVar.DKind) ||
9905              isOpenMPTeamsDirective(DVar.DKind))) {
9906           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9907               << getOpenMPDirectiveName(DVar.DKind);
9908           reportOriginalDsa(*this, DSAStack, D, DVar);
9909           continue;
9910         }
9911       }
9912 
9913       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9914       // A list item cannot appear in both a map clause and a data-sharing
9915       // attribute clause on the same construct
9916       if (isOpenMPTargetExecutionDirective(CurrDir)) {
9917         OpenMPClauseKind ConflictKind;
9918         if (DSAStack->checkMappableExprComponentListsForDecl(
9919                 VD, /*CurrentRegionOnly=*/true,
9920                 [&ConflictKind](
9921                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
9922                     OpenMPClauseKind WhereFoundClauseKind) {
9923                   ConflictKind = WhereFoundClauseKind;
9924                   return true;
9925                 })) {
9926           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9927               << getOpenMPClauseName(OMPC_firstprivate)
9928               << getOpenMPClauseName(ConflictKind)
9929               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9930           reportOriginalDsa(*this, DSAStack, D, DVar);
9931           continue;
9932         }
9933       }
9934     }
9935 
9936     // Variably modified types are not supported for tasks.
9937     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9938         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
9939       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9940           << getOpenMPClauseName(OMPC_firstprivate) << Type
9941           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9942       bool IsDecl =
9943           !VD ||
9944           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9945       Diag(D->getLocation(),
9946            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9947           << D;
9948       continue;
9949     }
9950 
9951     Type = Type.getUnqualifiedType();
9952     VarDecl *VDPrivate =
9953         buildVarDecl(*this, ELoc, Type, D->getName(),
9954                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9955                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9956     // Generate helper private variable and initialize it with the value of the
9957     // original variable. The address of the original variable is replaced by
9958     // the address of the new private variable in the CodeGen. This new variable
9959     // is not added to IdResolver, so the code in the OpenMP region uses
9960     // original variable for proper diagnostics and variable capturing.
9961     Expr *VDInitRefExpr = nullptr;
9962     // For arrays generate initializer for single element and replace it by the
9963     // original array element in CodeGen.
9964     if (Type->isArrayType()) {
9965       VarDecl *VDInit =
9966           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
9967       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
9968       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
9969       ElemType = ElemType.getUnqualifiedType();
9970       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
9971                                          ".firstprivate.temp");
9972       InitializedEntity Entity =
9973           InitializedEntity::InitializeVariable(VDInitTemp);
9974       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9975 
9976       InitializationSequence InitSeq(*this, Entity, Kind, Init);
9977       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9978       if (Result.isInvalid())
9979         VDPrivate->setInvalidDecl();
9980       else
9981         VDPrivate->setInit(Result.getAs<Expr>());
9982       // Remove temp variable declaration.
9983       Context.Deallocate(VDInitTemp);
9984     } else {
9985       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9986                                      ".firstprivate.temp");
9987       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9988                                        RefExpr->getExprLoc());
9989       AddInitializerToDecl(VDPrivate,
9990                            DefaultLvalueConversion(VDInitRefExpr).get(),
9991                            /*DirectInit=*/false);
9992     }
9993     if (VDPrivate->isInvalidDecl()) {
9994       if (IsImplicitClause) {
9995         Diag(RefExpr->getExprLoc(),
9996              diag::note_omp_task_predetermined_firstprivate_here);
9997       }
9998       continue;
9999     }
10000     CurContext->addDecl(VDPrivate);
10001     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10002         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10003         RefExpr->getExprLoc());
10004     DeclRefExpr *Ref = nullptr;
10005     if (!VD && !CurContext->isDependentContext()) {
10006       if (TopDVar.CKind == OMPC_lastprivate) {
10007         Ref = TopDVar.PrivateCopy;
10008       } else {
10009         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10010         if (!isOpenMPCapturedDecl(D))
10011           ExprCaptures.push_back(Ref->getDecl());
10012       }
10013     }
10014     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10015     Vars.push_back((VD || CurContext->isDependentContext())
10016                        ? RefExpr->IgnoreParens()
10017                        : Ref);
10018     PrivateCopies.push_back(VDPrivateRefExpr);
10019     Inits.push_back(VDInitRefExpr);
10020   }
10021 
10022   if (Vars.empty())
10023     return nullptr;
10024 
10025   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10026                                        Vars, PrivateCopies, Inits,
10027                                        buildPreInits(Context, ExprCaptures));
10028 }
10029 
10030 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10031                                               SourceLocation StartLoc,
10032                                               SourceLocation LParenLoc,
10033                                               SourceLocation EndLoc) {
10034   SmallVector<Expr *, 8> Vars;
10035   SmallVector<Expr *, 8> SrcExprs;
10036   SmallVector<Expr *, 8> DstExprs;
10037   SmallVector<Expr *, 8> AssignmentOps;
10038   SmallVector<Decl *, 4> ExprCaptures;
10039   SmallVector<Expr *, 4> ExprPostUpdates;
10040   for (Expr *RefExpr : VarList) {
10041     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10042     SourceLocation ELoc;
10043     SourceRange ERange;
10044     Expr *SimpleRefExpr = RefExpr;
10045     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10046     if (Res.second) {
10047       // It will be analyzed later.
10048       Vars.push_back(RefExpr);
10049       SrcExprs.push_back(nullptr);
10050       DstExprs.push_back(nullptr);
10051       AssignmentOps.push_back(nullptr);
10052     }
10053     ValueDecl *D = Res.first;
10054     if (!D)
10055       continue;
10056 
10057     QualType Type = D->getType();
10058     auto *VD = dyn_cast<VarDecl>(D);
10059 
10060     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10061     //  A variable that appears in a lastprivate clause must not have an
10062     //  incomplete type or a reference type.
10063     if (RequireCompleteType(ELoc, Type,
10064                             diag::err_omp_lastprivate_incomplete_type))
10065       continue;
10066     Type = Type.getNonReferenceType();
10067 
10068     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10069     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10070     // in a Construct]
10071     //  Variables with the predetermined data-sharing attributes may not be
10072     //  listed in data-sharing attributes clauses, except for the cases
10073     //  listed below.
10074     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10075     // A list item may appear in a firstprivate or lastprivate clause but not
10076     // both.
10077     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10078     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
10079         (isOpenMPDistributeDirective(CurrDir) ||
10080          DVar.CKind != OMPC_firstprivate) &&
10081         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10082       Diag(ELoc, diag::err_omp_wrong_dsa)
10083           << getOpenMPClauseName(DVar.CKind)
10084           << getOpenMPClauseName(OMPC_lastprivate);
10085       reportOriginalDsa(*this, DSAStack, D, DVar);
10086       continue;
10087     }
10088 
10089     // OpenMP [2.14.3.5, Restrictions, p.2]
10090     // A list item that is private within a parallel region, or that appears in
10091     // the reduction clause of a parallel construct, must not appear in a
10092     // lastprivate clause on a worksharing construct if any of the corresponding
10093     // worksharing regions ever binds to any of the corresponding parallel
10094     // regions.
10095     DSAStackTy::DSAVarData TopDVar = DVar;
10096     if (isOpenMPWorksharingDirective(CurrDir) &&
10097         !isOpenMPParallelDirective(CurrDir) &&
10098         !isOpenMPTeamsDirective(CurrDir)) {
10099       DVar = DSAStack->getImplicitDSA(D, true);
10100       if (DVar.CKind != OMPC_shared) {
10101         Diag(ELoc, diag::err_omp_required_access)
10102             << getOpenMPClauseName(OMPC_lastprivate)
10103             << getOpenMPClauseName(OMPC_shared);
10104         reportOriginalDsa(*this, DSAStack, D, DVar);
10105         continue;
10106       }
10107     }
10108 
10109     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
10110     //  A variable of class type (or array thereof) that appears in a
10111     //  lastprivate clause requires an accessible, unambiguous default
10112     //  constructor for the class type, unless the list item is also specified
10113     //  in a firstprivate clause.
10114     //  A variable of class type (or array thereof) that appears in a
10115     //  lastprivate clause requires an accessible, unambiguous copy assignment
10116     //  operator for the class type.
10117     Type = Context.getBaseElementType(Type).getNonReferenceType();
10118     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10119                                   Type.getUnqualifiedType(), ".lastprivate.src",
10120                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10121     DeclRefExpr *PseudoSrcExpr =
10122         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
10123     VarDecl *DstVD =
10124         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
10125                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10126     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10127     // For arrays generate assignment operation for single element and replace
10128     // it by the original array element in CodeGen.
10129     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10130                                          PseudoDstExpr, PseudoSrcExpr);
10131     if (AssignmentOp.isInvalid())
10132       continue;
10133     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
10134                                        /*DiscardedValue=*/true);
10135     if (AssignmentOp.isInvalid())
10136       continue;
10137 
10138     DeclRefExpr *Ref = nullptr;
10139     if (!VD && !CurContext->isDependentContext()) {
10140       if (TopDVar.CKind == OMPC_firstprivate) {
10141         Ref = TopDVar.PrivateCopy;
10142       } else {
10143         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10144         if (!isOpenMPCapturedDecl(D))
10145           ExprCaptures.push_back(Ref->getDecl());
10146       }
10147       if (TopDVar.CKind == OMPC_firstprivate ||
10148           (!isOpenMPCapturedDecl(D) &&
10149            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
10150         ExprResult RefRes = DefaultLvalueConversion(Ref);
10151         if (!RefRes.isUsable())
10152           continue;
10153         ExprResult PostUpdateRes =
10154             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10155                        RefRes.get());
10156         if (!PostUpdateRes.isUsable())
10157           continue;
10158         ExprPostUpdates.push_back(
10159             IgnoredValueConversions(PostUpdateRes.get()).get());
10160       }
10161     }
10162     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
10163     Vars.push_back((VD || CurContext->isDependentContext())
10164                        ? RefExpr->IgnoreParens()
10165                        : Ref);
10166     SrcExprs.push_back(PseudoSrcExpr);
10167     DstExprs.push_back(PseudoDstExpr);
10168     AssignmentOps.push_back(AssignmentOp.get());
10169   }
10170 
10171   if (Vars.empty())
10172     return nullptr;
10173 
10174   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10175                                       Vars, SrcExprs, DstExprs, AssignmentOps,
10176                                       buildPreInits(Context, ExprCaptures),
10177                                       buildPostUpdate(*this, ExprPostUpdates));
10178 }
10179 
10180 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10181                                          SourceLocation StartLoc,
10182                                          SourceLocation LParenLoc,
10183                                          SourceLocation EndLoc) {
10184   SmallVector<Expr *, 8> Vars;
10185   for (Expr *RefExpr : VarList) {
10186     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10187     SourceLocation ELoc;
10188     SourceRange ERange;
10189     Expr *SimpleRefExpr = RefExpr;
10190     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10191     if (Res.second) {
10192       // It will be analyzed later.
10193       Vars.push_back(RefExpr);
10194     }
10195     ValueDecl *D = Res.first;
10196     if (!D)
10197       continue;
10198 
10199     auto *VD = dyn_cast<VarDecl>(D);
10200     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10201     // in a Construct]
10202     //  Variables with the predetermined data-sharing attributes may not be
10203     //  listed in data-sharing attributes clauses, except for the cases
10204     //  listed below. For these exceptions only, listing a predetermined
10205     //  variable in a data-sharing attribute clause is allowed and overrides
10206     //  the variable's predetermined data-sharing attributes.
10207     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10208     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10209         DVar.RefExpr) {
10210       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10211                                           << getOpenMPClauseName(OMPC_shared);
10212       reportOriginalDsa(*this, DSAStack, D, DVar);
10213       continue;
10214     }
10215 
10216     DeclRefExpr *Ref = nullptr;
10217     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
10218       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10219     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
10220     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10221                        ? RefExpr->IgnoreParens()
10222                        : Ref);
10223   }
10224 
10225   if (Vars.empty())
10226     return nullptr;
10227 
10228   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10229 }
10230 
10231 namespace {
10232 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10233   DSAStackTy *Stack;
10234 
10235 public:
10236   bool VisitDeclRefExpr(DeclRefExpr *E) {
10237     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10238       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
10239       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10240         return false;
10241       if (DVar.CKind != OMPC_unknown)
10242         return true;
10243       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
10244           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
10245           /*FromParent=*/true);
10246       return DVarPrivate.CKind != OMPC_unknown;
10247     }
10248     return false;
10249   }
10250   bool VisitStmt(Stmt *S) {
10251     for (Stmt *Child : S->children()) {
10252       if (Child && Visit(Child))
10253         return true;
10254     }
10255     return false;
10256   }
10257   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
10258 };
10259 } // namespace
10260 
10261 namespace {
10262 // Transform MemberExpression for specified FieldDecl of current class to
10263 // DeclRefExpr to specified OMPCapturedExprDecl.
10264 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10265   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
10266   ValueDecl *Field = nullptr;
10267   DeclRefExpr *CapturedExpr = nullptr;
10268 
10269 public:
10270   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10271       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10272 
10273   ExprResult TransformMemberExpr(MemberExpr *E) {
10274     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10275         E->getMemberDecl() == Field) {
10276       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
10277       return CapturedExpr;
10278     }
10279     return BaseTransform::TransformMemberExpr(E);
10280   }
10281   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10282 };
10283 } // namespace
10284 
10285 template <typename T, typename U>
10286 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
10287                             const llvm::function_ref<T(ValueDecl *)> Gen) {
10288   for (U &Set : Lookups) {
10289     for (auto *D : Set) {
10290       if (T Res = Gen(cast<ValueDecl>(D)))
10291         return Res;
10292     }
10293   }
10294   return T();
10295 }
10296 
10297 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10298   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10299 
10300   for (auto RD : D->redecls()) {
10301     // Don't bother with extra checks if we already know this one isn't visible.
10302     if (RD == D)
10303       continue;
10304 
10305     auto ND = cast<NamedDecl>(RD);
10306     if (LookupResult::isVisible(SemaRef, ND))
10307       return ND;
10308   }
10309 
10310   return nullptr;
10311 }
10312 
10313 static void
10314 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
10315                         SourceLocation Loc, QualType Ty,
10316                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10317   // Find all of the associated namespaces and classes based on the
10318   // arguments we have.
10319   Sema::AssociatedNamespaceSet AssociatedNamespaces;
10320   Sema::AssociatedClassSet AssociatedClasses;
10321   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10322   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10323                                              AssociatedClasses);
10324 
10325   // C++ [basic.lookup.argdep]p3:
10326   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10327   //   and let Y be the lookup set produced by argument dependent
10328   //   lookup (defined as follows). If X contains [...] then Y is
10329   //   empty. Otherwise Y is the set of declarations found in the
10330   //   namespaces associated with the argument types as described
10331   //   below. The set of declarations found by the lookup of the name
10332   //   is the union of X and Y.
10333   //
10334   // Here, we compute Y and add its members to the overloaded
10335   // candidate set.
10336   for (auto *NS : AssociatedNamespaces) {
10337     //   When considering an associated namespace, the lookup is the
10338     //   same as the lookup performed when the associated namespace is
10339     //   used as a qualifier (3.4.3.2) except that:
10340     //
10341     //     -- Any using-directives in the associated namespace are
10342     //        ignored.
10343     //
10344     //     -- Any namespace-scope friend functions declared in
10345     //        associated classes are visible within their respective
10346     //        namespaces even if they are not visible during an ordinary
10347     //        lookup (11.4).
10348     DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
10349     for (auto *D : R) {
10350       auto *Underlying = D;
10351       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10352         Underlying = USD->getTargetDecl();
10353 
10354       if (!isa<OMPDeclareReductionDecl>(Underlying))
10355         continue;
10356 
10357       if (!SemaRef.isVisible(D)) {
10358         D = findAcceptableDecl(SemaRef, D);
10359         if (!D)
10360           continue;
10361         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10362           Underlying = USD->getTargetDecl();
10363       }
10364       Lookups.emplace_back();
10365       Lookups.back().addDecl(Underlying);
10366     }
10367   }
10368 }
10369 
10370 static ExprResult
10371 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10372                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10373                          const DeclarationNameInfo &ReductionId, QualType Ty,
10374                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10375   if (ReductionIdScopeSpec.isInvalid())
10376     return ExprError();
10377   SmallVector<UnresolvedSet<8>, 4> Lookups;
10378   if (S) {
10379     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10380     Lookup.suppressDiagnostics();
10381     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
10382       NamedDecl *D = Lookup.getRepresentativeDecl();
10383       do {
10384         S = S->getParent();
10385       } while (S && !S->isDeclScope(D));
10386       if (S)
10387         S = S->getParent();
10388       Lookups.emplace_back();
10389       Lookups.back().append(Lookup.begin(), Lookup.end());
10390       Lookup.clear();
10391     }
10392   } else if (auto *ULE =
10393                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10394     Lookups.push_back(UnresolvedSet<8>());
10395     Decl *PrevD = nullptr;
10396     for (NamedDecl *D : ULE->decls()) {
10397       if (D == PrevD)
10398         Lookups.push_back(UnresolvedSet<8>());
10399       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10400         Lookups.back().addDecl(DRD);
10401       PrevD = D;
10402     }
10403   }
10404   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10405       Ty->isInstantiationDependentType() ||
10406       Ty->containsUnexpandedParameterPack() ||
10407       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
10408         return !D->isInvalidDecl() &&
10409                (D->getType()->isDependentType() ||
10410                 D->getType()->isInstantiationDependentType() ||
10411                 D->getType()->containsUnexpandedParameterPack());
10412       })) {
10413     UnresolvedSet<8> ResSet;
10414     for (const UnresolvedSet<8> &Set : Lookups) {
10415       if (Set.empty())
10416         continue;
10417       ResSet.append(Set.begin(), Set.end());
10418       // The last item marks the end of all declarations at the specified scope.
10419       ResSet.addDecl(Set[Set.size() - 1]);
10420     }
10421     return UnresolvedLookupExpr::Create(
10422         SemaRef.Context, /*NamingClass=*/nullptr,
10423         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10424         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10425   }
10426   // Lookup inside the classes.
10427   // C++ [over.match.oper]p3:
10428   //   For a unary operator @ with an operand of a type whose
10429   //   cv-unqualified version is T1, and for a binary operator @ with
10430   //   a left operand of a type whose cv-unqualified version is T1 and
10431   //   a right operand of a type whose cv-unqualified version is T2,
10432   //   three sets of candidate functions, designated member
10433   //   candidates, non-member candidates and built-in candidates, are
10434   //   constructed as follows:
10435   //     -- If T1 is a complete class type or a class currently being
10436   //        defined, the set of member candidates is the result of the
10437   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10438   //        the set of member candidates is empty.
10439   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10440   Lookup.suppressDiagnostics();
10441   if (const auto *TyRec = Ty->getAs<RecordType>()) {
10442     // Complete the type if it can be completed.
10443     // If the type is neither complete nor being defined, bail out now.
10444     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10445         TyRec->getDecl()->getDefinition()) {
10446       Lookup.clear();
10447       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10448       if (Lookup.empty()) {
10449         Lookups.emplace_back();
10450         Lookups.back().append(Lookup.begin(), Lookup.end());
10451       }
10452     }
10453   }
10454   // Perform ADL.
10455   argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
10456   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10457           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10458             if (!D->isInvalidDecl() &&
10459                 SemaRef.Context.hasSameType(D->getType(), Ty))
10460               return D;
10461             return nullptr;
10462           }))
10463     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10464   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10465           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10466             if (!D->isInvalidDecl() &&
10467                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10468                 !Ty.isMoreQualifiedThan(D->getType()))
10469               return D;
10470             return nullptr;
10471           })) {
10472     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10473                        /*DetectVirtual=*/false);
10474     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10475       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10476               VD->getType().getUnqualifiedType()))) {
10477         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10478                                          /*DiagID=*/0) !=
10479             Sema::AR_inaccessible) {
10480           SemaRef.BuildBasePathArray(Paths, BasePath);
10481           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10482         }
10483       }
10484     }
10485   }
10486   if (ReductionIdScopeSpec.isSet()) {
10487     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10488     return ExprError();
10489   }
10490   return ExprEmpty();
10491 }
10492 
10493 namespace {
10494 /// Data for the reduction-based clauses.
10495 struct ReductionData {
10496   /// List of original reduction items.
10497   SmallVector<Expr *, 8> Vars;
10498   /// List of private copies of the reduction items.
10499   SmallVector<Expr *, 8> Privates;
10500   /// LHS expressions for the reduction_op expressions.
10501   SmallVector<Expr *, 8> LHSs;
10502   /// RHS expressions for the reduction_op expressions.
10503   SmallVector<Expr *, 8> RHSs;
10504   /// Reduction operation expression.
10505   SmallVector<Expr *, 8> ReductionOps;
10506   /// Taskgroup descriptors for the corresponding reduction items in
10507   /// in_reduction clauses.
10508   SmallVector<Expr *, 8> TaskgroupDescriptors;
10509   /// List of captures for clause.
10510   SmallVector<Decl *, 4> ExprCaptures;
10511   /// List of postupdate expressions.
10512   SmallVector<Expr *, 4> ExprPostUpdates;
10513   ReductionData() = delete;
10514   /// Reserves required memory for the reduction data.
10515   ReductionData(unsigned Size) {
10516     Vars.reserve(Size);
10517     Privates.reserve(Size);
10518     LHSs.reserve(Size);
10519     RHSs.reserve(Size);
10520     ReductionOps.reserve(Size);
10521     TaskgroupDescriptors.reserve(Size);
10522     ExprCaptures.reserve(Size);
10523     ExprPostUpdates.reserve(Size);
10524   }
10525   /// Stores reduction item and reduction operation only (required for dependent
10526   /// reduction item).
10527   void push(Expr *Item, Expr *ReductionOp) {
10528     Vars.emplace_back(Item);
10529     Privates.emplace_back(nullptr);
10530     LHSs.emplace_back(nullptr);
10531     RHSs.emplace_back(nullptr);
10532     ReductionOps.emplace_back(ReductionOp);
10533     TaskgroupDescriptors.emplace_back(nullptr);
10534   }
10535   /// Stores reduction data.
10536   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10537             Expr *TaskgroupDescriptor) {
10538     Vars.emplace_back(Item);
10539     Privates.emplace_back(Private);
10540     LHSs.emplace_back(LHS);
10541     RHSs.emplace_back(RHS);
10542     ReductionOps.emplace_back(ReductionOp);
10543     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
10544   }
10545 };
10546 } // namespace
10547 
10548 static bool checkOMPArraySectionConstantForReduction(
10549     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10550     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10551   const Expr *Length = OASE->getLength();
10552   if (Length == nullptr) {
10553     // For array sections of the form [1:] or [:], we would need to analyze
10554     // the lower bound...
10555     if (OASE->getColonLoc().isValid())
10556       return false;
10557 
10558     // This is an array subscript which has implicit length 1!
10559     SingleElement = true;
10560     ArraySizes.push_back(llvm::APSInt::get(1));
10561   } else {
10562     llvm::APSInt ConstantLengthValue;
10563     if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10564       return false;
10565 
10566     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10567     ArraySizes.push_back(ConstantLengthValue);
10568   }
10569 
10570   // Get the base of this array section and walk up from there.
10571   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10572 
10573   // We require length = 1 for all array sections except the right-most to
10574   // guarantee that the memory region is contiguous and has no holes in it.
10575   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10576     Length = TempOASE->getLength();
10577     if (Length == nullptr) {
10578       // For array sections of the form [1:] or [:], we would need to analyze
10579       // the lower bound...
10580       if (OASE->getColonLoc().isValid())
10581         return false;
10582 
10583       // This is an array subscript which has implicit length 1!
10584       ArraySizes.push_back(llvm::APSInt::get(1));
10585     } else {
10586       llvm::APSInt ConstantLengthValue;
10587       if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10588           ConstantLengthValue.getSExtValue() != 1)
10589         return false;
10590 
10591       ArraySizes.push_back(ConstantLengthValue);
10592     }
10593     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10594   }
10595 
10596   // If we have a single element, we don't need to add the implicit lengths.
10597   if (!SingleElement) {
10598     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10599       // Has implicit length 1!
10600       ArraySizes.push_back(llvm::APSInt::get(1));
10601       Base = TempASE->getBase()->IgnoreParenImpCasts();
10602     }
10603   }
10604 
10605   // This array section can be privatized as a single value or as a constant
10606   // sized array.
10607   return true;
10608 }
10609 
10610 static bool actOnOMPReductionKindClause(
10611     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10612     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10613     SourceLocation ColonLoc, SourceLocation EndLoc,
10614     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10615     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10616   DeclarationName DN = ReductionId.getName();
10617   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
10618   BinaryOperatorKind BOK = BO_Comma;
10619 
10620   ASTContext &Context = S.Context;
10621   // OpenMP [2.14.3.6, reduction clause]
10622   // C
10623   // reduction-identifier is either an identifier or one of the following
10624   // operators: +, -, *,  &, |, ^, && and ||
10625   // C++
10626   // reduction-identifier is either an id-expression or one of the following
10627   // operators: +, -, *, &, |, ^, && and ||
10628   switch (OOK) {
10629   case OO_Plus:
10630   case OO_Minus:
10631     BOK = BO_Add;
10632     break;
10633   case OO_Star:
10634     BOK = BO_Mul;
10635     break;
10636   case OO_Amp:
10637     BOK = BO_And;
10638     break;
10639   case OO_Pipe:
10640     BOK = BO_Or;
10641     break;
10642   case OO_Caret:
10643     BOK = BO_Xor;
10644     break;
10645   case OO_AmpAmp:
10646     BOK = BO_LAnd;
10647     break;
10648   case OO_PipePipe:
10649     BOK = BO_LOr;
10650     break;
10651   case OO_New:
10652   case OO_Delete:
10653   case OO_Array_New:
10654   case OO_Array_Delete:
10655   case OO_Slash:
10656   case OO_Percent:
10657   case OO_Tilde:
10658   case OO_Exclaim:
10659   case OO_Equal:
10660   case OO_Less:
10661   case OO_Greater:
10662   case OO_LessEqual:
10663   case OO_GreaterEqual:
10664   case OO_PlusEqual:
10665   case OO_MinusEqual:
10666   case OO_StarEqual:
10667   case OO_SlashEqual:
10668   case OO_PercentEqual:
10669   case OO_CaretEqual:
10670   case OO_AmpEqual:
10671   case OO_PipeEqual:
10672   case OO_LessLess:
10673   case OO_GreaterGreater:
10674   case OO_LessLessEqual:
10675   case OO_GreaterGreaterEqual:
10676   case OO_EqualEqual:
10677   case OO_ExclaimEqual:
10678   case OO_Spaceship:
10679   case OO_PlusPlus:
10680   case OO_MinusMinus:
10681   case OO_Comma:
10682   case OO_ArrowStar:
10683   case OO_Arrow:
10684   case OO_Call:
10685   case OO_Subscript:
10686   case OO_Conditional:
10687   case OO_Coawait:
10688   case NUM_OVERLOADED_OPERATORS:
10689     llvm_unreachable("Unexpected reduction identifier");
10690   case OO_None:
10691     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
10692       if (II->isStr("max"))
10693         BOK = BO_GT;
10694       else if (II->isStr("min"))
10695         BOK = BO_LT;
10696     }
10697     break;
10698   }
10699   SourceRange ReductionIdRange;
10700   if (ReductionIdScopeSpec.isValid())
10701     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10702   else
10703     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10704   ReductionIdRange.setEnd(ReductionId.getEndLoc());
10705 
10706   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10707   bool FirstIter = true;
10708   for (Expr *RefExpr : VarList) {
10709     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
10710     // OpenMP [2.1, C/C++]
10711     //  A list item is a variable or array section, subject to the restrictions
10712     //  specified in Section 2.4 on page 42 and in each of the sections
10713     // describing clauses and directives for which a list appears.
10714     // OpenMP  [2.14.3.3, Restrictions, p.1]
10715     //  A variable that is part of another variable (as an array or
10716     //  structure element) cannot appear in a private clause.
10717     if (!FirstIter && IR != ER)
10718       ++IR;
10719     FirstIter = false;
10720     SourceLocation ELoc;
10721     SourceRange ERange;
10722     Expr *SimpleRefExpr = RefExpr;
10723     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10724                               /*AllowArraySection=*/true);
10725     if (Res.second) {
10726       // Try to find 'declare reduction' corresponding construct before using
10727       // builtin/overloaded operators.
10728       QualType Type = Context.DependentTy;
10729       CXXCastPath BasePath;
10730       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10731           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10732           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10733       Expr *ReductionOp = nullptr;
10734       if (S.CurContext->isDependentContext() &&
10735           (DeclareReductionRef.isUnset() ||
10736            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10737         ReductionOp = DeclareReductionRef.get();
10738       // It will be analyzed later.
10739       RD.push(RefExpr, ReductionOp);
10740     }
10741     ValueDecl *D = Res.first;
10742     if (!D)
10743       continue;
10744 
10745     Expr *TaskgroupDescriptor = nullptr;
10746     QualType Type;
10747     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10748     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10749     if (ASE) {
10750       Type = ASE->getType().getNonReferenceType();
10751     } else if (OASE) {
10752       QualType BaseType =
10753           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10754       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
10755         Type = ATy->getElementType();
10756       else
10757         Type = BaseType->getPointeeType();
10758       Type = Type.getNonReferenceType();
10759     } else {
10760       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10761     }
10762     auto *VD = dyn_cast<VarDecl>(D);
10763 
10764     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10765     //  A variable that appears in a private clause must not have an incomplete
10766     //  type or a reference type.
10767     if (S.RequireCompleteType(ELoc, D->getType(),
10768                               diag::err_omp_reduction_incomplete_type))
10769       continue;
10770     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10771     // A list item that appears in a reduction clause must not be
10772     // const-qualified.
10773     if (Type.getNonReferenceType().isConstant(Context)) {
10774       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10775       if (!ASE && !OASE) {
10776         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10777                                  VarDecl::DeclarationOnly;
10778         S.Diag(D->getLocation(),
10779                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10780             << D;
10781       }
10782       continue;
10783     }
10784 
10785     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10786     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10787     //  If a list-item is a reference type then it must bind to the same object
10788     //  for all threads of the team.
10789     if (!ASE && !OASE) {
10790       if (VD) {
10791         VarDecl *VDDef = VD->getDefinition();
10792         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10793           DSARefChecker Check(Stack);
10794           if (Check.Visit(VDDef->getInit())) {
10795             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10796                 << getOpenMPClauseName(ClauseKind) << ERange;
10797             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10798             continue;
10799           }
10800         }
10801       }
10802 
10803       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10804       // in a Construct]
10805       //  Variables with the predetermined data-sharing attributes may not be
10806       //  listed in data-sharing attributes clauses, except for the cases
10807       //  listed below. For these exceptions only, listing a predetermined
10808       //  variable in a data-sharing attribute clause is allowed and overrides
10809       //  the variable's predetermined data-sharing attributes.
10810       // OpenMP [2.14.3.6, Restrictions, p.3]
10811       //  Any number of reduction clauses can be specified on the directive,
10812       //  but a list item can appear only once in the reduction clauses for that
10813       //  directive.
10814       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
10815       if (DVar.CKind == OMPC_reduction) {
10816         S.Diag(ELoc, diag::err_omp_once_referenced)
10817             << getOpenMPClauseName(ClauseKind);
10818         if (DVar.RefExpr)
10819           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10820         continue;
10821       }
10822       if (DVar.CKind != OMPC_unknown) {
10823         S.Diag(ELoc, diag::err_omp_wrong_dsa)
10824             << getOpenMPClauseName(DVar.CKind)
10825             << getOpenMPClauseName(OMPC_reduction);
10826         reportOriginalDsa(S, Stack, D, DVar);
10827         continue;
10828       }
10829 
10830       // OpenMP [2.14.3.6, Restrictions, p.1]
10831       //  A list item that appears in a reduction clause of a worksharing
10832       //  construct must be shared in the parallel regions to which any of the
10833       //  worksharing regions arising from the worksharing construct bind.
10834       if (isOpenMPWorksharingDirective(CurrDir) &&
10835           !isOpenMPParallelDirective(CurrDir) &&
10836           !isOpenMPTeamsDirective(CurrDir)) {
10837         DVar = Stack->getImplicitDSA(D, true);
10838         if (DVar.CKind != OMPC_shared) {
10839           S.Diag(ELoc, diag::err_omp_required_access)
10840               << getOpenMPClauseName(OMPC_reduction)
10841               << getOpenMPClauseName(OMPC_shared);
10842           reportOriginalDsa(S, Stack, D, DVar);
10843           continue;
10844         }
10845       }
10846     }
10847 
10848     // Try to find 'declare reduction' corresponding construct before using
10849     // builtin/overloaded operators.
10850     CXXCastPath BasePath;
10851     ExprResult DeclareReductionRef = buildDeclareReductionRef(
10852         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10853         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10854     if (DeclareReductionRef.isInvalid())
10855       continue;
10856     if (S.CurContext->isDependentContext() &&
10857         (DeclareReductionRef.isUnset() ||
10858          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
10859       RD.push(RefExpr, DeclareReductionRef.get());
10860       continue;
10861     }
10862     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10863       // Not allowed reduction identifier is found.
10864       S.Diag(ReductionId.getBeginLoc(),
10865              diag::err_omp_unknown_reduction_identifier)
10866           << Type << ReductionIdRange;
10867       continue;
10868     }
10869 
10870     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10871     // The type of a list item that appears in a reduction clause must be valid
10872     // for the reduction-identifier. For a max or min reduction in C, the type
10873     // of the list item must be an allowed arithmetic data type: char, int,
10874     // float, double, or _Bool, possibly modified with long, short, signed, or
10875     // unsigned. For a max or min reduction in C++, the type of the list item
10876     // must be an allowed arithmetic data type: char, wchar_t, int, float,
10877     // double, or bool, possibly modified with long, short, signed, or unsigned.
10878     if (DeclareReductionRef.isUnset()) {
10879       if ((BOK == BO_GT || BOK == BO_LT) &&
10880           !(Type->isScalarType() ||
10881             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10882         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
10883             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
10884         if (!ASE && !OASE) {
10885           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10886                                    VarDecl::DeclarationOnly;
10887           S.Diag(D->getLocation(),
10888                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10889               << D;
10890         }
10891         continue;
10892       }
10893       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
10894           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
10895         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10896             << getOpenMPClauseName(ClauseKind);
10897         if (!ASE && !OASE) {
10898           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10899                                    VarDecl::DeclarationOnly;
10900           S.Diag(D->getLocation(),
10901                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10902               << D;
10903         }
10904         continue;
10905       }
10906     }
10907 
10908     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
10909     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
10910                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10911     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
10912                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10913     QualType PrivateTy = Type;
10914 
10915     // Try if we can determine constant lengths for all array sections and avoid
10916     // the VLA.
10917     bool ConstantLengthOASE = false;
10918     if (OASE) {
10919       bool SingleElement;
10920       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10921       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
10922           Context, OASE, SingleElement, ArraySizes);
10923 
10924       // If we don't have a single element, we must emit a constant array type.
10925       if (ConstantLengthOASE && !SingleElement) {
10926         for (llvm::APSInt &Size : ArraySizes)
10927           PrivateTy = Context.getConstantArrayType(
10928               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10929       }
10930     }
10931 
10932     if ((OASE && !ConstantLengthOASE) ||
10933         (!OASE && !ASE &&
10934          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
10935       if (!Context.getTargetInfo().isVLASupported() &&
10936           S.shouldDiagnoseTargetSupportFromOpenMP()) {
10937         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10938         S.Diag(ELoc, diag::note_vla_unsupported);
10939         continue;
10940       }
10941       // For arrays/array sections only:
10942       // Create pseudo array type for private copy. The size for this array will
10943       // be generated during codegen.
10944       // For array subscripts or single variables Private Ty is the same as Type
10945       // (type of the variable or single array element).
10946       PrivateTy = Context.getVariableArrayType(
10947           Type,
10948           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
10949           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
10950     } else if (!ASE && !OASE &&
10951                Context.getAsArrayType(D->getType().getNonReferenceType())) {
10952       PrivateTy = D->getType().getNonReferenceType();
10953     }
10954     // Private copy.
10955     VarDecl *PrivateVD =
10956         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10957                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10958                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10959     // Add initializer for private variable.
10960     Expr *Init = nullptr;
10961     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10962     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
10963     if (DeclareReductionRef.isUsable()) {
10964       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10965       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10966       if (DRD->getInitializer()) {
10967         Init = DRDRef;
10968         RHSVD->setInit(DRDRef);
10969         RHSVD->setInitStyle(VarDecl::CallInit);
10970       }
10971     } else {
10972       switch (BOK) {
10973       case BO_Add:
10974       case BO_Xor:
10975       case BO_Or:
10976       case BO_LOr:
10977         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10978         if (Type->isScalarType() || Type->isAnyComplexType())
10979           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
10980         break;
10981       case BO_Mul:
10982       case BO_LAnd:
10983         if (Type->isScalarType() || Type->isAnyComplexType()) {
10984           // '*' and '&&' reduction ops - initializer is '1'.
10985           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
10986         }
10987         break;
10988       case BO_And: {
10989         // '&' reduction op - initializer is '~0'.
10990         QualType OrigType = Type;
10991         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10992           Type = ComplexTy->getElementType();
10993         if (Type->isRealFloatingType()) {
10994           llvm::APFloat InitValue =
10995               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10996                                              /*isIEEE=*/true);
10997           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10998                                          Type, ELoc);
10999         } else if (Type->isScalarType()) {
11000           uint64_t Size = Context.getTypeSize(Type);
11001           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11002           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11003           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11004         }
11005         if (Init && OrigType->isAnyComplexType()) {
11006           // Init = 0xFFFF + 0xFFFFi;
11007           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
11008           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
11009         }
11010         Type = OrigType;
11011         break;
11012       }
11013       case BO_LT:
11014       case BO_GT: {
11015         // 'min' reduction op - initializer is 'Largest representable number in
11016         // the reduction list item type'.
11017         // 'max' reduction op - initializer is 'Least representable number in
11018         // the reduction list item type'.
11019         if (Type->isIntegerType() || Type->isPointerType()) {
11020           bool IsSigned = Type->hasSignedIntegerRepresentation();
11021           uint64_t Size = Context.getTypeSize(Type);
11022           QualType IntTy =
11023               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11024           llvm::APInt InitValue =
11025               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11026                                         : llvm::APInt::getMinValue(Size)
11027                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11028                                         : llvm::APInt::getMaxValue(Size);
11029           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11030           if (Type->isPointerType()) {
11031             // Cast to pointer type.
11032             ExprResult CastExpr = S.BuildCStyleCastExpr(
11033                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
11034             if (CastExpr.isInvalid())
11035               continue;
11036             Init = CastExpr.get();
11037           }
11038         } else if (Type->isRealFloatingType()) {
11039           llvm::APFloat InitValue = llvm::APFloat::getLargest(
11040               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11041           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11042                                          Type, ELoc);
11043         }
11044         break;
11045       }
11046       case BO_PtrMemD:
11047       case BO_PtrMemI:
11048       case BO_MulAssign:
11049       case BO_Div:
11050       case BO_Rem:
11051       case BO_Sub:
11052       case BO_Shl:
11053       case BO_Shr:
11054       case BO_LE:
11055       case BO_GE:
11056       case BO_EQ:
11057       case BO_NE:
11058       case BO_Cmp:
11059       case BO_AndAssign:
11060       case BO_XorAssign:
11061       case BO_OrAssign:
11062       case BO_Assign:
11063       case BO_AddAssign:
11064       case BO_SubAssign:
11065       case BO_DivAssign:
11066       case BO_RemAssign:
11067       case BO_ShlAssign:
11068       case BO_ShrAssign:
11069       case BO_Comma:
11070         llvm_unreachable("Unexpected reduction operation");
11071       }
11072     }
11073     if (Init && DeclareReductionRef.isUnset())
11074       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11075     else if (!Init)
11076       S.ActOnUninitializedDecl(RHSVD);
11077     if (RHSVD->isInvalidDecl())
11078       continue;
11079     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
11080       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11081           << Type << ReductionIdRange;
11082       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11083                                VarDecl::DeclarationOnly;
11084       S.Diag(D->getLocation(),
11085              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11086           << D;
11087       continue;
11088     }
11089     // Store initializer for single element in private copy. Will be used during
11090     // codegen.
11091     PrivateVD->setInit(RHSVD->getInit());
11092     PrivateVD->setInitStyle(RHSVD->getInitStyle());
11093     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
11094     ExprResult ReductionOp;
11095     if (DeclareReductionRef.isUsable()) {
11096       QualType RedTy = DeclareReductionRef.get()->getType();
11097       QualType PtrRedTy = Context.getPointerType(RedTy);
11098       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11099       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
11100       if (!BasePath.empty()) {
11101         LHS = S.DefaultLvalueConversion(LHS.get());
11102         RHS = S.DefaultLvalueConversion(RHS.get());
11103         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11104                                        CK_UncheckedDerivedToBase, LHS.get(),
11105                                        &BasePath, LHS.get()->getValueKind());
11106         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11107                                        CK_UncheckedDerivedToBase, RHS.get(),
11108                                        &BasePath, RHS.get()->getValueKind());
11109       }
11110       FunctionProtoType::ExtProtoInfo EPI;
11111       QualType Params[] = {PtrRedTy, PtrRedTy};
11112       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11113       auto *OVE = new (Context) OpaqueValueExpr(
11114           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
11115           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
11116       Expr *Args[] = {LHS.get(), RHS.get()};
11117       ReductionOp = new (Context)
11118           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
11119     } else {
11120       ReductionOp = S.BuildBinOp(
11121           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
11122       if (ReductionOp.isUsable()) {
11123         if (BOK != BO_LT && BOK != BO_GT) {
11124           ReductionOp =
11125               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11126                            BO_Assign, LHSDRE, ReductionOp.get());
11127         } else {
11128           auto *ConditionalOp = new (Context)
11129               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11130                                   Type, VK_LValue, OK_Ordinary);
11131           ReductionOp =
11132               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11133                            BO_Assign, LHSDRE, ConditionalOp);
11134         }
11135         if (ReductionOp.isUsable())
11136           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
11137       }
11138       if (!ReductionOp.isUsable())
11139         continue;
11140     }
11141 
11142     // OpenMP [2.15.4.6, Restrictions, p.2]
11143     // A list item that appears in an in_reduction clause of a task construct
11144     // must appear in a task_reduction clause of a construct associated with a
11145     // taskgroup region that includes the participating task in its taskgroup
11146     // set. The construct associated with the innermost region that meets this
11147     // condition must specify the same reduction-identifier as the in_reduction
11148     // clause.
11149     if (ClauseKind == OMPC_in_reduction) {
11150       SourceRange ParentSR;
11151       BinaryOperatorKind ParentBOK;
11152       const Expr *ParentReductionOp;
11153       Expr *ParentBOKTD, *ParentReductionOpTD;
11154       DSAStackTy::DSAVarData ParentBOKDSA =
11155           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11156                                                   ParentBOKTD);
11157       DSAStackTy::DSAVarData ParentReductionOpDSA =
11158           Stack->getTopMostTaskgroupReductionData(
11159               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
11160       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11161       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11162       if (!IsParentBOK && !IsParentReductionOp) {
11163         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11164         continue;
11165       }
11166       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11167           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11168           IsParentReductionOp) {
11169         bool EmitError = true;
11170         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11171           llvm::FoldingSetNodeID RedId, ParentRedId;
11172           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11173           DeclareReductionRef.get()->Profile(RedId, Context,
11174                                              /*Canonical=*/true);
11175           EmitError = RedId != ParentRedId;
11176         }
11177         if (EmitError) {
11178           S.Diag(ReductionId.getBeginLoc(),
11179                  diag::err_omp_reduction_identifier_mismatch)
11180               << ReductionIdRange << RefExpr->getSourceRange();
11181           S.Diag(ParentSR.getBegin(),
11182                  diag::note_omp_previous_reduction_identifier)
11183               << ParentSR
11184               << (IsParentBOK ? ParentBOKDSA.RefExpr
11185                               : ParentReductionOpDSA.RefExpr)
11186                      ->getSourceRange();
11187           continue;
11188         }
11189       }
11190       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11191       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
11192     }
11193 
11194     DeclRefExpr *Ref = nullptr;
11195     Expr *VarsExpr = RefExpr->IgnoreParens();
11196     if (!VD && !S.CurContext->isDependentContext()) {
11197       if (ASE || OASE) {
11198         TransformExprToCaptures RebuildToCapture(S, D);
11199         VarsExpr =
11200             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11201         Ref = RebuildToCapture.getCapturedExpr();
11202       } else {
11203         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
11204       }
11205       if (!S.isOpenMPCapturedDecl(D)) {
11206         RD.ExprCaptures.emplace_back(Ref->getDecl());
11207         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11208           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
11209           if (!RefRes.isUsable())
11210             continue;
11211           ExprResult PostUpdateRes =
11212               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11213                            RefRes.get());
11214           if (!PostUpdateRes.isUsable())
11215             continue;
11216           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11217               Stack->getCurrentDirective() == OMPD_taskgroup) {
11218             S.Diag(RefExpr->getExprLoc(),
11219                    diag::err_omp_reduction_non_addressable_expression)
11220                 << RefExpr->getSourceRange();
11221             continue;
11222           }
11223           RD.ExprPostUpdates.emplace_back(
11224               S.IgnoredValueConversions(PostUpdateRes.get()).get());
11225         }
11226       }
11227     }
11228     // All reduction items are still marked as reduction (to do not increase
11229     // code base size).
11230     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
11231     if (CurrDir == OMPD_taskgroup) {
11232       if (DeclareReductionRef.isUsable())
11233         Stack->addTaskgroupReductionData(D, ReductionIdRange,
11234                                          DeclareReductionRef.get());
11235       else
11236         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
11237     }
11238     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11239             TaskgroupDescriptor);
11240   }
11241   return RD.Vars.empty();
11242 }
11243 
11244 OMPClause *Sema::ActOnOpenMPReductionClause(
11245     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11246     SourceLocation ColonLoc, SourceLocation EndLoc,
11247     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11248     ArrayRef<Expr *> UnresolvedReductions) {
11249   ReductionData RD(VarList.size());
11250   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
11251                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11252                                   ReductionIdScopeSpec, ReductionId,
11253                                   UnresolvedReductions, RD))
11254     return nullptr;
11255 
11256   return OMPReductionClause::Create(
11257       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11258       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11259       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11260       buildPreInits(Context, RD.ExprCaptures),
11261       buildPostUpdate(*this, RD.ExprPostUpdates));
11262 }
11263 
11264 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11265     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11266     SourceLocation ColonLoc, SourceLocation EndLoc,
11267     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11268     ArrayRef<Expr *> UnresolvedReductions) {
11269   ReductionData RD(VarList.size());
11270   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11271                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11272                                   ReductionIdScopeSpec, ReductionId,
11273                                   UnresolvedReductions, RD))
11274     return nullptr;
11275 
11276   return OMPTaskReductionClause::Create(
11277       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11278       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11279       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11280       buildPreInits(Context, RD.ExprCaptures),
11281       buildPostUpdate(*this, RD.ExprPostUpdates));
11282 }
11283 
11284 OMPClause *Sema::ActOnOpenMPInReductionClause(
11285     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11286     SourceLocation ColonLoc, SourceLocation EndLoc,
11287     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11288     ArrayRef<Expr *> UnresolvedReductions) {
11289   ReductionData RD(VarList.size());
11290   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
11291                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11292                                   ReductionIdScopeSpec, ReductionId,
11293                                   UnresolvedReductions, RD))
11294     return nullptr;
11295 
11296   return OMPInReductionClause::Create(
11297       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11298       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11299       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
11300       buildPreInits(Context, RD.ExprCaptures),
11301       buildPostUpdate(*this, RD.ExprPostUpdates));
11302 }
11303 
11304 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11305                                      SourceLocation LinLoc) {
11306   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11307       LinKind == OMPC_LINEAR_unknown) {
11308     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11309     return true;
11310   }
11311   return false;
11312 }
11313 
11314 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11315                                  OpenMPLinearClauseKind LinKind,
11316                                  QualType Type) {
11317   const auto *VD = dyn_cast_or_null<VarDecl>(D);
11318   // A variable must not have an incomplete type or a reference type.
11319   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11320     return true;
11321   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11322       !Type->isReferenceType()) {
11323     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11324         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11325     return true;
11326   }
11327   Type = Type.getNonReferenceType();
11328 
11329   // A list item must not be const-qualified.
11330   if (Type.isConstant(Context)) {
11331     Diag(ELoc, diag::err_omp_const_variable)
11332         << getOpenMPClauseName(OMPC_linear);
11333     if (D) {
11334       bool IsDecl =
11335           !VD ||
11336           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11337       Diag(D->getLocation(),
11338            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11339           << D;
11340     }
11341     return true;
11342   }
11343 
11344   // A list item must be of integral or pointer type.
11345   Type = Type.getUnqualifiedType().getCanonicalType();
11346   const auto *Ty = Type.getTypePtrOrNull();
11347   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11348               !Ty->isPointerType())) {
11349     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11350     if (D) {
11351       bool IsDecl =
11352           !VD ||
11353           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11354       Diag(D->getLocation(),
11355            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11356           << D;
11357     }
11358     return true;
11359   }
11360   return false;
11361 }
11362 
11363 OMPClause *Sema::ActOnOpenMPLinearClause(
11364     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11365     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11366     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11367   SmallVector<Expr *, 8> Vars;
11368   SmallVector<Expr *, 8> Privates;
11369   SmallVector<Expr *, 8> Inits;
11370   SmallVector<Decl *, 4> ExprCaptures;
11371   SmallVector<Expr *, 4> ExprPostUpdates;
11372   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
11373     LinKind = OMPC_LINEAR_val;
11374   for (Expr *RefExpr : VarList) {
11375     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11376     SourceLocation ELoc;
11377     SourceRange ERange;
11378     Expr *SimpleRefExpr = RefExpr;
11379     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11380     if (Res.second) {
11381       // It will be analyzed later.
11382       Vars.push_back(RefExpr);
11383       Privates.push_back(nullptr);
11384       Inits.push_back(nullptr);
11385     }
11386     ValueDecl *D = Res.first;
11387     if (!D)
11388       continue;
11389 
11390     QualType Type = D->getType();
11391     auto *VD = dyn_cast<VarDecl>(D);
11392 
11393     // OpenMP [2.14.3.7, linear clause]
11394     //  A list-item cannot appear in more than one linear clause.
11395     //  A list-item that appears in a linear clause cannot appear in any
11396     //  other data-sharing attribute clause.
11397     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
11398     if (DVar.RefExpr) {
11399       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11400                                           << getOpenMPClauseName(OMPC_linear);
11401       reportOriginalDsa(*this, DSAStack, D, DVar);
11402       continue;
11403     }
11404 
11405     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
11406       continue;
11407     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11408 
11409     // Build private copy of original var.
11410     VarDecl *Private =
11411         buildVarDecl(*this, ELoc, Type, D->getName(),
11412                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11413                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11414     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
11415     // Build var to save initial value.
11416     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
11417     Expr *InitExpr;
11418     DeclRefExpr *Ref = nullptr;
11419     if (!VD && !CurContext->isDependentContext()) {
11420       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
11421       if (!isOpenMPCapturedDecl(D)) {
11422         ExprCaptures.push_back(Ref->getDecl());
11423         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11424           ExprResult RefRes = DefaultLvalueConversion(Ref);
11425           if (!RefRes.isUsable())
11426             continue;
11427           ExprResult PostUpdateRes =
11428               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11429                          SimpleRefExpr, RefRes.get());
11430           if (!PostUpdateRes.isUsable())
11431             continue;
11432           ExprPostUpdates.push_back(
11433               IgnoredValueConversions(PostUpdateRes.get()).get());
11434         }
11435       }
11436     }
11437     if (LinKind == OMPC_LINEAR_uval)
11438       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
11439     else
11440       InitExpr = VD ? SimpleRefExpr : Ref;
11441     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
11442                          /*DirectInit=*/false);
11443     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
11444 
11445     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
11446     Vars.push_back((VD || CurContext->isDependentContext())
11447                        ? RefExpr->IgnoreParens()
11448                        : Ref);
11449     Privates.push_back(PrivateRef);
11450     Inits.push_back(InitRef);
11451   }
11452 
11453   if (Vars.empty())
11454     return nullptr;
11455 
11456   Expr *StepExpr = Step;
11457   Expr *CalcStepExpr = nullptr;
11458   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11459       !Step->isInstantiationDependent() &&
11460       !Step->containsUnexpandedParameterPack()) {
11461     SourceLocation StepLoc = Step->getBeginLoc();
11462     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
11463     if (Val.isInvalid())
11464       return nullptr;
11465     StepExpr = Val.get();
11466 
11467     // Build var to save the step value.
11468     VarDecl *SaveVar =
11469         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
11470     ExprResult SaveRef =
11471         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
11472     ExprResult CalcStep =
11473         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
11474     CalcStep = ActOnFinishFullExpr(CalcStep.get());
11475 
11476     // Warn about zero linear step (it would be probably better specified as
11477     // making corresponding variables 'const').
11478     llvm::APSInt Result;
11479     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11480     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
11481       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11482                                                      << (Vars.size() > 1);
11483     if (!IsConstant && CalcStep.isUsable()) {
11484       // Calculate the step beforehand instead of doing this on each iteration.
11485       // (This is not used if the number of iterations may be kfold-ed).
11486       CalcStepExpr = CalcStep.get();
11487     }
11488   }
11489 
11490   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11491                                  ColonLoc, EndLoc, Vars, Privates, Inits,
11492                                  StepExpr, CalcStepExpr,
11493                                  buildPreInits(Context, ExprCaptures),
11494                                  buildPostUpdate(*this, ExprPostUpdates));
11495 }
11496 
11497 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11498                                      Expr *NumIterations, Sema &SemaRef,
11499                                      Scope *S, DSAStackTy *Stack) {
11500   // Walk the vars and build update/final expressions for the CodeGen.
11501   SmallVector<Expr *, 8> Updates;
11502   SmallVector<Expr *, 8> Finals;
11503   Expr *Step = Clause.getStep();
11504   Expr *CalcStep = Clause.getCalcStep();
11505   // OpenMP [2.14.3.7, linear clause]
11506   // If linear-step is not specified it is assumed to be 1.
11507   if (!Step)
11508     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11509   else if (CalcStep)
11510     Step = cast<BinaryOperator>(CalcStep)->getLHS();
11511   bool HasErrors = false;
11512   auto CurInit = Clause.inits().begin();
11513   auto CurPrivate = Clause.privates().begin();
11514   OpenMPLinearClauseKind LinKind = Clause.getModifier();
11515   for (Expr *RefExpr : Clause.varlists()) {
11516     SourceLocation ELoc;
11517     SourceRange ERange;
11518     Expr *SimpleRefExpr = RefExpr;
11519     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
11520     ValueDecl *D = Res.first;
11521     if (Res.second || !D) {
11522       Updates.push_back(nullptr);
11523       Finals.push_back(nullptr);
11524       HasErrors = true;
11525       continue;
11526     }
11527     auto &&Info = Stack->isLoopControlVariable(D);
11528     // OpenMP [2.15.11, distribute simd Construct]
11529     // A list item may not appear in a linear clause, unless it is the loop
11530     // iteration variable.
11531     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11532         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11533       SemaRef.Diag(ELoc,
11534                    diag::err_omp_linear_distribute_var_non_loop_iteration);
11535       Updates.push_back(nullptr);
11536       Finals.push_back(nullptr);
11537       HasErrors = true;
11538       continue;
11539     }
11540     Expr *InitExpr = *CurInit;
11541 
11542     // Build privatized reference to the current linear var.
11543     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
11544     Expr *CapturedRef;
11545     if (LinKind == OMPC_LINEAR_uval)
11546       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11547     else
11548       CapturedRef =
11549           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11550                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11551                            /*RefersToCapture=*/true);
11552 
11553     // Build update: Var = InitExpr + IV * Step
11554     ExprResult Update;
11555     if (!Info.first)
11556       Update =
11557           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11558                              InitExpr, IV, Step, /* Subtract */ false);
11559     else
11560       Update = *CurPrivate;
11561     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
11562                                          /*DiscardedValue=*/true);
11563 
11564     // Build final: Var = InitExpr + NumIterations * Step
11565     ExprResult Final;
11566     if (!Info.first)
11567       Final =
11568           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11569                              InitExpr, NumIterations, Step, /*Subtract=*/false);
11570     else
11571       Final = *CurPrivate;
11572     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
11573                                         /*DiscardedValue=*/true);
11574 
11575     if (!Update.isUsable() || !Final.isUsable()) {
11576       Updates.push_back(nullptr);
11577       Finals.push_back(nullptr);
11578       HasErrors = true;
11579     } else {
11580       Updates.push_back(Update.get());
11581       Finals.push_back(Final.get());
11582     }
11583     ++CurInit;
11584     ++CurPrivate;
11585   }
11586   Clause.setUpdates(Updates);
11587   Clause.setFinals(Finals);
11588   return HasErrors;
11589 }
11590 
11591 OMPClause *Sema::ActOnOpenMPAlignedClause(
11592     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11593     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11594   SmallVector<Expr *, 8> Vars;
11595   for (Expr *RefExpr : VarList) {
11596     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11597     SourceLocation ELoc;
11598     SourceRange ERange;
11599     Expr *SimpleRefExpr = RefExpr;
11600     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11601     if (Res.second) {
11602       // It will be analyzed later.
11603       Vars.push_back(RefExpr);
11604     }
11605     ValueDecl *D = Res.first;
11606     if (!D)
11607       continue;
11608 
11609     QualType QType = D->getType();
11610     auto *VD = dyn_cast<VarDecl>(D);
11611 
11612     // OpenMP  [2.8.1, simd construct, Restrictions]
11613     // The type of list items appearing in the aligned clause must be
11614     // array, pointer, reference to array, or reference to pointer.
11615     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11616     const Type *Ty = QType.getTypePtrOrNull();
11617     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11618       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11619           << QType << getLangOpts().CPlusPlus << ERange;
11620       bool IsDecl =
11621           !VD ||
11622           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11623       Diag(D->getLocation(),
11624            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11625           << D;
11626       continue;
11627     }
11628 
11629     // OpenMP  [2.8.1, simd construct, Restrictions]
11630     // A list-item cannot appear in more than one aligned clause.
11631     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11632       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11633       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11634           << getOpenMPClauseName(OMPC_aligned);
11635       continue;
11636     }
11637 
11638     DeclRefExpr *Ref = nullptr;
11639     if (!VD && isOpenMPCapturedDecl(D))
11640       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11641     Vars.push_back(DefaultFunctionArrayConversion(
11642                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11643                        .get());
11644   }
11645 
11646   // OpenMP [2.8.1, simd construct, Description]
11647   // The parameter of the aligned clause, alignment, must be a constant
11648   // positive integer expression.
11649   // If no optional parameter is specified, implementation-defined default
11650   // alignments for SIMD instructions on the target platforms are assumed.
11651   if (Alignment != nullptr) {
11652     ExprResult AlignResult =
11653         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11654     if (AlignResult.isInvalid())
11655       return nullptr;
11656     Alignment = AlignResult.get();
11657   }
11658   if (Vars.empty())
11659     return nullptr;
11660 
11661   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11662                                   EndLoc, Vars, Alignment);
11663 }
11664 
11665 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11666                                          SourceLocation StartLoc,
11667                                          SourceLocation LParenLoc,
11668                                          SourceLocation EndLoc) {
11669   SmallVector<Expr *, 8> Vars;
11670   SmallVector<Expr *, 8> SrcExprs;
11671   SmallVector<Expr *, 8> DstExprs;
11672   SmallVector<Expr *, 8> AssignmentOps;
11673   for (Expr *RefExpr : VarList) {
11674     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11675     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11676       // It will be analyzed later.
11677       Vars.push_back(RefExpr);
11678       SrcExprs.push_back(nullptr);
11679       DstExprs.push_back(nullptr);
11680       AssignmentOps.push_back(nullptr);
11681       continue;
11682     }
11683 
11684     SourceLocation ELoc = RefExpr->getExprLoc();
11685     // OpenMP [2.1, C/C++]
11686     //  A list item is a variable name.
11687     // OpenMP  [2.14.4.1, Restrictions, p.1]
11688     //  A list item that appears in a copyin clause must be threadprivate.
11689     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
11690     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11691       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11692           << 0 << RefExpr->getSourceRange();
11693       continue;
11694     }
11695 
11696     Decl *D = DE->getDecl();
11697     auto *VD = cast<VarDecl>(D);
11698 
11699     QualType Type = VD->getType();
11700     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11701       // It will be analyzed later.
11702       Vars.push_back(DE);
11703       SrcExprs.push_back(nullptr);
11704       DstExprs.push_back(nullptr);
11705       AssignmentOps.push_back(nullptr);
11706       continue;
11707     }
11708 
11709     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11710     //  A list item that appears in a copyin clause must be threadprivate.
11711     if (!DSAStack->isThreadPrivate(VD)) {
11712       Diag(ELoc, diag::err_omp_required_access)
11713           << getOpenMPClauseName(OMPC_copyin)
11714           << getOpenMPDirectiveName(OMPD_threadprivate);
11715       continue;
11716     }
11717 
11718     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11719     //  A variable of class type (or array thereof) that appears in a
11720     //  copyin clause requires an accessible, unambiguous copy assignment
11721     //  operator for the class type.
11722     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11723     VarDecl *SrcVD =
11724         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
11725                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11726     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
11727         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11728     VarDecl *DstVD =
11729         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
11730                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11731     DeclRefExpr *PseudoDstExpr =
11732         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11733     // For arrays generate assignment operation for single element and replace
11734     // it by the original array element in CodeGen.
11735     ExprResult AssignmentOp =
11736         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
11737                    PseudoSrcExpr);
11738     if (AssignmentOp.isInvalid())
11739       continue;
11740     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11741                                        /*DiscardedValue=*/true);
11742     if (AssignmentOp.isInvalid())
11743       continue;
11744 
11745     DSAStack->addDSA(VD, DE, OMPC_copyin);
11746     Vars.push_back(DE);
11747     SrcExprs.push_back(PseudoSrcExpr);
11748     DstExprs.push_back(PseudoDstExpr);
11749     AssignmentOps.push_back(AssignmentOp.get());
11750   }
11751 
11752   if (Vars.empty())
11753     return nullptr;
11754 
11755   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11756                                  SrcExprs, DstExprs, AssignmentOps);
11757 }
11758 
11759 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11760                                               SourceLocation StartLoc,
11761                                               SourceLocation LParenLoc,
11762                                               SourceLocation EndLoc) {
11763   SmallVector<Expr *, 8> Vars;
11764   SmallVector<Expr *, 8> SrcExprs;
11765   SmallVector<Expr *, 8> DstExprs;
11766   SmallVector<Expr *, 8> AssignmentOps;
11767   for (Expr *RefExpr : VarList) {
11768     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11769     SourceLocation ELoc;
11770     SourceRange ERange;
11771     Expr *SimpleRefExpr = RefExpr;
11772     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11773     if (Res.second) {
11774       // It will be analyzed later.
11775       Vars.push_back(RefExpr);
11776       SrcExprs.push_back(nullptr);
11777       DstExprs.push_back(nullptr);
11778       AssignmentOps.push_back(nullptr);
11779     }
11780     ValueDecl *D = Res.first;
11781     if (!D)
11782       continue;
11783 
11784     QualType Type = D->getType();
11785     auto *VD = dyn_cast<VarDecl>(D);
11786 
11787     // OpenMP [2.14.4.2, Restrictions, p.2]
11788     //  A list item that appears in a copyprivate clause may not appear in a
11789     //  private or firstprivate clause on the single construct.
11790     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11791       DSAStackTy::DSAVarData DVar =
11792           DSAStack->getTopDSA(D, /*FromParent=*/false);
11793       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11794           DVar.RefExpr) {
11795         Diag(ELoc, diag::err_omp_wrong_dsa)
11796             << getOpenMPClauseName(DVar.CKind)
11797             << getOpenMPClauseName(OMPC_copyprivate);
11798         reportOriginalDsa(*this, DSAStack, D, DVar);
11799         continue;
11800       }
11801 
11802       // OpenMP [2.11.4.2, Restrictions, p.1]
11803       //  All list items that appear in a copyprivate clause must be either
11804       //  threadprivate or private in the enclosing context.
11805       if (DVar.CKind == OMPC_unknown) {
11806         DVar = DSAStack->getImplicitDSA(D, false);
11807         if (DVar.CKind == OMPC_shared) {
11808           Diag(ELoc, diag::err_omp_required_access)
11809               << getOpenMPClauseName(OMPC_copyprivate)
11810               << "threadprivate or private in the enclosing context";
11811           reportOriginalDsa(*this, DSAStack, D, DVar);
11812           continue;
11813         }
11814       }
11815     }
11816 
11817     // Variably modified types are not supported.
11818     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11819       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11820           << getOpenMPClauseName(OMPC_copyprivate) << Type
11821           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11822       bool IsDecl =
11823           !VD ||
11824           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11825       Diag(D->getLocation(),
11826            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11827           << D;
11828       continue;
11829     }
11830 
11831     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11832     //  A variable of class type (or array thereof) that appears in a
11833     //  copyin clause requires an accessible, unambiguous copy assignment
11834     //  operator for the class type.
11835     Type = Context.getBaseElementType(Type.getNonReferenceType())
11836                .getUnqualifiedType();
11837     VarDecl *SrcVD =
11838         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
11839                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11840     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11841     VarDecl *DstVD =
11842         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
11843                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11844     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11845     ExprResult AssignmentOp = BuildBinOp(
11846         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
11847     if (AssignmentOp.isInvalid())
11848       continue;
11849     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
11850                                        /*DiscardedValue=*/true);
11851     if (AssignmentOp.isInvalid())
11852       continue;
11853 
11854     // No need to mark vars as copyprivate, they are already threadprivate or
11855     // implicitly private.
11856     assert(VD || isOpenMPCapturedDecl(D));
11857     Vars.push_back(
11858         VD ? RefExpr->IgnoreParens()
11859            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
11860     SrcExprs.push_back(PseudoSrcExpr);
11861     DstExprs.push_back(PseudoDstExpr);
11862     AssignmentOps.push_back(AssignmentOp.get());
11863   }
11864 
11865   if (Vars.empty())
11866     return nullptr;
11867 
11868   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11869                                       Vars, SrcExprs, DstExprs, AssignmentOps);
11870 }
11871 
11872 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11873                                         SourceLocation StartLoc,
11874                                         SourceLocation LParenLoc,
11875                                         SourceLocation EndLoc) {
11876   if (VarList.empty())
11877     return nullptr;
11878 
11879   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11880 }
11881 
11882 OMPClause *
11883 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11884                               SourceLocation DepLoc, SourceLocation ColonLoc,
11885                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11886                               SourceLocation LParenLoc, SourceLocation EndLoc) {
11887   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
11888       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
11889     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11890         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
11891     return nullptr;
11892   }
11893   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
11894       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11895        DepKind == OMPC_DEPEND_sink)) {
11896     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
11897     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11898         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11899                                    /*Last=*/OMPC_DEPEND_unknown, Except)
11900         << getOpenMPClauseName(OMPC_depend);
11901     return nullptr;
11902   }
11903   SmallVector<Expr *, 8> Vars;
11904   DSAStackTy::OperatorOffsetTy OpsOffs;
11905   llvm::APSInt DepCounter(/*BitWidth=*/32);
11906   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11907   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
11908     if (const Expr *OrderedCountExpr =
11909             DSAStack->getParentOrderedRegionParam().first) {
11910       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11911       TotalDepCount.setIsUnsigned(/*Val=*/true);
11912     }
11913   }
11914   for (Expr *RefExpr : VarList) {
11915     assert(RefExpr && "NULL expr in OpenMP shared clause.");
11916     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11917       // It will be analyzed later.
11918       Vars.push_back(RefExpr);
11919       continue;
11920     }
11921 
11922     SourceLocation ELoc = RefExpr->getExprLoc();
11923     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
11924     if (DepKind == OMPC_DEPEND_sink) {
11925       if (DSAStack->getParentOrderedRegionParam().first &&
11926           DepCounter >= TotalDepCount) {
11927         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11928         continue;
11929       }
11930       ++DepCounter;
11931       // OpenMP  [2.13.9, Summary]
11932       // depend(dependence-type : vec), where dependence-type is:
11933       // 'sink' and where vec is the iteration vector, which has the form:
11934       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11935       // where n is the value specified by the ordered clause in the loop
11936       // directive, xi denotes the loop iteration variable of the i-th nested
11937       // loop associated with the loop directive, and di is a constant
11938       // non-negative integer.
11939       if (CurContext->isDependentContext()) {
11940         // It will be analyzed later.
11941         Vars.push_back(RefExpr);
11942         continue;
11943       }
11944       SimpleExpr = SimpleExpr->IgnoreImplicit();
11945       OverloadedOperatorKind OOK = OO_None;
11946       SourceLocation OOLoc;
11947       Expr *LHS = SimpleExpr;
11948       Expr *RHS = nullptr;
11949       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11950         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11951         OOLoc = BO->getOperatorLoc();
11952         LHS = BO->getLHS()->IgnoreParenImpCasts();
11953         RHS = BO->getRHS()->IgnoreParenImpCasts();
11954       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11955         OOK = OCE->getOperator();
11956         OOLoc = OCE->getOperatorLoc();
11957         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11958         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11959       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11960         OOK = MCE->getMethodDecl()
11961                   ->getNameInfo()
11962                   .getName()
11963                   .getCXXOverloadedOperator();
11964         OOLoc = MCE->getCallee()->getExprLoc();
11965         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11966         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11967       }
11968       SourceLocation ELoc;
11969       SourceRange ERange;
11970       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
11971       if (Res.second) {
11972         // It will be analyzed later.
11973         Vars.push_back(RefExpr);
11974       }
11975       ValueDecl *D = Res.first;
11976       if (!D)
11977         continue;
11978 
11979       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11980         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11981         continue;
11982       }
11983       if (RHS) {
11984         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11985             RHS, OMPC_depend, /*StrictlyPositive=*/false);
11986         if (RHSRes.isInvalid())
11987           continue;
11988       }
11989       if (!CurContext->isDependentContext() &&
11990           DSAStack->getParentOrderedRegionParam().first &&
11991           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11992         const ValueDecl *VD =
11993             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11994         if (VD)
11995           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11996               << 1 << VD;
11997         else
11998           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11999         continue;
12000       }
12001       OpsOffs.emplace_back(RHS, OOK);
12002     } else {
12003       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12004       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12005           (ASE &&
12006            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12007            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12008         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12009             << RefExpr->getSourceRange();
12010         continue;
12011       }
12012       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12013       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12014       ExprResult Res =
12015           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12016       getDiagnostics().setSuppressAllDiagnostics(Suppress);
12017       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12018         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12019             << RefExpr->getSourceRange();
12020         continue;
12021       }
12022     }
12023     Vars.push_back(RefExpr->IgnoreParenImpCasts());
12024   }
12025 
12026   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12027       TotalDepCount > VarList.size() &&
12028       DSAStack->getParentOrderedRegionParam().first &&
12029       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12030     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12031         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12032   }
12033   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12034       Vars.empty())
12035     return nullptr;
12036 
12037   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12038                                     DepKind, DepLoc, ColonLoc, Vars,
12039                                     TotalDepCount.getZExtValue());
12040   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12041       DSAStack->isParentOrderedRegion())
12042     DSAStack->addDoacrossDependClause(C, OpsOffs);
12043   return C;
12044 }
12045 
12046 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12047                                          SourceLocation LParenLoc,
12048                                          SourceLocation EndLoc) {
12049   Expr *ValExpr = Device;
12050   Stmt *HelperValStmt = nullptr;
12051 
12052   // OpenMP [2.9.1, Restrictions]
12053   // The device expression must evaluate to a non-negative integer value.
12054   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
12055                                  /*StrictlyPositive=*/false))
12056     return nullptr;
12057 
12058   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12059   OpenMPDirectiveKind CaptureRegion =
12060       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12061   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12062     ValExpr = MakeFullExpr(ValExpr).get();
12063     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12064     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12065     HelperValStmt = buildPreInits(Context, Captures);
12066   }
12067 
12068   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12069                                        StartLoc, LParenLoc, EndLoc);
12070 }
12071 
12072 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
12073                               DSAStackTy *Stack, QualType QTy,
12074                               bool FullCheck = true) {
12075   NamedDecl *ND;
12076   if (QTy->isIncompleteType(&ND)) {
12077     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12078     return false;
12079   }
12080   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12081       !QTy.isTrivialType(SemaRef.Context))
12082     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
12083   return true;
12084 }
12085 
12086 /// Return true if it can be proven that the provided array expression
12087 /// (array section or array subscript) does NOT specify the whole size of the
12088 /// array whose base type is \a BaseQTy.
12089 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
12090                                                         const Expr *E,
12091                                                         QualType BaseQTy) {
12092   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12093 
12094   // If this is an array subscript, it refers to the whole size if the size of
12095   // the dimension is constant and equals 1. Also, an array section assumes the
12096   // format of an array subscript if no colon is used.
12097   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
12098     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12099       return ATy->getSize().getSExtValue() != 1;
12100     // Size can't be evaluated statically.
12101     return false;
12102   }
12103 
12104   assert(OASE && "Expecting array section if not an array subscript.");
12105   const Expr *LowerBound = OASE->getLowerBound();
12106   const Expr *Length = OASE->getLength();
12107 
12108   // If there is a lower bound that does not evaluates to zero, we are not
12109   // covering the whole dimension.
12110   if (LowerBound) {
12111     llvm::APSInt ConstLowerBound;
12112     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
12113       return false; // Can't get the integer value as a constant.
12114     if (ConstLowerBound.getSExtValue())
12115       return true;
12116   }
12117 
12118   // If we don't have a length we covering the whole dimension.
12119   if (!Length)
12120     return false;
12121 
12122   // If the base is a pointer, we don't have a way to get the size of the
12123   // pointee.
12124   if (BaseQTy->isPointerType())
12125     return false;
12126 
12127   // We can only check if the length is the same as the size of the dimension
12128   // if we have a constant array.
12129   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
12130   if (!CATy)
12131     return false;
12132 
12133   llvm::APSInt ConstLength;
12134   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
12135     return false; // Can't get the integer value as a constant.
12136 
12137   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12138 }
12139 
12140 // Return true if it can be proven that the provided array expression (array
12141 // section or array subscript) does NOT specify a single element of the array
12142 // whose base type is \a BaseQTy.
12143 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
12144                                                         const Expr *E,
12145                                                         QualType BaseQTy) {
12146   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12147 
12148   // An array subscript always refer to a single element. Also, an array section
12149   // assumes the format of an array subscript if no colon is used.
12150   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12151     return false;
12152 
12153   assert(OASE && "Expecting array section if not an array subscript.");
12154   const Expr *Length = OASE->getLength();
12155 
12156   // If we don't have a length we have to check if the array has unitary size
12157   // for this dimension. Also, we should always expect a length if the base type
12158   // is pointer.
12159   if (!Length) {
12160     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12161       return ATy->getSize().getSExtValue() != 1;
12162     // We cannot assume anything.
12163     return false;
12164   }
12165 
12166   // Check if the length evaluates to 1.
12167   llvm::APSInt ConstLength;
12168   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
12169     return false; // Can't get the integer value as a constant.
12170 
12171   return ConstLength.getSExtValue() != 1;
12172 }
12173 
12174 // Return the expression of the base of the mappable expression or null if it
12175 // cannot be determined and do all the necessary checks to see if the expression
12176 // is valid as a standalone mappable expression. In the process, record all the
12177 // components of the expression.
12178 static const Expr *checkMapClauseExpressionBase(
12179     Sema &SemaRef, Expr *E,
12180     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
12181     OpenMPClauseKind CKind, bool NoDiagnose) {
12182   SourceLocation ELoc = E->getExprLoc();
12183   SourceRange ERange = E->getSourceRange();
12184 
12185   // The base of elements of list in a map clause have to be either:
12186   //  - a reference to variable or field.
12187   //  - a member expression.
12188   //  - an array expression.
12189   //
12190   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12191   // reference to 'r'.
12192   //
12193   // If we have:
12194   //
12195   // struct SS {
12196   //   Bla S;
12197   //   foo() {
12198   //     #pragma omp target map (S.Arr[:12]);
12199   //   }
12200   // }
12201   //
12202   // We want to retrieve the member expression 'this->S';
12203 
12204   const Expr *RelevantExpr = nullptr;
12205 
12206   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12207   //  If a list item is an array section, it must specify contiguous storage.
12208   //
12209   // For this restriction it is sufficient that we make sure only references
12210   // to variables or fields and array expressions, and that no array sections
12211   // exist except in the rightmost expression (unless they cover the whole
12212   // dimension of the array). E.g. these would be invalid:
12213   //
12214   //   r.ArrS[3:5].Arr[6:7]
12215   //
12216   //   r.ArrS[3:5].x
12217   //
12218   // but these would be valid:
12219   //   r.ArrS[3].Arr[6:7]
12220   //
12221   //   r.ArrS[3].x
12222 
12223   bool AllowUnitySizeArraySection = true;
12224   bool AllowWholeSizeArraySection = true;
12225 
12226   while (!RelevantExpr) {
12227     E = E->IgnoreParenImpCasts();
12228 
12229     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12230       if (!isa<VarDecl>(CurE->getDecl()))
12231         return nullptr;
12232 
12233       RelevantExpr = CurE;
12234 
12235       // If we got a reference to a declaration, we should not expect any array
12236       // section before that.
12237       AllowUnitySizeArraySection = false;
12238       AllowWholeSizeArraySection = false;
12239 
12240       // Record the component.
12241       CurComponents.emplace_back(CurE, CurE->getDecl());
12242     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
12243       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
12244 
12245       if (isa<CXXThisExpr>(BaseE))
12246         // We found a base expression: this->Val.
12247         RelevantExpr = CurE;
12248       else
12249         E = BaseE;
12250 
12251       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
12252         if (!NoDiagnose) {
12253           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12254               << CurE->getSourceRange();
12255           return nullptr;
12256         }
12257         if (RelevantExpr)
12258           return nullptr;
12259         continue;
12260       }
12261 
12262       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12263 
12264       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12265       //  A bit-field cannot appear in a map clause.
12266       //
12267       if (FD->isBitField()) {
12268         if (!NoDiagnose) {
12269           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12270               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12271           return nullptr;
12272         }
12273         if (RelevantExpr)
12274           return nullptr;
12275         continue;
12276       }
12277 
12278       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12279       //  If the type of a list item is a reference to a type T then the type
12280       //  will be considered to be T for all purposes of this clause.
12281       QualType CurType = BaseE->getType().getNonReferenceType();
12282 
12283       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12284       //  A list item cannot be a variable that is a member of a structure with
12285       //  a union type.
12286       //
12287       if (CurType->isUnionType()) {
12288         if (!NoDiagnose) {
12289           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12290               << CurE->getSourceRange();
12291           return nullptr;
12292         }
12293         continue;
12294       }
12295 
12296       // If we got a member expression, we should not expect any array section
12297       // before that:
12298       //
12299       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12300       //  If a list item is an element of a structure, only the rightmost symbol
12301       //  of the variable reference can be an array section.
12302       //
12303       AllowUnitySizeArraySection = false;
12304       AllowWholeSizeArraySection = false;
12305 
12306       // Record the component.
12307       CurComponents.emplace_back(CurE, FD);
12308     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
12309       E = CurE->getBase()->IgnoreParenImpCasts();
12310 
12311       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
12312         if (!NoDiagnose) {
12313           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12314               << 0 << CurE->getSourceRange();
12315           return nullptr;
12316         }
12317         continue;
12318       }
12319 
12320       // If we got an array subscript that express the whole dimension we
12321       // can have any array expressions before. If it only expressing part of
12322       // the dimension, we can only have unitary-size array expressions.
12323       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
12324                                                       E->getType()))
12325         AllowWholeSizeArraySection = false;
12326 
12327       // Record the component - we don't have any declaration associated.
12328       CurComponents.emplace_back(CurE, nullptr);
12329     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
12330       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
12331       E = CurE->getBase()->IgnoreParenImpCasts();
12332 
12333       QualType CurType =
12334           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12335 
12336       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12337       //  If the type of a list item is a reference to a type T then the type
12338       //  will be considered to be T for all purposes of this clause.
12339       if (CurType->isReferenceType())
12340         CurType = CurType->getPointeeType();
12341 
12342       bool IsPointer = CurType->isAnyPointerType();
12343 
12344       if (!IsPointer && !CurType->isArrayType()) {
12345         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12346             << 0 << CurE->getSourceRange();
12347         return nullptr;
12348       }
12349 
12350       bool NotWhole =
12351           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
12352       bool NotUnity =
12353           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
12354 
12355       if (AllowWholeSizeArraySection) {
12356         // Any array section is currently allowed. Allowing a whole size array
12357         // section implies allowing a unity array section as well.
12358         //
12359         // If this array section refers to the whole dimension we can still
12360         // accept other array sections before this one, except if the base is a
12361         // pointer. Otherwise, only unitary sections are accepted.
12362         if (NotWhole || IsPointer)
12363           AllowWholeSizeArraySection = false;
12364       } else if (AllowUnitySizeArraySection && NotUnity) {
12365         // A unity or whole array section is not allowed and that is not
12366         // compatible with the properties of the current array section.
12367         SemaRef.Diag(
12368             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12369             << CurE->getSourceRange();
12370         return nullptr;
12371       }
12372 
12373       // Record the component - we don't have any declaration associated.
12374       CurComponents.emplace_back(CurE, nullptr);
12375     } else {
12376       if (!NoDiagnose) {
12377         // If nothing else worked, this is not a valid map clause expression.
12378         SemaRef.Diag(
12379             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12380             << ERange;
12381       }
12382       return nullptr;
12383     }
12384   }
12385 
12386   return RelevantExpr;
12387 }
12388 
12389 // Return true if expression E associated with value VD has conflicts with other
12390 // map information.
12391 static bool checkMapConflicts(
12392     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
12393     bool CurrentRegionOnly,
12394     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12395     OpenMPClauseKind CKind) {
12396   assert(VD && E);
12397   SourceLocation ELoc = E->getExprLoc();
12398   SourceRange ERange = E->getSourceRange();
12399 
12400   // In order to easily check the conflicts we need to match each component of
12401   // the expression under test with the components of the expressions that are
12402   // already in the stack.
12403 
12404   assert(!CurComponents.empty() && "Map clause expression with no components!");
12405   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
12406          "Map clause expression with unexpected base!");
12407 
12408   // Variables to help detecting enclosing problems in data environment nests.
12409   bool IsEnclosedByDataEnvironmentExpr = false;
12410   const Expr *EnclosingExpr = nullptr;
12411 
12412   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12413       VD, CurrentRegionOnly,
12414       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12415        ERange, CKind, &EnclosingExpr,
12416        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12417                           StackComponents,
12418                       OpenMPClauseKind) {
12419         assert(!StackComponents.empty() &&
12420                "Map clause expression with no components!");
12421         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
12422                "Map clause expression with unexpected base!");
12423         (void)VD;
12424 
12425         // The whole expression in the stack.
12426         const Expr *RE = StackComponents.front().getAssociatedExpression();
12427 
12428         // Expressions must start from the same base. Here we detect at which
12429         // point both expressions diverge from each other and see if we can
12430         // detect if the memory referred to both expressions is contiguous and
12431         // do not overlap.
12432         auto CI = CurComponents.rbegin();
12433         auto CE = CurComponents.rend();
12434         auto SI = StackComponents.rbegin();
12435         auto SE = StackComponents.rend();
12436         for (; CI != CE && SI != SE; ++CI, ++SI) {
12437 
12438           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12439           //  At most one list item can be an array item derived from a given
12440           //  variable in map clauses of the same construct.
12441           if (CurrentRegionOnly &&
12442               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12443                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12444               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12445                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12446             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
12447                          diag::err_omp_multiple_array_items_in_map_clause)
12448                 << CI->getAssociatedExpression()->getSourceRange();
12449             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12450                          diag::note_used_here)
12451                 << SI->getAssociatedExpression()->getSourceRange();
12452             return true;
12453           }
12454 
12455           // Do both expressions have the same kind?
12456           if (CI->getAssociatedExpression()->getStmtClass() !=
12457               SI->getAssociatedExpression()->getStmtClass())
12458             break;
12459 
12460           // Are we dealing with different variables/fields?
12461           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
12462             break;
12463         }
12464         // Check if the extra components of the expressions in the enclosing
12465         // data environment are redundant for the current base declaration.
12466         // If they are, the maps completely overlap, which is legal.
12467         for (; SI != SE; ++SI) {
12468           QualType Type;
12469           if (const auto *ASE =
12470                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
12471             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
12472           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
12473                          SI->getAssociatedExpression())) {
12474             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
12475             Type =
12476                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12477           }
12478           if (Type.isNull() || Type->isAnyPointerType() ||
12479               checkArrayExpressionDoesNotReferToWholeSize(
12480                   SemaRef, SI->getAssociatedExpression(), Type))
12481             break;
12482         }
12483 
12484         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12485         //  List items of map clauses in the same construct must not share
12486         //  original storage.
12487         //
12488         // If the expressions are exactly the same or one is a subset of the
12489         // other, it means they are sharing storage.
12490         if (CI == CE && SI == SE) {
12491           if (CurrentRegionOnly) {
12492             if (CKind == OMPC_map) {
12493               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12494             } else {
12495               assert(CKind == OMPC_to || CKind == OMPC_from);
12496               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12497                   << ERange;
12498             }
12499             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12500                 << RE->getSourceRange();
12501             return true;
12502           }
12503           // If we find the same expression in the enclosing data environment,
12504           // that is legal.
12505           IsEnclosedByDataEnvironmentExpr = true;
12506           return false;
12507         }
12508 
12509         QualType DerivedType =
12510             std::prev(CI)->getAssociatedDeclaration()->getType();
12511         SourceLocation DerivedLoc =
12512             std::prev(CI)->getAssociatedExpression()->getExprLoc();
12513 
12514         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12515         //  If the type of a list item is a reference to a type T then the type
12516         //  will be considered to be T for all purposes of this clause.
12517         DerivedType = DerivedType.getNonReferenceType();
12518 
12519         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12520         //  A variable for which the type is pointer and an array section
12521         //  derived from that variable must not appear as list items of map
12522         //  clauses of the same construct.
12523         //
12524         // Also, cover one of the cases in:
12525         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12526         //  If any part of the original storage of a list item has corresponding
12527         //  storage in the device data environment, all of the original storage
12528         //  must have corresponding storage in the device data environment.
12529         //
12530         if (DerivedType->isAnyPointerType()) {
12531           if (CI == CE || SI == SE) {
12532             SemaRef.Diag(
12533                 DerivedLoc,
12534                 diag::err_omp_pointer_mapped_along_with_derived_section)
12535                 << DerivedLoc;
12536             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12537                 << RE->getSourceRange();
12538             return true;
12539           }
12540           if (CI->getAssociatedExpression()->getStmtClass() !=
12541                          SI->getAssociatedExpression()->getStmtClass() ||
12542                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12543                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
12544             assert(CI != CE && SI != SE);
12545             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
12546                 << DerivedLoc;
12547             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12548                 << RE->getSourceRange();
12549             return true;
12550           }
12551         }
12552 
12553         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12554         //  List items of map clauses in the same construct must not share
12555         //  original storage.
12556         //
12557         // An expression is a subset of the other.
12558         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
12559           if (CKind == OMPC_map) {
12560             if (CI != CE || SI != SE) {
12561               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12562               // a pointer.
12563               auto Begin =
12564                   CI != CE ? CurComponents.begin() : StackComponents.begin();
12565               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12566               auto It = Begin;
12567               while (It != End && !It->getAssociatedDeclaration())
12568                 std::advance(It, 1);
12569               assert(It != End &&
12570                      "Expected at least one component with the declaration.");
12571               if (It != Begin && It->getAssociatedDeclaration()
12572                                      ->getType()
12573                                      .getCanonicalType()
12574                                      ->isAnyPointerType()) {
12575                 IsEnclosedByDataEnvironmentExpr = false;
12576                 EnclosingExpr = nullptr;
12577                 return false;
12578               }
12579             }
12580             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12581           } else {
12582             assert(CKind == OMPC_to || CKind == OMPC_from);
12583             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12584                 << ERange;
12585           }
12586           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12587               << RE->getSourceRange();
12588           return true;
12589         }
12590 
12591         // The current expression uses the same base as other expression in the
12592         // data environment but does not contain it completely.
12593         if (!CurrentRegionOnly && SI != SE)
12594           EnclosingExpr = RE;
12595 
12596         // The current expression is a subset of the expression in the data
12597         // environment.
12598         IsEnclosedByDataEnvironmentExpr |=
12599             (!CurrentRegionOnly && CI != CE && SI == SE);
12600 
12601         return false;
12602       });
12603 
12604   if (CurrentRegionOnly)
12605     return FoundError;
12606 
12607   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12608   //  If any part of the original storage of a list item has corresponding
12609   //  storage in the device data environment, all of the original storage must
12610   //  have corresponding storage in the device data environment.
12611   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12612   //  If a list item is an element of a structure, and a different element of
12613   //  the structure has a corresponding list item in the device data environment
12614   //  prior to a task encountering the construct associated with the map clause,
12615   //  then the list item must also have a corresponding list item in the device
12616   //  data environment prior to the task encountering the construct.
12617   //
12618   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12619     SemaRef.Diag(ELoc,
12620                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12621         << ERange;
12622     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12623         << EnclosingExpr->getSourceRange();
12624     return true;
12625   }
12626 
12627   return FoundError;
12628 }
12629 
12630 namespace {
12631 // Utility struct that gathers all the related lists associated with a mappable
12632 // expression.
12633 struct MappableVarListInfo {
12634   // The list of expressions.
12635   ArrayRef<Expr *> VarList;
12636   // The list of processed expressions.
12637   SmallVector<Expr *, 16> ProcessedVarList;
12638   // The mappble components for each expression.
12639   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12640   // The base declaration of the variable.
12641   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12642 
12643   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12644     // We have a list of components and base declarations for each entry in the
12645     // variable list.
12646     VarComponents.reserve(VarList.size());
12647     VarBaseDeclarations.reserve(VarList.size());
12648   }
12649 };
12650 }
12651 
12652 // Check the validity of the provided variable list for the provided clause kind
12653 // \a CKind. In the check process the valid expressions, and mappable expression
12654 // components and variables are extracted and used to fill \a Vars,
12655 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12656 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12657 static void
12658 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12659                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12660                             SourceLocation StartLoc,
12661                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12662                             bool IsMapTypeImplicit = false) {
12663   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12664   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12665          "Unexpected clause kind with mappable expressions!");
12666 
12667   // Keep track of the mappable components and base declarations in this clause.
12668   // Each entry in the list is going to have a list of components associated. We
12669   // record each set of the components so that we can build the clause later on.
12670   // In the end we should have the same amount of declarations and component
12671   // lists.
12672 
12673   for (Expr *RE : MVLI.VarList) {
12674     assert(RE && "Null expr in omp to/from/map clause");
12675     SourceLocation ELoc = RE->getExprLoc();
12676 
12677     const Expr *VE = RE->IgnoreParenLValueCasts();
12678 
12679     if (VE->isValueDependent() || VE->isTypeDependent() ||
12680         VE->isInstantiationDependent() ||
12681         VE->containsUnexpandedParameterPack()) {
12682       // We can only analyze this information once the missing information is
12683       // resolved.
12684       MVLI.ProcessedVarList.push_back(RE);
12685       continue;
12686     }
12687 
12688     Expr *SimpleExpr = RE->IgnoreParenCasts();
12689 
12690     if (!RE->IgnoreParenImpCasts()->isLValue()) {
12691       SemaRef.Diag(ELoc,
12692                    diag::err_omp_expected_named_var_member_or_array_expression)
12693           << RE->getSourceRange();
12694       continue;
12695     }
12696 
12697     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12698     ValueDecl *CurDeclaration = nullptr;
12699 
12700     // Obtain the array or member expression bases if required. Also, fill the
12701     // components array with all the components identified in the process.
12702     const Expr *BE = checkMapClauseExpressionBase(
12703         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
12704     if (!BE)
12705       continue;
12706 
12707     assert(!CurComponents.empty() &&
12708            "Invalid mappable expression information.");
12709 
12710     // For the following checks, we rely on the base declaration which is
12711     // expected to be associated with the last component. The declaration is
12712     // expected to be a variable or a field (if 'this' is being mapped).
12713     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12714     assert(CurDeclaration && "Null decl on map clause.");
12715     assert(
12716         CurDeclaration->isCanonicalDecl() &&
12717         "Expecting components to have associated only canonical declarations.");
12718 
12719     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12720     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
12721 
12722     assert((VD || FD) && "Only variables or fields are expected here!");
12723     (void)FD;
12724 
12725     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
12726     // threadprivate variables cannot appear in a map clause.
12727     // OpenMP 4.5 [2.10.5, target update Construct]
12728     // threadprivate variables cannot appear in a from clause.
12729     if (VD && DSAS->isThreadPrivate(VD)) {
12730       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12731       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12732           << getOpenMPClauseName(CKind);
12733       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
12734       continue;
12735     }
12736 
12737     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12738     //  A list item cannot appear in both a map clause and a data-sharing
12739     //  attribute clause on the same construct.
12740 
12741     // Check conflicts with other map clause expressions. We check the conflicts
12742     // with the current construct separately from the enclosing data
12743     // environment, because the restrictions are different. We only have to
12744     // check conflicts across regions for the map clauses.
12745     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12746                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
12747       break;
12748     if (CKind == OMPC_map &&
12749         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12750                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
12751       break;
12752 
12753     // OpenMP 4.5 [2.10.5, target update Construct]
12754     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12755     //  If the type of a list item is a reference to a type T then the type will
12756     //  be considered to be T for all purposes of this clause.
12757     auto I = llvm::find_if(
12758         CurComponents,
12759         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
12760           return MC.getAssociatedDeclaration();
12761         });
12762     assert(I != CurComponents.end() && "Null decl on map clause.");
12763     QualType Type =
12764         I->getAssociatedDeclaration()->getType().getNonReferenceType();
12765 
12766     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12767     // A list item in a to or from clause must have a mappable type.
12768     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12769     //  A list item must have a mappable type.
12770     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12771                            DSAS, Type))
12772       continue;
12773 
12774     if (CKind == OMPC_map) {
12775       // target enter data
12776       // OpenMP [2.10.2, Restrictions, p. 99]
12777       // A map-type must be specified in all map clauses and must be either
12778       // to or alloc.
12779       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12780       if (DKind == OMPD_target_enter_data &&
12781           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12782         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12783             << (IsMapTypeImplicit ? 1 : 0)
12784             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12785             << getOpenMPDirectiveName(DKind);
12786         continue;
12787       }
12788 
12789       // target exit_data
12790       // OpenMP [2.10.3, Restrictions, p. 102]
12791       // A map-type must be specified in all map clauses and must be either
12792       // from, release, or delete.
12793       if (DKind == OMPD_target_exit_data &&
12794           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12795             MapType == OMPC_MAP_delete)) {
12796         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12797             << (IsMapTypeImplicit ? 1 : 0)
12798             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12799             << getOpenMPDirectiveName(DKind);
12800         continue;
12801       }
12802 
12803       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12804       // A list item cannot appear in both a map clause and a data-sharing
12805       // attribute clause on the same construct
12806       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
12807         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12808         if (isOpenMPPrivate(DVar.CKind)) {
12809           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12810               << getOpenMPClauseName(DVar.CKind)
12811               << getOpenMPClauseName(OMPC_map)
12812               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12813           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
12814           continue;
12815         }
12816       }
12817     }
12818 
12819     // Save the current expression.
12820     MVLI.ProcessedVarList.push_back(RE);
12821 
12822     // Store the components in the stack so that they can be used to check
12823     // against other clauses later on.
12824     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12825                                           /*WhereFoundClauseKind=*/OMPC_map);
12826 
12827     // Save the components and declaration to create the clause. For purposes of
12828     // the clause creation, any component list that has has base 'this' uses
12829     // null as base declaration.
12830     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12831     MVLI.VarComponents.back().append(CurComponents.begin(),
12832                                      CurComponents.end());
12833     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12834                                                            : CurDeclaration);
12835   }
12836 }
12837 
12838 OMPClause *
12839 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12840                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12841                            SourceLocation MapLoc, SourceLocation ColonLoc,
12842                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12843                            SourceLocation LParenLoc, SourceLocation EndLoc) {
12844   MappableVarListInfo MVLI(VarList);
12845   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12846                               MapType, IsMapTypeImplicit);
12847 
12848   // We need to produce a map clause even if we don't have variables so that
12849   // other diagnostics related with non-existing map clauses are accurate.
12850   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12851                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12852                               MVLI.VarComponents, MapTypeModifier, MapType,
12853                               IsMapTypeImplicit, MapLoc);
12854 }
12855 
12856 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12857                                                TypeResult ParsedType) {
12858   assert(ParsedType.isUsable());
12859 
12860   QualType ReductionType = GetTypeFromParser(ParsedType.get());
12861   if (ReductionType.isNull())
12862     return QualType();
12863 
12864   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12865   // A type name in a declare reduction directive cannot be a function type, an
12866   // array type, a reference type, or a type qualified with const, volatile or
12867   // restrict.
12868   if (ReductionType.hasQualifiers()) {
12869     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12870     return QualType();
12871   }
12872 
12873   if (ReductionType->isFunctionType()) {
12874     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12875     return QualType();
12876   }
12877   if (ReductionType->isReferenceType()) {
12878     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12879     return QualType();
12880   }
12881   if (ReductionType->isArrayType()) {
12882     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12883     return QualType();
12884   }
12885   return ReductionType;
12886 }
12887 
12888 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12889     Scope *S, DeclContext *DC, DeclarationName Name,
12890     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12891     AccessSpecifier AS, Decl *PrevDeclInScope) {
12892   SmallVector<Decl *, 8> Decls;
12893   Decls.reserve(ReductionTypes.size());
12894 
12895   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
12896                       forRedeclarationInCurContext());
12897   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12898   // A reduction-identifier may not be re-declared in the current scope for the
12899   // same type or for a type that is compatible according to the base language
12900   // rules.
12901   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12902   OMPDeclareReductionDecl *PrevDRD = nullptr;
12903   bool InCompoundScope = true;
12904   if (S != nullptr) {
12905     // Find previous declaration with the same name not referenced in other
12906     // declarations.
12907     FunctionScopeInfo *ParentFn = getEnclosingFunction();
12908     InCompoundScope =
12909         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12910     LookupName(Lookup, S);
12911     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12912                          /*AllowInlineNamespace=*/false);
12913     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12914     LookupResult::Filter Filter = Lookup.makeFilter();
12915     while (Filter.hasNext()) {
12916       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12917       if (InCompoundScope) {
12918         auto I = UsedAsPrevious.find(PrevDecl);
12919         if (I == UsedAsPrevious.end())
12920           UsedAsPrevious[PrevDecl] = false;
12921         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
12922           UsedAsPrevious[D] = true;
12923       }
12924       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12925           PrevDecl->getLocation();
12926     }
12927     Filter.done();
12928     if (InCompoundScope) {
12929       for (const auto &PrevData : UsedAsPrevious) {
12930         if (!PrevData.second) {
12931           PrevDRD = PrevData.first;
12932           break;
12933         }
12934       }
12935     }
12936   } else if (PrevDeclInScope != nullptr) {
12937     auto *PrevDRDInScope = PrevDRD =
12938         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12939     do {
12940       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12941           PrevDRDInScope->getLocation();
12942       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12943     } while (PrevDRDInScope != nullptr);
12944   }
12945   for (const auto &TyData : ReductionTypes) {
12946     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12947     bool Invalid = false;
12948     if (I != PreviousRedeclTypes.end()) {
12949       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12950           << TyData.first;
12951       Diag(I->second, diag::note_previous_definition);
12952       Invalid = true;
12953     }
12954     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12955     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12956                                                 Name, TyData.first, PrevDRD);
12957     DC->addDecl(DRD);
12958     DRD->setAccess(AS);
12959     Decls.push_back(DRD);
12960     if (Invalid)
12961       DRD->setInvalidDecl();
12962     else
12963       PrevDRD = DRD;
12964   }
12965 
12966   return DeclGroupPtrTy::make(
12967       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12968 }
12969 
12970 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12971   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12972 
12973   // Enter new function scope.
12974   PushFunctionScope();
12975   setFunctionHasBranchProtectedScope();
12976   getCurFunction()->setHasOMPDeclareReductionCombiner();
12977 
12978   if (S != nullptr)
12979     PushDeclContext(S, DRD);
12980   else
12981     CurContext = DRD;
12982 
12983   PushExpressionEvaluationContext(
12984       ExpressionEvaluationContext::PotentiallyEvaluated);
12985 
12986   QualType ReductionType = DRD->getType();
12987   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12988   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12989   // uses semantics of argument handles by value, but it should be passed by
12990   // reference. C lang does not support references, so pass all parameters as
12991   // pointers.
12992   // Create 'T omp_in;' variable.
12993   VarDecl *OmpInParm =
12994       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
12995   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12996   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12997   // uses semantics of argument handles by value, but it should be passed by
12998   // reference. C lang does not support references, so pass all parameters as
12999   // pointers.
13000   // Create 'T omp_out;' variable.
13001   VarDecl *OmpOutParm =
13002       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13003   if (S != nullptr) {
13004     PushOnScopeChains(OmpInParm, S);
13005     PushOnScopeChains(OmpOutParm, S);
13006   } else {
13007     DRD->addDecl(OmpInParm);
13008     DRD->addDecl(OmpOutParm);
13009   }
13010   Expr *InE =
13011       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13012   Expr *OutE =
13013       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13014   DRD->setCombinerData(InE, OutE);
13015 }
13016 
13017 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13018   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13019   DiscardCleanupsInEvaluationContext();
13020   PopExpressionEvaluationContext();
13021 
13022   PopDeclContext();
13023   PopFunctionScopeInfo();
13024 
13025   if (Combiner != nullptr)
13026     DRD->setCombiner(Combiner);
13027   else
13028     DRD->setInvalidDecl();
13029 }
13030 
13031 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
13032   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13033 
13034   // Enter new function scope.
13035   PushFunctionScope();
13036   setFunctionHasBranchProtectedScope();
13037 
13038   if (S != nullptr)
13039     PushDeclContext(S, DRD);
13040   else
13041     CurContext = DRD;
13042 
13043   PushExpressionEvaluationContext(
13044       ExpressionEvaluationContext::PotentiallyEvaluated);
13045 
13046   QualType ReductionType = DRD->getType();
13047   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13048   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13049   // uses semantics of argument handles by value, but it should be passed by
13050   // reference. C lang does not support references, so pass all parameters as
13051   // pointers.
13052   // Create 'T omp_priv;' variable.
13053   VarDecl *OmpPrivParm =
13054       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
13055   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13056   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13057   // uses semantics of argument handles by value, but it should be passed by
13058   // reference. C lang does not support references, so pass all parameters as
13059   // pointers.
13060   // Create 'T omp_orig;' variable.
13061   VarDecl *OmpOrigParm =
13062       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
13063   if (S != nullptr) {
13064     PushOnScopeChains(OmpPrivParm, S);
13065     PushOnScopeChains(OmpOrigParm, S);
13066   } else {
13067     DRD->addDecl(OmpPrivParm);
13068     DRD->addDecl(OmpOrigParm);
13069   }
13070   Expr *OrigE =
13071       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13072   Expr *PrivE =
13073       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13074   DRD->setInitializerData(OrigE, PrivE);
13075   return OmpPrivParm;
13076 }
13077 
13078 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13079                                                      VarDecl *OmpPrivParm) {
13080   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13081   DiscardCleanupsInEvaluationContext();
13082   PopExpressionEvaluationContext();
13083 
13084   PopDeclContext();
13085   PopFunctionScopeInfo();
13086 
13087   if (Initializer != nullptr) {
13088     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13089   } else if (OmpPrivParm->hasInit()) {
13090     DRD->setInitializer(OmpPrivParm->getInit(),
13091                         OmpPrivParm->isDirectInit()
13092                             ? OMPDeclareReductionDecl::DirectInit
13093                             : OMPDeclareReductionDecl::CopyInit);
13094   } else {
13095     DRD->setInvalidDecl();
13096   }
13097 }
13098 
13099 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13100     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
13101   for (Decl *D : DeclReductions.get()) {
13102     if (IsValid) {
13103       if (S)
13104         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13105                           /*AddToContext=*/false);
13106     } else {
13107       D->setInvalidDecl();
13108     }
13109   }
13110   return DeclReductions;
13111 }
13112 
13113 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
13114                                            SourceLocation StartLoc,
13115                                            SourceLocation LParenLoc,
13116                                            SourceLocation EndLoc) {
13117   Expr *ValExpr = NumTeams;
13118   Stmt *HelperValStmt = nullptr;
13119 
13120   // OpenMP [teams Constrcut, Restrictions]
13121   // The num_teams expression must evaluate to a positive integer value.
13122   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
13123                                  /*StrictlyPositive=*/true))
13124     return nullptr;
13125 
13126   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13127   OpenMPDirectiveKind CaptureRegion =
13128       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13129   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13130     ValExpr = MakeFullExpr(ValExpr).get();
13131     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13132     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13133     HelperValStmt = buildPreInits(Context, Captures);
13134   }
13135 
13136   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13137                                          StartLoc, LParenLoc, EndLoc);
13138 }
13139 
13140 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13141                                               SourceLocation StartLoc,
13142                                               SourceLocation LParenLoc,
13143                                               SourceLocation EndLoc) {
13144   Expr *ValExpr = ThreadLimit;
13145   Stmt *HelperValStmt = nullptr;
13146 
13147   // OpenMP [teams Constrcut, Restrictions]
13148   // The thread_limit expression must evaluate to a positive integer value.
13149   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
13150                                  /*StrictlyPositive=*/true))
13151     return nullptr;
13152 
13153   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13154   OpenMPDirectiveKind CaptureRegion =
13155       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13156   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13157     ValExpr = MakeFullExpr(ValExpr).get();
13158     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13159     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13160     HelperValStmt = buildPreInits(Context, Captures);
13161   }
13162 
13163   return new (Context) OMPThreadLimitClause(
13164       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13165 }
13166 
13167 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13168                                            SourceLocation StartLoc,
13169                                            SourceLocation LParenLoc,
13170                                            SourceLocation EndLoc) {
13171   Expr *ValExpr = Priority;
13172 
13173   // OpenMP [2.9.1, task Constrcut]
13174   // The priority-value is a non-negative numerical scalar expression.
13175   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
13176                                  /*StrictlyPositive=*/false))
13177     return nullptr;
13178 
13179   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13180 }
13181 
13182 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13183                                             SourceLocation StartLoc,
13184                                             SourceLocation LParenLoc,
13185                                             SourceLocation EndLoc) {
13186   Expr *ValExpr = Grainsize;
13187 
13188   // OpenMP [2.9.2, taskloop Constrcut]
13189   // The parameter of the grainsize clause must be a positive integer
13190   // expression.
13191   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
13192                                  /*StrictlyPositive=*/true))
13193     return nullptr;
13194 
13195   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13196 }
13197 
13198 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13199                                            SourceLocation StartLoc,
13200                                            SourceLocation LParenLoc,
13201                                            SourceLocation EndLoc) {
13202   Expr *ValExpr = NumTasks;
13203 
13204   // OpenMP [2.9.2, taskloop Constrcut]
13205   // The parameter of the num_tasks clause must be a positive integer
13206   // expression.
13207   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
13208                                  /*StrictlyPositive=*/true))
13209     return nullptr;
13210 
13211   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13212 }
13213 
13214 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13215                                        SourceLocation LParenLoc,
13216                                        SourceLocation EndLoc) {
13217   // OpenMP [2.13.2, critical construct, Description]
13218   // ... where hint-expression is an integer constant expression that evaluates
13219   // to a valid lock hint.
13220   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13221   if (HintExpr.isInvalid())
13222     return nullptr;
13223   return new (Context)
13224       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13225 }
13226 
13227 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13228     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13229     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13230     SourceLocation EndLoc) {
13231   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13232     std::string Values;
13233     Values += "'";
13234     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13235     Values += "'";
13236     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13237         << Values << getOpenMPClauseName(OMPC_dist_schedule);
13238     return nullptr;
13239   }
13240   Expr *ValExpr = ChunkSize;
13241   Stmt *HelperValStmt = nullptr;
13242   if (ChunkSize) {
13243     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13244         !ChunkSize->isInstantiationDependent() &&
13245         !ChunkSize->containsUnexpandedParameterPack()) {
13246       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13247       ExprResult Val =
13248           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13249       if (Val.isInvalid())
13250         return nullptr;
13251 
13252       ValExpr = Val.get();
13253 
13254       // OpenMP [2.7.1, Restrictions]
13255       //  chunk_size must be a loop invariant integer expression with a positive
13256       //  value.
13257       llvm::APSInt Result;
13258       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13259         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13260           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13261               << "dist_schedule" << ChunkSize->getSourceRange();
13262           return nullptr;
13263         }
13264       } else if (getOpenMPCaptureRegionForClause(
13265                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13266                      OMPD_unknown &&
13267                  !CurContext->isDependentContext()) {
13268         ValExpr = MakeFullExpr(ValExpr).get();
13269         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13270         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13271         HelperValStmt = buildPreInits(Context, Captures);
13272       }
13273     }
13274   }
13275 
13276   return new (Context)
13277       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
13278                             Kind, ValExpr, HelperValStmt);
13279 }
13280 
13281 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13282     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13283     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13284     SourceLocation KindLoc, SourceLocation EndLoc) {
13285   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
13286   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
13287     std::string Value;
13288     SourceLocation Loc;
13289     Value += "'";
13290     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
13291       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13292                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
13293       Loc = MLoc;
13294     } else {
13295       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13296                                              OMPC_DEFAULTMAP_scalar);
13297       Loc = KindLoc;
13298     }
13299     Value += "'";
13300     Diag(Loc, diag::err_omp_unexpected_clause_value)
13301         << Value << getOpenMPClauseName(OMPC_defaultmap);
13302     return nullptr;
13303   }
13304   DSAStack->setDefaultDMAToFromScalar(StartLoc);
13305 
13306   return new (Context)
13307       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
13308 }
13309 
13310 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
13311   DeclContext *CurLexicalContext = getCurLexicalContext();
13312   if (!CurLexicalContext->isFileContext() &&
13313       !CurLexicalContext->isExternCContext() &&
13314       !CurLexicalContext->isExternCXXContext() &&
13315       !isa<CXXRecordDecl>(CurLexicalContext) &&
13316       !isa<ClassTemplateDecl>(CurLexicalContext) &&
13317       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
13318       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
13319     Diag(Loc, diag::err_omp_region_not_file_context);
13320     return false;
13321   }
13322   ++DeclareTargetNestingLevel;
13323   return true;
13324 }
13325 
13326 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
13327   assert(DeclareTargetNestingLevel > 0 &&
13328          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
13329   --DeclareTargetNestingLevel;
13330 }
13331 
13332 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
13333                                         CXXScopeSpec &ScopeSpec,
13334                                         const DeclarationNameInfo &Id,
13335                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
13336                                         NamedDeclSetType &SameDirectiveDecls) {
13337   LookupResult Lookup(*this, Id, LookupOrdinaryName);
13338   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
13339 
13340   if (Lookup.isAmbiguous())
13341     return;
13342   Lookup.suppressDiagnostics();
13343 
13344   if (!Lookup.isSingleResult()) {
13345     if (TypoCorrection Corrected =
13346             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
13347                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
13348                         CTK_ErrorRecovery)) {
13349       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
13350                                   << Id.getName());
13351       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
13352       return;
13353     }
13354 
13355     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
13356     return;
13357   }
13358 
13359   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
13360   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
13361       isa<FunctionTemplateDecl>(ND)) {
13362     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
13363       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
13364     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13365         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
13366             cast<ValueDecl>(ND));
13367     if (!Res) {
13368       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
13369       ND->addAttr(A);
13370       if (ASTMutationListener *ML = Context.getASTMutationListener())
13371         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
13372       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
13373     } else if (*Res != MT) {
13374       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
13375           << Id.getName();
13376     }
13377   } else {
13378     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
13379   }
13380 }
13381 
13382 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
13383                                      Sema &SemaRef, Decl *D) {
13384   if (!D || !isa<VarDecl>(D))
13385     return;
13386   auto *VD = cast<VarDecl>(D);
13387   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13388     return;
13389   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
13390   SemaRef.Diag(SL, diag::note_used_here) << SR;
13391 }
13392 
13393 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
13394                                    Sema &SemaRef, DSAStackTy *Stack,
13395                                    ValueDecl *VD) {
13396   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
13397          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
13398                            /*FullCheck=*/false);
13399 }
13400 
13401 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13402                                             SourceLocation IdLoc) {
13403   if (!D || D->isInvalidDecl())
13404     return;
13405   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13406   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
13407   if (auto *VD = dyn_cast<VarDecl>(D)) {
13408     // Only global variables can be marked as declare target.
13409     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
13410         !VD->isStaticDataMember())
13411       return;
13412     // 2.10.6: threadprivate variable cannot appear in a declare target
13413     // directive.
13414     if (DSAStack->isThreadPrivate(VD)) {
13415       Diag(SL, diag::err_omp_threadprivate_in_target);
13416       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
13417       return;
13418     }
13419   }
13420   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
13421     D = FTD->getTemplatedDecl();
13422   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13423     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13424         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
13425     if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
13426       assert(IdLoc.isValid() && "Source location is expected");
13427       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13428       Diag(FD->getLocation(), diag::note_defined_here) << FD;
13429       return;
13430     }
13431   }
13432   if (auto *VD = dyn_cast<ValueDecl>(D)) {
13433     // Problem if any with var declared with incomplete type will be reported
13434     // as normal, so no need to check it here.
13435     if ((E || !VD->getType()->isIncompleteType()) &&
13436         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
13437       return;
13438     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
13439       // Checking declaration inside declare target region.
13440       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13441           isa<FunctionTemplateDecl>(D)) {
13442         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13443             Context, OMPDeclareTargetDeclAttr::MT_To);
13444         D->addAttr(A);
13445         if (ASTMutationListener *ML = Context.getASTMutationListener())
13446           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13447       }
13448       return;
13449     }
13450   }
13451   if (!E)
13452     return;
13453   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13454 }
13455 
13456 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13457                                      SourceLocation StartLoc,
13458                                      SourceLocation LParenLoc,
13459                                      SourceLocation EndLoc) {
13460   MappableVarListInfo MVLI(VarList);
13461   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13462   if (MVLI.ProcessedVarList.empty())
13463     return nullptr;
13464 
13465   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13466                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13467                              MVLI.VarComponents);
13468 }
13469 
13470 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13471                                        SourceLocation StartLoc,
13472                                        SourceLocation LParenLoc,
13473                                        SourceLocation EndLoc) {
13474   MappableVarListInfo MVLI(VarList);
13475   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13476   if (MVLI.ProcessedVarList.empty())
13477     return nullptr;
13478 
13479   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13480                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13481                                MVLI.VarComponents);
13482 }
13483 
13484 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13485                                                SourceLocation StartLoc,
13486                                                SourceLocation LParenLoc,
13487                                                SourceLocation EndLoc) {
13488   MappableVarListInfo MVLI(VarList);
13489   SmallVector<Expr *, 8> PrivateCopies;
13490   SmallVector<Expr *, 8> Inits;
13491 
13492   for (Expr *RefExpr : VarList) {
13493     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13494     SourceLocation ELoc;
13495     SourceRange ERange;
13496     Expr *SimpleRefExpr = RefExpr;
13497     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13498     if (Res.second) {
13499       // It will be analyzed later.
13500       MVLI.ProcessedVarList.push_back(RefExpr);
13501       PrivateCopies.push_back(nullptr);
13502       Inits.push_back(nullptr);
13503     }
13504     ValueDecl *D = Res.first;
13505     if (!D)
13506       continue;
13507 
13508     QualType Type = D->getType();
13509     Type = Type.getNonReferenceType().getUnqualifiedType();
13510 
13511     auto *VD = dyn_cast<VarDecl>(D);
13512 
13513     // Item should be a pointer or reference to pointer.
13514     if (!Type->isPointerType()) {
13515       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13516           << 0 << RefExpr->getSourceRange();
13517       continue;
13518     }
13519 
13520     // Build the private variable and the expression that refers to it.
13521     auto VDPrivate =
13522         buildVarDecl(*this, ELoc, Type, D->getName(),
13523                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13524                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13525     if (VDPrivate->isInvalidDecl())
13526       continue;
13527 
13528     CurContext->addDecl(VDPrivate);
13529     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13530         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13531 
13532     // Add temporary variable to initialize the private copy of the pointer.
13533     VarDecl *VDInit =
13534         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13535     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
13536         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
13537     AddInitializerToDecl(VDPrivate,
13538                          DefaultLvalueConversion(VDInitRefExpr).get(),
13539                          /*DirectInit=*/false);
13540 
13541     // If required, build a capture to implement the privatization initialized
13542     // with the current list item value.
13543     DeclRefExpr *Ref = nullptr;
13544     if (!VD)
13545       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13546     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13547     PrivateCopies.push_back(VDPrivateRefExpr);
13548     Inits.push_back(VDInitRefExpr);
13549 
13550     // We need to add a data sharing attribute for this variable to make sure it
13551     // is correctly captured. A variable that shows up in a use_device_ptr has
13552     // similar properties of a first private variable.
13553     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13554 
13555     // Create a mappable component for the list item. List items in this clause
13556     // only need a component.
13557     MVLI.VarBaseDeclarations.push_back(D);
13558     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13559     MVLI.VarComponents.back().push_back(
13560         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
13561   }
13562 
13563   if (MVLI.ProcessedVarList.empty())
13564     return nullptr;
13565 
13566   return OMPUseDevicePtrClause::Create(
13567       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13568       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
13569 }
13570 
13571 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13572                                               SourceLocation StartLoc,
13573                                               SourceLocation LParenLoc,
13574                                               SourceLocation EndLoc) {
13575   MappableVarListInfo MVLI(VarList);
13576   for (Expr *RefExpr : VarList) {
13577     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
13578     SourceLocation ELoc;
13579     SourceRange ERange;
13580     Expr *SimpleRefExpr = RefExpr;
13581     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13582     if (Res.second) {
13583       // It will be analyzed later.
13584       MVLI.ProcessedVarList.push_back(RefExpr);
13585     }
13586     ValueDecl *D = Res.first;
13587     if (!D)
13588       continue;
13589 
13590     QualType Type = D->getType();
13591     // item should be a pointer or array or reference to pointer or array
13592     if (!Type.getNonReferenceType()->isPointerType() &&
13593         !Type.getNonReferenceType()->isArrayType()) {
13594       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13595           << 0 << RefExpr->getSourceRange();
13596       continue;
13597     }
13598 
13599     // Check if the declaration in the clause does not show up in any data
13600     // sharing attribute.
13601     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13602     if (isOpenMPPrivate(DVar.CKind)) {
13603       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13604           << getOpenMPClauseName(DVar.CKind)
13605           << getOpenMPClauseName(OMPC_is_device_ptr)
13606           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13607       reportOriginalDsa(*this, DSAStack, D, DVar);
13608       continue;
13609     }
13610 
13611     const Expr *ConflictExpr;
13612     if (DSAStack->checkMappableExprComponentListsForDecl(
13613             D, /*CurrentRegionOnly=*/true,
13614             [&ConflictExpr](
13615                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13616                 OpenMPClauseKind) -> bool {
13617               ConflictExpr = R.front().getAssociatedExpression();
13618               return true;
13619             })) {
13620       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13621       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13622           << ConflictExpr->getSourceRange();
13623       continue;
13624     }
13625 
13626     // Store the components in the stack so that they can be used to check
13627     // against other clauses later on.
13628     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13629     DSAStack->addMappableExpressionComponents(
13630         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13631 
13632     // Record the expression we've just processed.
13633     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13634 
13635     // Create a mappable component for the list item. List items in this clause
13636     // only need a component. We use a null declaration to signal fields in
13637     // 'this'.
13638     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13639             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13640            "Unexpected device pointer expression!");
13641     MVLI.VarBaseDeclarations.push_back(
13642         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13643     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13644     MVLI.VarComponents.back().push_back(MC);
13645   }
13646 
13647   if (MVLI.ProcessedVarList.empty())
13648     return nullptr;
13649 
13650   return OMPIsDevicePtrClause::Create(
13651       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13652       MVLI.VarBaseDeclarations, MVLI.VarComponents);
13653 }
13654